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 const EXT_LINK_URL_CLASS
= '(?:[^\]\[<>"\\x00-\\x20\\x7F]|(?:\[\]))';
72 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
73 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
75 # State constants for the definition list colon extraction
76 const COLON_STATE_TEXT
= 0;
77 const COLON_STATE_TAG
= 1;
78 const COLON_STATE_TAGSTART
= 2;
79 const COLON_STATE_CLOSETAG
= 3;
80 const COLON_STATE_TAGSLASH
= 4;
81 const COLON_STATE_COMMENT
= 5;
82 const COLON_STATE_COMMENTDASH
= 6;
83 const COLON_STATE_COMMENTDASHDASH
= 7;
85 # Flags for preprocessToDom
86 const PTD_FOR_INCLUSION
= 1;
88 # Allowed values for $this->mOutputType
89 # Parameter to startExternalParse().
90 const OT_HTML
= 1; # like parse()
91 const OT_WIKI
= 2; # like preSaveTransform()
92 const OT_PREPROCESS
= 3; # like preprocess()
94 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
96 # Marker Suffix needs to be accessible staticly.
97 const MARKER_SUFFIX
= "-QINU\x7f";
100 var $mTagHooks = array();
101 var $mTransparentTagHooks = array();
102 var $mFunctionHooks = array();
103 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
104 var $mFunctionTagHooks = array();
105 var $mStripList = array();
106 var $mDefaultStripList = array();
107 var $mVarCache = array();
108 var $mImageParams = array();
109 var $mImageParamsMagicArray = array();
110 var $mMarkerIndex = 0;
111 var $mFirstCall = true;
113 # Initialised by initialiseVariables()
117 * @var MagicWordArray
120 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
122 # Cleared with clearState():
127 var $mAutonumber, $mDTopen;
134 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
136 * @var LinkHolderArray
141 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
142 var $mTplExpandCache; # empty-frame expansion cache
143 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
144 var $mExpensiveFunctionCount; # number of expensive parser function calls
149 var $mUser; # User object; only used when doing pre-save transform
152 # These are variables reset at least once per parse regardless of $clearState
162 var $mTitle; # Title context, used for self-link rendering and similar things
163 var $mOutputType; # Output type, one of the OT_xxx constants
164 var $ot; # Shortcut alias, see setOutputType()
165 var $mRevisionObject; # The revision object of the specified revision ID
166 var $mRevisionId; # ID to display in {{REVISIONID}} tags
167 var $mRevisionTimestamp; # The timestamp of the specified revision ID
168 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
169 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
174 public function __construct( $conf = array() ) {
175 $this->mConf
= $conf;
176 $this->mUrlProtocols
= wfUrlProtocols();
177 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
178 '(?:[^\]\[<>"\x00-\x20\x7F]|\[\])+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
179 if ( isset( $conf['preprocessorClass'] ) ) {
180 $this->mPreprocessorClass
= $conf['preprocessorClass'];
181 } elseif ( extension_loaded( 'domxml' ) ) {
182 # PECL extension that conflicts with the core DOM extension (bug 13770)
183 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
184 $this->mPreprocessorClass
= 'Preprocessor_Hash';
185 } elseif ( extension_loaded( 'dom' ) ) {
186 $this->mPreprocessorClass
= 'Preprocessor_DOM';
188 $this->mPreprocessorClass
= 'Preprocessor_Hash';
193 * Reduce memory usage to reduce the impact of circular references
195 function __destruct() {
196 if ( isset( $this->mLinkHolders
) ) {
197 unset( $this->mLinkHolders
);
199 foreach ( $this as $name => $value ) {
200 unset( $this->$name );
205 * Do various kinds of initialisation on the first call of the parser
207 function firstCallInit() {
208 if ( !$this->mFirstCall
) {
211 $this->mFirstCall
= false;
213 wfProfileIn( __METHOD__
);
215 CoreParserFunctions
::register( $this );
216 CoreTagHooks
::register( $this );
217 $this->initialiseVariables();
219 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
220 wfProfileOut( __METHOD__
);
228 function clearState() {
229 wfProfileIn( __METHOD__
);
230 if ( $this->mFirstCall
) {
231 $this->firstCallInit();
233 $this->mOutput
= new ParserOutput
;
234 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
235 $this->mAutonumber
= 0;
236 $this->mLastSection
= '';
237 $this->mDTopen
= false;
238 $this->mIncludeCount
= array();
239 $this->mArgStack
= false;
240 $this->mInPre
= false;
241 $this->mLinkHolders
= new LinkHolderArray( $this );
243 $this->mRevisionObject
= $this->mRevisionTimestamp
=
244 $this->mRevisionId
= $this->mRevisionUser
= null;
245 $this->mVarCache
= array();
249 * Prefix for temporary replacement strings for the multipass parser.
250 * \x07 should never appear in input as it's disallowed in XML.
251 * Using it at the front also gives us a little extra robustness
252 * since it shouldn't match when butted up against identifier-like
255 * Must not consist of all title characters, or else it will change
256 * the behaviour of <nowiki> in a link.
258 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
259 # Changed to \x7f to allow XML double-parsing -- TS
260 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
261 $this->mStripState
= new StripState( $this->mUniqPrefix
);
264 # Clear these on every parse, bug 4549
265 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
267 $this->mShowToc
= true;
268 $this->mForceTocPosition
= false;
269 $this->mIncludeSizes
= array(
273 $this->mPPNodeCount
= 0;
274 $this->mDefaultSort
= false;
275 $this->mHeadings
= array();
276 $this->mDoubleUnderscores
= array();
277 $this->mExpensiveFunctionCount
= 0;
280 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
281 $this->mPreprocessor
= null;
284 wfRunHooks( 'ParserClearState', array( &$this ) );
285 wfProfileOut( __METHOD__
);
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title Title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
311 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
313 $oldRevisionId = $this->mRevisionId
;
314 $oldRevisionObject = $this->mRevisionObject
;
315 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
316 $oldRevisionUser = $this->mRevisionUser
;
317 if ( $revid !== null ) {
318 $this->mRevisionId
= $revid;
319 $this->mRevisionObject
= null;
320 $this->mRevisionTimestamp
= null;
321 $this->mRevisionUser
= null;
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
327 $text = $this->internalParse( $text );
329 $text = $this->mStripState
->unstripGeneral( $text );
331 # Clean up special characters, only run once, next-to-last before doBlockLevels
333 # french spaces, last one Guillemet-left
334 # only if there is something before the space
335 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
336 # french spaces, Guillemet-right
337 '/(\\302\\253) /' => '\\1 ',
338 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
340 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
342 $text = $this->doBlockLevels( $text, $linestart );
344 $this->replaceLinkHolders( $text );
347 * The page doesn't get language converted if
349 * b) Content isn't converted
350 * c) It's a conversion table
352 if ( !( $wgDisableLangConversion
353 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
354 ||
$this->mTitle
->isConversionTable() ) ) {
356 # The position of the convert() call should not be changed. it
357 # assumes that the links are all replaced and the only thing left
358 # is the <nowiki> mark.
360 $text = $wgContLang->convert( $text );
364 * A converted title will be provided in the output object if title and
365 * content conversion are enabled, the article text does not contain
366 * a conversion-suppressing double-underscore tag, and no
367 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
368 * automatic link conversion.
370 if ( !( $wgDisableLangConversion
371 ||
$wgDisableTitleConversion
372 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
373 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
374 ||
$this->mOutput
->getDisplayTitle() !== false ) )
376 $convruletitle = $wgContLang->getConvRuleTitle();
377 if ( $convruletitle ) {
378 $this->mOutput
->setTitleText( $convruletitle );
380 $titleText = $wgContLang->convertTitle( $title );
381 $this->mOutput
->setTitleText( $titleText );
385 $text = $this->mStripState
->unstripNoWiki( $text );
387 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
389 $text = $this->replaceTransparentTags( $text );
390 $text = $this->mStripState
->unstripGeneral( $text );
392 $text = Sanitizer
::normalizeCharReferences( $text );
394 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
395 $text = MWTidy
::tidy( $text );
397 # attempt to sanitize at least some nesting problems
398 # (bug #2702 and quite a few others)
400 # ''Something [http://www.cool.com cool''] -->
401 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
402 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
403 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
404 # fix up an anchor inside another anchor, only
405 # at least for a single single nested link (bug 3695)
406 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
407 '\\1\\2</a>\\3</a>\\1\\4</a>',
408 # fix div inside inline elements- doBlockLevels won't wrap a line which
409 # contains a div, so fix it up here; replace
410 # div with escaped text
411 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
412 '\\1\\3<div\\5>\\6</div>\\8\\9',
413 # remove empty italic or bold tag pairs, some
414 # introduced by rules above
415 '/<([bi])><\/\\1>/' => '',
418 $text = preg_replace(
419 array_keys( $tidyregs ),
420 array_values( $tidyregs ),
423 global $wgExpensiveParserFunctionLimit;
424 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
425 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
428 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
430 # Information on include size limits, for the benefit of users who try to skirt them
431 if ( $this->mOptions
->getEnableLimitReport() ) {
432 $max = $this->mOptions
->getMaxIncludeSize();
433 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
435 "NewPP limit report\n" .
436 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
437 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
438 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
440 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
441 $text .= "\n<!-- \n$limitReport-->\n";
443 $this->mOutput
->setText( $text );
445 $this->mRevisionId
= $oldRevisionId;
446 $this->mRevisionObject
= $oldRevisionObject;
447 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
448 $this->mRevisionUser
= $oldRevisionUser;
449 wfProfileOut( $fname );
450 wfProfileOut( __METHOD__
);
452 return $this->mOutput
;
456 * Recursive parser entry point that can be called from an extension tag
459 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
461 * @param $text String: text extension wants to have parsed
462 * @param $frame PPFrame: The frame to use for expanding any template variables
464 function recursiveTagParse( $text, $frame=false ) {
465 wfProfileIn( __METHOD__
);
466 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
467 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
468 $text = $this->internalParse( $text, false, $frame );
469 wfProfileOut( __METHOD__
);
474 * Expand templates and variables in the text, producing valid, static wikitext.
475 * Also removes comments.
477 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
478 wfProfileIn( __METHOD__
);
479 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
480 if ( $revid !== null ) {
481 $this->mRevisionId
= $revid;
483 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
484 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
485 $text = $this->replaceVariables( $text );
486 $text = $this->mStripState
->unstripBoth( $text );
487 wfProfileOut( __METHOD__
);
492 * Process the wikitext for the ?preload= feature. (bug 5210)
494 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
495 * comments, templates, arguments, tags hooks and parser functions are untouched.
497 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
498 # Parser (re)initialisation
499 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
501 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
502 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
503 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
504 $text = $this->mStripState
->unstripBoth( $text );
509 * Get a random string
511 static public function getRandomString() {
512 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
516 * Set the current user.
517 * Should only be used when doing pre-save transform.
519 * @param $user Mixed: User object or null (to reset)
521 function setUser( $user ) {
522 $this->mUser
= $user;
526 * Accessor for mUniqPrefix.
530 public function uniqPrefix() {
531 if ( !isset( $this->mUniqPrefix
) ) {
532 # @todo FIXME: This is probably *horribly wrong*
533 # LanguageConverter seems to want $wgParser's uniqPrefix, however
534 # if this is called for a parser cache hit, the parser may not
535 # have ever been initialized in the first place.
536 # Not really sure what the heck is supposed to be going on here.
538 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
540 return $this->mUniqPrefix
;
544 * Set the context title
546 function setTitle( $t ) {
547 if ( !$t ||
$t instanceof FakeTitle
) {
548 $t = Title
::newFromText( 'NO TITLE' );
551 if ( strval( $t->getFragment() ) !== '' ) {
552 # Strip the fragment to avoid various odd effects
553 $this->mTitle
= clone $t;
554 $this->mTitle
->setFragment( '' );
561 * Accessor for the Title object
563 * @return Title object
565 function getTitle() {
566 return $this->mTitle
;
570 * Accessor/mutator for the Title object
572 * @param $x New Title object or null to just get the current one
573 * @return Title object
575 function Title( $x = null ) {
576 return wfSetVar( $this->mTitle
, $x );
580 * Set the output type
582 * @param $ot Integer: new value
584 function setOutputType( $ot ) {
585 $this->mOutputType
= $ot;
588 'html' => $ot == self
::OT_HTML
,
589 'wiki' => $ot == self
::OT_WIKI
,
590 'pre' => $ot == self
::OT_PREPROCESS
,
591 'plain' => $ot == self
::OT_PLAIN
,
596 * Accessor/mutator for the output type
598 * @param $x New value or null to just get the current one
601 function OutputType( $x = null ) {
602 return wfSetVar( $this->mOutputType
, $x );
606 * Get the ParserOutput object
608 * @return ParserOutput object
610 function getOutput() {
611 return $this->mOutput
;
615 * Get the ParserOptions object
617 * @return ParserOptions object
619 function getOptions() {
620 return $this->mOptions
;
624 * Accessor/mutator for the ParserOptions object
626 * @param $x New value or null to just get the current one
627 * @return Current ParserOptions object
629 function Options( $x = null ) {
630 return wfSetVar( $this->mOptions
, $x );
633 function nextLinkID() {
634 return $this->mLinkID++
;
637 function setLinkID( $id ) {
638 $this->mLinkID
= $id;
644 function getFunctionLang() {
645 global $wgLang, $wgContLang;
647 $target = $this->mOptions
->getTargetLanguage();
648 if ( $target !== null ) {
651 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
656 * Get a User object either from $this->mUser, if set, or from the
657 * ParserOptions object otherwise
659 * @return User object
662 if ( !is_null( $this->mUser
) ) {
665 return $this->mOptions
->getUser();
669 * Get a preprocessor object
671 * @return Preprocessor instance
673 function getPreprocessor() {
674 if ( !isset( $this->mPreprocessor
) ) {
675 $class = $this->mPreprocessorClass
;
676 $this->mPreprocessor
= new $class( $this );
678 return $this->mPreprocessor
;
682 * Replaces all occurrences of HTML-style comments and the given tags
683 * in the text with a random marker and returns the next text. The output
684 * parameter $matches will be an associative array filled with data in
686 * 'UNIQ-xxxxx' => array(
689 * array( 'param' => 'x' ),
690 * '<element param="x">tag content</element>' ) )
692 * @param $elements list of element names. Comments are always extracted.
693 * @param $text Source text string.
694 * @param $matches Out parameter, Array: extracted tags
695 * @param $uniq_prefix
696 * @return String: stripped text
698 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
703 $taglist = implode( '|', $elements );
704 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
706 while ( $text != '' ) {
707 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
709 if ( count( $p ) < 5 ) {
712 if ( count( $p ) > 5 ) {
726 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
727 $stripped .= $marker;
729 if ( $close === '/>' ) {
730 # Empty element tag, <tag />
735 if ( $element === '!--' ) {
738 $end = "/(<\\/$element\\s*>)/i";
740 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
742 if ( count( $q ) < 3 ) {
743 # No end tag -- let it run out to the end of the text.
752 $matches[$marker] = array( $element,
754 Sanitizer
::decodeTagAttributes( $attributes ),
755 "<$element$attributes$close$content$tail" );
761 * Get a list of strippable XML-like elements
763 function getStripList() {
764 return $this->mStripList
;
768 * Add an item to the strip state
769 * Returns the unique tag which must be inserted into the stripped text
770 * The tag will be replaced with the original text in unstrip()
774 function insertStripItem( $text ) {
775 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
776 $this->mMarkerIndex++
;
777 $this->mStripState
->addGeneral( $rnd, $text );
782 * parse the wiki syntax used to render tables
786 function doTableStuff( $text ) {
787 wfProfileIn( __METHOD__
);
789 $lines = StringUtils
::explode( "\n", $text );
793 foreach ( $lines as $outLine ) {
794 $line = trim( $outLine );
796 # empty line, go to next line,
797 # but only append \n if outside of table
799 $output .= $outLine . "\n";
802 $firstChars = $line[0];
803 if ( strlen( $line ) > 1 ) {
804 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
808 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
810 $table =& $this->last( $tables );
811 $table[0] = array(); // first row
812 $currentRow =& $table[0];
813 $table['indent'] = strlen( $matches[1] );
815 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
816 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
818 if ( $attributes !== '' ) {
819 $table['attributes'] = $attributes;
821 } else if ( !isset( $tables[0] ) ) {
822 // we're outside the table
824 $out .= $outLine . "\n";
825 } else if ( $firstChars === '|}' ) {
826 // trim the |} code from the line
827 $line = substr ( $line , 2 );
829 // Shorthand for last row
830 $lastRow =& $this->last( $table );
832 // a thead at the end becomes a tfoot, unless there is only one row
833 // Do this before deleting empty last lines to allow headers at the bottom of tables
834 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
835 $lastRow['type'] = 'tfoot';
836 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
837 $lastRow[$i]['type'] = 'th';
841 // Delete empty last lines
842 if ( empty( $lastRow ) ) {
846 $curtable = array_pop( $tables );
848 #Add a line-ending before the table, but only if there isn't one already
849 if ( substr( $out, -1 ) !== "\n" ) {
852 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
854 if ( count( $tables ) > 0 ) {
855 $table =& $this->last( $tables );
856 $currentRow =& $this->last( $table );
857 $currentElement =& $this->last( $currentRow );
859 $output =& $currentElement['content'];
866 } else if ( $firstChars === '|-' ) {
867 // start a new row element
868 // but only when we haven't started one already
869 if ( count( $currentRow ) != 0 ) {
871 $currentRow =& $this->last( $table );
873 // Get the attributes, there's nothing else useful in $line now
874 $line = substr ( $line , 2 );
875 $attributes = $this->mStripState
->unstripBoth( $line );
876 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
877 if ( $attributes !== '' ) {
878 $currentRow['attributes'] = $attributes;
881 } else if ( $firstChars === '|+' ) {
882 // a table caption, but only proceed if there isn't one already
883 if ( !isset ( $table['caption'] ) ) {
884 $line = substr ( $line , 2 );
886 $c = $this->getCellAttr( $line , 'caption' );
887 $table['caption'] = array();
888 $table['caption']['content'] = $c[0];
889 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
891 $output =& $table['caption']['content'];
893 } else if ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
894 // Which kind of cells are we dealing with
896 $line = substr ( $line , 1 );
898 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
899 $line = str_replace ( '!!' , '||' , $line );
903 // Split up multiple cells on the same line.
904 $cells = StringUtils
::explodeMarkup( '||' , $line );
905 $line = ''; // save memory
907 // decide whether thead to tbody
908 if ( !array_key_exists( 'type', $currentRow ) ) {
909 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
910 } else if ( $firstChars === '|' ) {
911 $currentRow['type'] = 'tbody';
914 // Loop through each table cell
915 foreach ( $cells as $cell ) {
917 $currentRow[] = array();
918 $currentElement =& $this->last( $currentRow );
920 $currentElement['type'] = $currentTag;
922 $c = $this->getCellAttr( $cell , $currentTag );
923 $currentElement['content'] = $c[0];
924 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
927 $output =& $currentElement['content'];
930 $output .= "\n$outLine";
934 # Remove trailing line-ending (b/c)
935 if ( substr( $out, -1 ) === "\n" ) {
936 $out = substr( $out, 0, -1 );
939 # Close any unclosed tables
940 if ( isset( $tables ) && count( $tables ) > 0 ) {
941 for ( $i = 0; $i < count( $tables ); $i++
) {
942 $curtable = array_pop( $tables );
943 $curtable = $this->generateTableHTML( $curtable );
944 #Add a line-ending before the table, but only if there isn't one already
945 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
952 wfProfileOut( __METHOD__
);
958 * Helper function for doTableStuff() separating the contents of cells from
959 * attributes. Particularly useful as there's a possible bug and this action
964 function getCellAttr ( $cell, $tagName ) {
967 $cell = trim ( $cell );
969 // A cell could contain both parameters and data
970 $cellData = explode ( '|' , $cell , 2 );
972 // Bug 553: Note that a '|' inside an invalid link should not
973 // be mistaken as delimiting cell parameters
974 if ( strpos( $cellData[0], '[[' ) !== false ) {
975 $content = trim ( $cell );
977 else if ( count ( $cellData ) == 1 ) {
978 $content = trim ( $cellData[0] );
980 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
981 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
983 $content = trim ( $cellData[1] );
985 return array( $content, $attributes );
990 * Helper function for doTableStuff(). This converts the structured array into html.
994 function generateTableHTML ( &$table ) {
996 $return .= str_repeat( '<dl><dd>' , $table['indent'] );
998 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1000 unset( $table['attributes'] );
1002 if ( isset( $table['caption'] ) ) {
1003 $return .= "\n<caption";
1004 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1006 $return .= $table['caption']['content'];
1007 $return .= "\n</caption>";
1013 // If we only have tbodies, mark table as simple
1014 for ( $i = 0; isset( $table[$i] ); $i++
) {
1015 if ( !count( $table[$i] ) ) continue;
1016 if ( !isset( $table[$i]['type'] ) ) $table[$i]['type'] = 'tbody';
1017 if ( !$lastSection ) {
1018 $lastSection = $table[$i]['type'];
1019 } else if ( $lastSection != $table[$i]['type'] ) {
1025 for ( $i = 0; isset( $table[$i] ); $i++
) {
1026 // Check for empty tables
1027 if ( count( $table[$i] ) ) {
1032 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1033 $return .= "\n<" . $table[$i]['type'] . '>';
1037 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1039 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1040 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1041 $return .= "\n<" . $table[$i][$j]['type'];
1042 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1045 $return .= $table[$i][$j]['content'];
1046 if ( $table[$i][$j]['content'] != '' )
1049 $return .= '</' . $table[$i][$j]['type'] . '>';
1050 unset( $table[$i][$j] );
1052 $return .= "\n</tr>";
1054 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && isset( $table[$i +
1]['type'] ) && $table[$i]['type'] != $table[$i +
1]['type'] ) ) {
1055 $return .= '</' . $table[$i]['type'] . '>';
1057 $lastSection = $table[$i]['type'];
1058 unset( $table[$i] );
1061 if ( isset( $table['caption'] ) ) {
1062 $return .= "\n<tr><td></td></tr>";
1067 $return .= "\n</table>";
1068 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1074 * like end() but only works on the numeric array index and php's internal pointers
1075 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1076 * ignores associative elements and will create a 0 key will a NULL value if there were
1077 * no numric elements and an array itself if not previously defined.
1081 function &last ( &$arr ) {
1082 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1087 * Helper function for parse() that transforms wiki markup into
1088 * HTML. Only called for $mOutputType == self::OT_HTML.
1092 function internalParse( $text, $isMain = true, $frame=false ) {
1093 wfProfileIn( __METHOD__
);
1097 # Hook to suspend the parser in this state
1098 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1099 wfProfileOut( __METHOD__
);
1103 # if $frame is provided, then use $frame for replacing any variables
1105 # use frame depth to infer how include/noinclude tags should be handled
1106 # depth=0 means this is the top-level document; otherwise it's an included document
1107 if ( !$frame->depth
) {
1110 $flag = Parser
::PTD_FOR_INCLUSION
;
1112 $dom = $this->preprocessToDom( $text, $flag );
1113 $text = $frame->expand( $dom );
1115 # if $frame is not provided, then use old-style replaceVariables
1116 $text = $this->replaceVariables( $text );
1119 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1120 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1122 # Tables need to come after variable replacement for things to work
1123 # properly; putting them before other transformations should keep
1124 # exciting things like link expansions from showing up in surprising
1126 $text = $this->doTableStuff( $text );
1128 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1130 $text = $this->doDoubleUnderscore( $text );
1132 $text = $this->doHeadings( $text );
1133 if ( $this->mOptions
->getUseDynamicDates() ) {
1134 $df = DateFormatter
::getInstance();
1135 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1137 $text = $this->replaceInternalLinks( $text );
1138 $text = $this->doAllQuotes( $text );
1139 $text = $this->replaceExternalLinks( $text );
1141 # replaceInternalLinks may sometimes leave behind
1142 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1143 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1145 $text = $this->doMagicLinks( $text );
1146 $text = $this->formatHeadings( $text, $origText, $isMain );
1148 wfProfileOut( __METHOD__
);
1153 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1154 * magic external links.
1159 function doMagicLinks( $text ) {
1160 wfProfileIn( __METHOD__
);
1161 $prots = $this->mUrlProtocols
;
1162 $urlChar = self
::EXT_LINK_URL_CLASS
;
1163 $text = preg_replace_callback(
1165 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1166 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1167 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1168 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1169 ISBN\s+(\b # m[5]: ISBN, capture number
1170 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1171 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1172 [0-9Xx] # check digit
1174 )!x', array( &$this, 'magicLinkCallback' ), $text );
1175 wfProfileOut( __METHOD__
);
1179 function magicLinkCallback( $m ) {
1180 if ( isset( $m[1] ) && $m[1] !== '' ) {
1183 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1186 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1187 # Free external link
1188 return $this->makeFreeExternalLink( $m[0] );
1189 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1191 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1194 $CssClass = 'mw-magiclink-rfc';
1196 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1198 $urlmsg = 'pubmedurl';
1199 $CssClass = 'mw-magiclink-pmid';
1202 throw new MWException( __METHOD__
.': unrecognised match type "' .
1203 substr( $m[0], 0, 20 ) . '"' );
1205 $url = wfMsgForContent( $urlmsg, $id );
1206 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1207 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1210 $num = strtr( $isbn, array(
1215 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1217 $titleObj->escapeLocalUrl() .
1218 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1225 * Make a free external link, given a user-supplied URL
1229 function makeFreeExternalLink( $url ) {
1231 wfProfileIn( __METHOD__
);
1235 # The characters '<' and '>' (which were escaped by
1236 # removeHTMLtags()) should not be included in
1237 # URLs, per RFC 2396.
1239 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1240 $trail = substr( $url, $m2[0][1] ) . $trail;
1241 $url = substr( $url, 0, $m2[0][1] );
1244 # Move trailing punctuation to $trail
1246 # If there is no left bracket, then consider right brackets fair game too
1247 if ( strpos( $url, '(' ) === false ) {
1251 $numSepChars = strspn( strrev( $url ), $sep );
1252 if ( $numSepChars ) {
1253 $trail = substr( $url, -$numSepChars ) . $trail;
1254 $url = substr( $url, 0, -$numSepChars );
1257 $url = Sanitizer
::cleanUrl( $url );
1259 # Is this an external image?
1260 $text = $this->maybeMakeExternalImage( $url );
1261 if ( $text === false ) {
1262 # Not an image, make a link
1263 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1264 $this->getExternalLinkAttribs( $url ) );
1265 # Register it in the output object...
1266 # Replace unnecessary URL escape codes with their equivalent characters
1267 $pasteurized = self
::replaceUnusualEscapes( $url );
1268 $this->mOutput
->addExternalLink( $pasteurized );
1270 wfProfileOut( __METHOD__
);
1271 return $text . $trail;
1276 * Parse headers and return html
1280 function doHeadings( $text ) {
1281 wfProfileIn( __METHOD__
);
1282 for ( $i = 6; $i >= 1; --$i ) {
1283 $h = str_repeat( '=', $i );
1284 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1285 "<h$i>\\1</h$i>", $text );
1287 wfProfileOut( __METHOD__
);
1292 * Replace single quotes with HTML markup
1294 * @return string the altered text
1296 function doAllQuotes( $text ) {
1297 wfProfileIn( __METHOD__
);
1299 $lines = StringUtils
::explode( "\n", $text );
1300 foreach ( $lines as $line ) {
1301 $outtext .= $this->doQuotes( $line ) . "\n";
1303 $outtext = substr( $outtext, 0,-1 );
1304 wfProfileOut( __METHOD__
);
1309 * Helper function for doAllQuotes()
1311 public function doQuotes( $text ) {
1312 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1313 if ( count( $arr ) == 1 ) {
1316 # First, do some preliminary work. This may shift some apostrophes from
1317 # being mark-up to being text. It also counts the number of occurrences
1318 # of bold and italics mark-ups.
1321 for ( $i = 0; $i < count( $arr ); $i++
) {
1322 if ( ( $i %
2 ) == 1 ) {
1323 # If there are ever four apostrophes, assume the first is supposed to
1324 # be text, and the remaining three constitute mark-up for bold text.
1325 if ( strlen( $arr[$i] ) == 4 ) {
1328 } elseif ( strlen( $arr[$i] ) > 5 ) {
1329 # If there are more than 5 apostrophes in a row, assume they're all
1330 # text except for the last 5.
1331 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1334 # Count the number of occurrences of bold and italics mark-ups.
1335 # We are not counting sequences of five apostrophes.
1336 if ( strlen( $arr[$i] ) == 2 ) {
1338 } elseif ( strlen( $arr[$i] ) == 3 ) {
1340 } elseif ( strlen( $arr[$i] ) == 5 ) {
1347 # If there is an odd number of both bold and italics, it is likely
1348 # that one of the bold ones was meant to be an apostrophe followed
1349 # by italics. Which one we cannot know for certain, but it is more
1350 # likely to be one that has a single-letter word before it.
1351 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1353 $firstsingleletterword = -1;
1354 $firstmultiletterword = -1;
1356 foreach ( $arr as $r ) {
1357 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1358 $x1 = substr( $arr[$i-1], -1 );
1359 $x2 = substr( $arr[$i-1], -2, 1 );
1360 if ( $x1 === ' ' ) {
1361 if ( $firstspace == -1 ) {
1364 } elseif ( $x2 === ' ') {
1365 if ( $firstsingleletterword == -1 ) {
1366 $firstsingleletterword = $i;
1369 if ( $firstmultiletterword == -1 ) {
1370 $firstmultiletterword = $i;
1377 # If there is a single-letter word, use it!
1378 if ( $firstsingleletterword > -1 ) {
1379 $arr[$firstsingleletterword] = "''";
1380 $arr[$firstsingleletterword-1] .= "'";
1381 } elseif ( $firstmultiletterword > -1 ) {
1382 # If not, but there's a multi-letter word, use that one.
1383 $arr[$firstmultiletterword] = "''";
1384 $arr[$firstmultiletterword-1] .= "'";
1385 } elseif ( $firstspace > -1 ) {
1386 # ... otherwise use the first one that has neither.
1387 # (notice that it is possible for all three to be -1 if, for example,
1388 # there is only one pentuple-apostrophe in the line)
1389 $arr[$firstspace] = "''";
1390 $arr[$firstspace-1] .= "'";
1394 # Now let's actually convert our apostrophic mush to HTML!
1399 foreach ( $arr as $r ) {
1400 if ( ( $i %
2 ) == 0 ) {
1401 if ( $state === 'both' ) {
1407 if ( strlen( $r ) == 2 ) {
1408 if ( $state === 'i' ) {
1409 $output .= '</i>'; $state = '';
1410 } elseif ( $state === 'bi' ) {
1411 $output .= '</i>'; $state = 'b';
1412 } elseif ( $state === 'ib' ) {
1413 $output .= '</b></i><b>'; $state = 'b';
1414 } elseif ( $state === 'both' ) {
1415 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1416 } else { # $state can be 'b' or ''
1417 $output .= '<i>'; $state .= 'i';
1419 } elseif ( strlen( $r ) == 3 ) {
1420 if ( $state === 'b' ) {
1421 $output .= '</b>'; $state = '';
1422 } elseif ( $state === 'bi' ) {
1423 $output .= '</i></b><i>'; $state = 'i';
1424 } elseif ( $state === 'ib' ) {
1425 $output .= '</b>'; $state = 'i';
1426 } elseif ( $state === 'both' ) {
1427 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1428 } else { # $state can be 'i' or ''
1429 $output .= '<b>'; $state .= 'b';
1431 } elseif ( strlen( $r ) == 5 ) {
1432 if ( $state === 'b' ) {
1433 $output .= '</b><i>'; $state = 'i';
1434 } elseif ( $state === 'i' ) {
1435 $output .= '</i><b>'; $state = 'b';
1436 } elseif ( $state === 'bi' ) {
1437 $output .= '</i></b>'; $state = '';
1438 } elseif ( $state === 'ib' ) {
1439 $output .= '</b></i>'; $state = '';
1440 } elseif ( $state === 'both' ) {
1441 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1442 } else { # ($state == '')
1443 $buffer = ''; $state = 'both';
1449 # Now close all remaining tags. Notice that the order is important.
1450 if ( $state === 'b' ||
$state === 'ib' ) {
1453 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1456 if ( $state === 'bi' ) {
1459 # There might be lonely ''''', so make sure we have a buffer
1460 if ( $state === 'both' && $buffer ) {
1461 $output .= '<b><i>'.$buffer.'</i></b>';
1468 * Replace external links (REL)
1470 * Note: this is all very hackish and the order of execution matters a lot.
1471 * Make sure to run maintenance/parserTests.php if you change this code.
1475 function replaceExternalLinks( $text ) {
1477 wfProfileIn( __METHOD__
);
1479 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1480 $s = array_shift( $bits );
1483 while ( $i<count( $bits ) ) {
1485 $protocol = $bits[$i++
];
1486 $text = $bits[$i++
];
1487 $trail = $bits[$i++
];
1489 # The characters '<' and '>' (which were escaped by
1490 # removeHTMLtags()) should not be included in
1491 # URLs, per RFC 2396.
1493 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1494 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1495 $url = substr( $url, 0, $m2[0][1] );
1498 # If the link text is an image URL, replace it with an <img> tag
1499 # This happened by accident in the original parser, but some people used it extensively
1500 $img = $this->maybeMakeExternalImage( $text );
1501 if ( $img !== false ) {
1507 # Set linktype for CSS - if URL==text, link is essentially free
1508 $linktype = ( $text === $url ) ?
'free' : 'text';
1510 # No link text, e.g. [http://domain.tld/some.link]
1511 if ( $text == '' ) {
1512 # Autonumber if allowed. See bug #5918
1513 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1514 $langObj = $this->getFunctionLang();
1515 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1516 $linktype = 'autonumber';
1518 # Otherwise just use the URL
1519 $text = htmlspecialchars( $url );
1523 # Have link text, e.g. [http://domain.tld/some.link text]s
1525 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1528 $text = $wgContLang->markNoConversion( $text );
1530 $url = Sanitizer
::cleanUrl( $url );
1532 # Use the encoded URL
1533 # This means that users can paste URLs directly into the text
1534 # Funny characters like ö aren't valid in URLs anyway
1535 # This was changed in August 2004
1536 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1537 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1539 # Register link in the output object.
1540 # Replace unnecessary URL escape codes with the referenced character
1541 # This prevents spammers from hiding links from the filters
1542 $pasteurized = self
::replaceUnusualEscapes( $url );
1543 $this->mOutput
->addExternalLink( $pasteurized );
1546 wfProfileOut( __METHOD__
);
1551 * Get an associative array of additional HTML attributes appropriate for a
1552 * particular external link. This currently may include rel => nofollow
1553 * (depending on configuration, namespace, and the URL's domain) and/or a
1554 * target attribute (depending on configuration).
1556 * @param $url String: optional URL, to extract the domain from for rel =>
1557 * nofollow if appropriate
1558 * @return Array: associative array of HTML attributes
1560 function getExternalLinkAttribs( $url = false ) {
1562 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1563 $ns = $this->mTitle
->getNamespace();
1564 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1565 $attribs['rel'] = 'nofollow';
1567 global $wgNoFollowDomainExceptions;
1568 if ( $wgNoFollowDomainExceptions ) {
1569 $bits = wfParseUrl( $url );
1570 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1571 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1572 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1573 unset( $attribs['rel'] );
1580 if ( $this->mOptions
->getExternalLinkTarget() ) {
1581 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1587 * Replace unusual URL escape codes with their equivalent characters
1589 * @param $url String
1592 * @todo This can merge genuinely required bits in the path or query string,
1593 * breaking legit URLs. A proper fix would treat the various parts of
1594 * the URL differently; as a workaround, just use the output for
1595 * statistical records, not for actual linking/output.
1597 static function replaceUnusualEscapes( $url ) {
1598 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1599 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1603 * Callback function used in replaceUnusualEscapes().
1604 * Replaces unusual URL escape codes with their equivalent character
1606 private static function replaceUnusualEscapesCallback( $matches ) {
1607 $char = urldecode( $matches[0] );
1608 $ord = ord( $char );
1609 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1610 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1611 # No, shouldn't be escaped
1614 # Yes, leave it escaped
1620 * make an image if it's allowed, either through the global
1621 * option, through the exception, or through the on-wiki whitelist
1624 function maybeMakeExternalImage( $url ) {
1625 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1626 $imagesexception = !empty( $imagesfrom );
1628 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1629 if ( $imagesexception && is_array( $imagesfrom ) ) {
1630 $imagematch = false;
1631 foreach ( $imagesfrom as $match ) {
1632 if ( strpos( $url, $match ) === 0 ) {
1637 } elseif ( $imagesexception ) {
1638 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1640 $imagematch = false;
1642 if ( $this->mOptions
->getAllowExternalImages()
1643 ||
( $imagesexception && $imagematch ) ) {
1644 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1646 $text = Linker
::makeExternalImage( $url );
1649 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1650 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1651 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1652 foreach ( $whitelist as $entry ) {
1653 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1654 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1657 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1658 # Image matches a whitelist entry
1659 $text = Linker
::makeExternalImage( $url );
1668 * Process [[ ]] wikilinks
1669 * @return String: processed text
1673 function replaceInternalLinks( $s ) {
1674 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1679 * Process [[ ]] wikilinks (RIL)
1680 * @return LinkHolderArray
1684 function replaceInternalLinks2( &$s ) {
1687 wfProfileIn( __METHOD__
);
1689 wfProfileIn( __METHOD__
.'-setup' );
1690 static $tc = FALSE, $e1, $e1_img;
1691 # the % is needed to support urlencoded titles as well
1693 $tc = Title
::legalChars() . '#%';
1694 # Match a link having the form [[namespace:link|alternate]]trail
1695 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1696 # Match cases where there is no "]]", which might still be images
1697 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1700 $holders = new LinkHolderArray( $this );
1702 # split the entire text string on occurences of [[
1703 $a = StringUtils
::explode( '[[', ' ' . $s );
1704 # get the first element (all text up to first [[), and remove the space we added
1707 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1708 $s = substr( $s, 1 );
1710 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1712 if ( $useLinkPrefixExtension ) {
1713 # Match the end of a line for a word that's not followed by whitespace,
1714 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1715 $e2 = wfMsgForContent( 'linkprefix' );
1718 if ( is_null( $this->mTitle
) ) {
1719 wfProfileOut( __METHOD__
.'-setup' );
1720 wfProfileOut( __METHOD__
);
1721 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1723 $nottalk = !$this->mTitle
->isTalkPage();
1725 if ( $useLinkPrefixExtension ) {
1727 if ( preg_match( $e2, $s, $m ) ) {
1728 $first_prefix = $m[2];
1730 $first_prefix = false;
1736 if ( $wgContLang->hasVariants() ) {
1737 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1739 $selflink = array( $this->mTitle
->getPrefixedText() );
1741 $useSubpages = $this->areSubpagesAllowed();
1742 wfProfileOut( __METHOD__
.'-setup' );
1744 # Loop for each link
1745 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1746 # Check for excessive memory usage
1747 if ( $holders->isBig() ) {
1749 # Do the existence check, replace the link holders and clear the array
1750 $holders->replace( $s );
1754 if ( $useLinkPrefixExtension ) {
1755 wfProfileIn( __METHOD__
.'-prefixhandling' );
1756 if ( preg_match( $e2, $s, $m ) ) {
1763 if ( $first_prefix ) {
1764 $prefix = $first_prefix;
1765 $first_prefix = false;
1767 wfProfileOut( __METHOD__
.'-prefixhandling' );
1770 $might_be_img = false;
1772 wfProfileIn( __METHOD__
."-e1" );
1773 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1775 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1776 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1777 # the real problem is with the $e1 regex
1780 # Still some problems for cases where the ] is meant to be outside punctuation,
1781 # and no image is in sight. See bug 2095.
1783 if ( $text !== '' &&
1784 substr( $m[3], 0, 1 ) === ']' &&
1785 strpos( $text, '[' ) !== false
1788 $text .= ']'; # so that replaceExternalLinks($text) works later
1789 $m[3] = substr( $m[3], 1 );
1791 # fix up urlencoded title texts
1792 if ( strpos( $m[1], '%' ) !== false ) {
1793 # Should anchors '#' also be rejected?
1794 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1797 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1798 $might_be_img = true;
1800 if ( strpos( $m[1], '%' ) !== false ) {
1801 $m[1] = rawurldecode( $m[1] );
1804 } else { # Invalid form; output directly
1805 $s .= $prefix . '[[' . $line ;
1806 wfProfileOut( __METHOD__
."-e1" );
1809 wfProfileOut( __METHOD__
."-e1" );
1810 wfProfileIn( __METHOD__
."-misc" );
1812 # Don't allow internal links to pages containing
1813 # PROTO: where PROTO is a valid URL protocol; these
1814 # should be external links.
1815 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1816 $s .= $prefix . '[[' . $line ;
1817 wfProfileOut( __METHOD__
."-misc" );
1821 # Make subpage if necessary
1822 if ( $useSubpages ) {
1823 $link = $this->maybeDoSubpageLink( $m[1], $text );
1828 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1830 # Strip off leading ':'
1831 $link = substr( $link, 1 );
1834 wfProfileOut( __METHOD__
."-misc" );
1835 wfProfileIn( __METHOD__
."-title" );
1836 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1837 if ( $nt === null ) {
1838 $s .= $prefix . '[[' . $line;
1839 wfProfileOut( __METHOD__
."-title" );
1843 $ns = $nt->getNamespace();
1844 $iw = $nt->getInterWiki();
1845 wfProfileOut( __METHOD__
."-title" );
1847 if ( $might_be_img ) { # if this is actually an invalid link
1848 wfProfileIn( __METHOD__
."-might_be_img" );
1849 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1852 # look at the next 'line' to see if we can close it there
1854 $next_line = $a->current();
1855 if ( $next_line === false ||
$next_line === null ) {
1858 $m = explode( ']]', $next_line, 3 );
1859 if ( count( $m ) == 3 ) {
1860 # the first ]] closes the inner link, the second the image
1862 $text .= "[[{$m[0]}]]{$m[1]}";
1865 } elseif ( count( $m ) == 2 ) {
1866 # if there's exactly one ]] that's fine, we'll keep looking
1867 $text .= "[[{$m[0]}]]{$m[1]}";
1869 # if $next_line is invalid too, we need look no further
1870 $text .= '[[' . $next_line;
1875 # we couldn't find the end of this imageLink, so output it raw
1876 # but don't ignore what might be perfectly normal links in the text we've examined
1877 $holders->merge( $this->replaceInternalLinks2( $text ) );
1878 $s .= "{$prefix}[[$link|$text";
1879 # note: no $trail, because without an end, there *is* no trail
1880 wfProfileOut( __METHOD__
."-might_be_img" );
1883 } else { # it's not an image, so output it raw
1884 $s .= "{$prefix}[[$link|$text";
1885 # note: no $trail, because without an end, there *is* no trail
1886 wfProfileOut( __METHOD__
."-might_be_img" );
1889 wfProfileOut( __METHOD__
."-might_be_img" );
1892 $wasblank = ( $text == '' );
1896 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1897 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1898 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1899 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1900 $text = $this->doQuotes( $text );
1903 # Link not escaped by : , create the various objects
1907 wfProfileIn( __METHOD__
."-interwiki" );
1908 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1909 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1910 $s = rtrim( $s . $prefix );
1911 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1912 wfProfileOut( __METHOD__
."-interwiki" );
1915 wfProfileOut( __METHOD__
."-interwiki" );
1917 if ( $ns == NS_FILE
) {
1918 wfProfileIn( __METHOD__
."-image" );
1919 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1921 # if no parameters were passed, $text
1922 # becomes something like "File:Foo.png",
1923 # which we don't want to pass on to the
1927 # recursively parse links inside the image caption
1928 # actually, this will parse them in any other parameters, too,
1929 # but it might be hard to fix that, and it doesn't matter ATM
1930 $text = $this->replaceExternalLinks( $text );
1931 $holders->merge( $this->replaceInternalLinks2( $text ) );
1933 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1934 $s .= $prefix . $this->armorLinks(
1935 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1937 $s .= $prefix . $trail;
1939 wfProfileOut( __METHOD__
."-image" );
1943 if ( $ns == NS_CATEGORY
) {
1944 wfProfileIn( __METHOD__
."-category" );
1945 $s = rtrim( $s . "\n" ); # bug 87
1948 $sortkey = $this->getDefaultSort();
1952 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1953 $sortkey = str_replace( "\n", '', $sortkey );
1954 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1955 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1958 * Strip the whitespace Category links produce, see bug 87
1959 * @todo We might want to use trim($tmp, "\n") here.
1961 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1963 wfProfileOut( __METHOD__
."-category" );
1968 # Self-link checking
1969 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1970 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1971 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
1976 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1977 # @todo FIXME: Should do batch file existence checks, see comment below
1978 if ( $ns == NS_MEDIA
) {
1979 wfProfileIn( __METHOD__
."-media" );
1980 # Give extensions a chance to select the file revision for us
1981 $time = $sha1 = $descQuery = false;
1982 wfRunHooks( 'BeforeParserFetchFileAndTitle',
1983 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
1984 # Fetch and register the file (file title may be different via hooks)
1985 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
1986 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1987 $s .= $prefix . $this->armorLinks(
1988 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
1989 wfProfileOut( __METHOD__
."-media" );
1993 wfProfileIn( __METHOD__
."-always_known" );
1994 # Some titles, such as valid special pages or files in foreign repos, should
1995 # be shown as bluelinks even though they're not included in the page table
1997 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1998 # batch file existence checks for NS_FILE and NS_MEDIA
1999 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2000 $this->mOutput
->addLink( $nt );
2001 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2003 # Links will be added to the output link list after checking
2004 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2006 wfProfileOut( __METHOD__
."-always_known" );
2008 wfProfileOut( __METHOD__
);
2013 * Render a forced-blue link inline; protect against double expansion of
2014 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2015 * Since this little disaster has to split off the trail text to avoid
2016 * breaking URLs in the following text without breaking trails on the
2017 * wiki links, it's been made into a horrible function.
2020 * @param $text String
2021 * @param $query Array or String
2022 * @param $trail String
2023 * @param $prefix String
2024 * @return String: HTML-wikitext mix oh yuck
2026 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2027 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2029 if ( is_string( $query ) ) {
2030 $query = wfCgiToArray( $query );
2032 if ( $text == '' ) {
2033 $text = htmlspecialchars( $nt->getPrefixedText() );
2036 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2038 return $this->armorLinks( $link ) . $trail;
2042 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2043 * going to go through further parsing steps before inline URL expansion.
2045 * Not needed quite as much as it used to be since free links are a bit
2046 * more sensible these days. But bracketed links are still an issue.
2048 * @param $text String: more-or-less HTML
2049 * @return String: less-or-more HTML with NOPARSE bits
2051 function armorLinks( $text ) {
2052 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2053 "{$this->mUniqPrefix}NOPARSE$1", $text );
2057 * Return true if subpage links should be expanded on this page.
2060 function areSubpagesAllowed() {
2061 # Some namespaces don't allow subpages
2062 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2066 * Handle link to subpage if necessary
2068 * @param $target String: the source of the link
2069 * @param &$text String: the link text, modified as necessary
2070 * @return string the full name of the link
2073 function maybeDoSubpageLink( $target, &$text ) {
2074 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2078 * Used by doBlockLevels()
2083 function closeParagraph() {
2085 if ( $this->mLastSection
!= '' ) {
2086 $result = '</' . $this->mLastSection
. ">\n";
2088 $this->mInPre
= false;
2089 $this->mLastSection
= '';
2094 * getCommon() returns the length of the longest common substring
2095 * of both arguments, starting at the beginning of both.
2098 function getCommon( $st1, $st2 ) {
2099 $fl = strlen( $st1 );
2100 $shorter = strlen( $st2 );
2101 if ( $fl < $shorter ) {
2105 for ( $i = 0; $i < $shorter; ++
$i ) {
2106 if ( $st1[$i] != $st2[$i] ) {
2114 * These next three functions open, continue, and close the list
2115 * element appropriate to the prefix character passed into them.
2120 function openList( $char ) {
2121 $result = $this->closeParagraph();
2123 if ( '*' === $char ) {
2124 $result .= '<ul><li>';
2125 } elseif ( '#' === $char ) {
2126 $result .= '<ol><li>';
2127 } elseif ( ':' === $char ) {
2128 $result .= '<dl><dd>';
2129 } elseif ( ';' === $char ) {
2130 $result .= '<dl><dt>';
2131 $this->mDTopen
= true;
2133 $result = '<!-- ERR 1 -->';
2141 * @param $char String
2146 function nextItem( $char ) {
2147 if ( '*' === $char ||
'#' === $char ) {
2149 } elseif ( ':' === $char ||
';' === $char ) {
2151 if ( $this->mDTopen
) {
2154 if ( ';' === $char ) {
2155 $this->mDTopen
= true;
2156 return $close . '<dt>';
2158 $this->mDTopen
= false;
2159 return $close . '<dd>';
2162 return '<!-- ERR 2 -->';
2167 * @param $char String
2172 function closeList( $char ) {
2173 if ( '*' === $char ) {
2174 $text = '</li></ul>';
2175 } elseif ( '#' === $char ) {
2176 $text = '</li></ol>';
2177 } elseif ( ':' === $char ) {
2178 if ( $this->mDTopen
) {
2179 $this->mDTopen
= false;
2180 $text = '</dt></dl>';
2182 $text = '</dd></dl>';
2185 return '<!-- ERR 3 -->';
2192 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2194 * @param $text String
2195 * @param $linestart Boolean: whether or not this is at the start of a line.
2197 * @return string the lists rendered as HTML
2199 function doBlockLevels( $text, $linestart ) {
2200 wfProfileIn( __METHOD__
);
2202 # Parsing through the text line by line. The main thing
2203 # happening here is handling of block-level elements p, pre,
2204 # and making lists from lines starting with * # : etc.
2206 $textLines = StringUtils
::explode( "\n", $text );
2208 $lastPrefix = $output = '';
2209 $this->mDTopen
= $inBlockElem = false;
2211 $paragraphStack = false;
2213 foreach ( $textLines as $oLine ) {
2215 if ( !$linestart ) {
2225 $lastPrefixLength = strlen( $lastPrefix );
2226 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2227 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2228 # If not in a <pre> element, scan for and figure out what prefixes are there.
2229 if ( !$this->mInPre
) {
2230 # Multiple prefixes may abut each other for nested lists.
2231 $prefixLength = strspn( $oLine, '*#:;' );
2232 $prefix = substr( $oLine, 0, $prefixLength );
2235 # ; and : are both from definition-lists, so they're equivalent
2236 # for the purposes of determining whether or not we need to open/close
2238 $prefix2 = str_replace( ';', ':', $prefix );
2239 $t = substr( $oLine, $prefixLength );
2240 $this->mInPre
= (bool)$preOpenMatch;
2242 # Don't interpret any other prefixes in preformatted text
2244 $prefix = $prefix2 = '';
2249 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2250 # Same as the last item, so no need to deal with nesting or opening stuff
2251 $output .= $this->nextItem( substr( $prefix, -1 ) );
2252 $paragraphStack = false;
2254 if ( substr( $prefix, -1 ) === ';') {
2255 # The one nasty exception: definition lists work like this:
2256 # ; title : definition text
2257 # So we check for : in the remainder text to split up the
2258 # title and definition, without b0rking links.
2260 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2262 $output .= $term . $this->nextItem( ':' );
2265 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2266 # We need to open or close prefixes, or both.
2268 # Either open or close a level...
2269 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2270 $paragraphStack = false;
2272 # Close all the prefixes which aren't shared.
2273 while ( $commonPrefixLength < $lastPrefixLength ) {
2274 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2275 --$lastPrefixLength;
2278 # Continue the current prefix if appropriate.
2279 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2280 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2283 # Open prefixes where appropriate.
2284 while ( $prefixLength > $commonPrefixLength ) {
2285 $char = substr( $prefix, $commonPrefixLength, 1 );
2286 $output .= $this->openList( $char );
2288 if ( ';' === $char ) {
2289 # @todo FIXME: This is dupe of code above
2290 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2292 $output .= $term . $this->nextItem( ':' );
2295 ++
$commonPrefixLength;
2297 $lastPrefix = $prefix2;
2300 # If we have no prefixes, go to paragraph mode.
2301 if ( 0 == $prefixLength ) {
2302 wfProfileIn( __METHOD__
."-paragraph" );
2303 # No prefix (not in list)--go to paragraph mode
2304 # XXX: use a stack for nestable elements like span, table and div
2305 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2306 $closematch = preg_match(
2307 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2308 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2309 if ( $openmatch or $closematch ) {
2310 $paragraphStack = false;
2311 # TODO bug 5718: paragraph closed
2312 $output .= $this->closeParagraph();
2313 if ( $preOpenMatch and !$preCloseMatch ) {
2314 $this->mInPre
= true;
2316 $inBlockElem = !$closematch;
2317 } elseif ( !$inBlockElem && !$this->mInPre
) {
2318 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2320 if ( $this->mLastSection
!== 'pre' ) {
2321 $paragraphStack = false;
2322 $output .= $this->closeParagraph().'<pre>';
2323 $this->mLastSection
= 'pre';
2325 $t = substr( $t, 1 );
2328 if ( trim( $t ) === '' ) {
2329 if ( $paragraphStack ) {
2330 $output .= $paragraphStack.'<br />';
2331 $paragraphStack = false;
2332 $this->mLastSection
= 'p';
2334 if ( $this->mLastSection
!== 'p' ) {
2335 $output .= $this->closeParagraph();
2336 $this->mLastSection
= '';
2337 $paragraphStack = '<p>';
2339 $paragraphStack = '</p><p>';
2343 if ( $paragraphStack ) {
2344 $output .= $paragraphStack;
2345 $paragraphStack = false;
2346 $this->mLastSection
= 'p';
2347 } elseif ( $this->mLastSection
!== 'p' ) {
2348 $output .= $this->closeParagraph().'<p>';
2349 $this->mLastSection
= 'p';
2354 wfProfileOut( __METHOD__
."-paragraph" );
2356 # somewhere above we forget to get out of pre block (bug 785)
2357 if ( $preCloseMatch && $this->mInPre
) {
2358 $this->mInPre
= false;
2360 if ( $paragraphStack === false ) {
2364 while ( $prefixLength ) {
2365 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2368 if ( $this->mLastSection
!= '' ) {
2369 $output .= '</' . $this->mLastSection
. '>';
2370 $this->mLastSection
= '';
2373 wfProfileOut( __METHOD__
);
2378 * Split up a string on ':', ignoring any occurences inside tags
2379 * to prevent illegal overlapping.
2381 * @param $str String: the string to split
2382 * @param &$before String: set to everything before the ':'
2383 * @param &$after String: set to everything after the ':'
2384 * return String: the position of the ':', or false if none found
2386 function findColonNoLinks( $str, &$before, &$after ) {
2387 wfProfileIn( __METHOD__
);
2389 $pos = strpos( $str, ':' );
2390 if ( $pos === false ) {
2392 wfProfileOut( __METHOD__
);
2396 $lt = strpos( $str, '<' );
2397 if ( $lt === false ||
$lt > $pos ) {
2398 # Easy; no tag nesting to worry about
2399 $before = substr( $str, 0, $pos );
2400 $after = substr( $str, $pos+
1 );
2401 wfProfileOut( __METHOD__
);
2405 # Ugly state machine to walk through avoiding tags.
2406 $state = self
::COLON_STATE_TEXT
;
2408 $len = strlen( $str );
2409 for( $i = 0; $i < $len; $i++
) {
2413 # (Using the number is a performance hack for common cases)
2414 case 0: # self::COLON_STATE_TEXT:
2417 # Could be either a <start> tag or an </end> tag
2418 $state = self
::COLON_STATE_TAGSTART
;
2421 if ( $stack == 0 ) {
2423 $before = substr( $str, 0, $i );
2424 $after = substr( $str, $i +
1 );
2425 wfProfileOut( __METHOD__
);
2428 # Embedded in a tag; don't break it.
2431 # Skip ahead looking for something interesting
2432 $colon = strpos( $str, ':', $i );
2433 if ( $colon === false ) {
2434 # Nothing else interesting
2435 wfProfileOut( __METHOD__
);
2438 $lt = strpos( $str, '<', $i );
2439 if ( $stack === 0 ) {
2440 if ( $lt === false ||
$colon < $lt ) {
2442 $before = substr( $str, 0, $colon );
2443 $after = substr( $str, $colon +
1 );
2444 wfProfileOut( __METHOD__
);
2448 if ( $lt === false ) {
2449 # Nothing else interesting to find; abort!
2450 # We're nested, but there's no close tags left. Abort!
2453 # Skip ahead to next tag start
2455 $state = self
::COLON_STATE_TAGSTART
;
2458 case 1: # self::COLON_STATE_TAG:
2463 $state = self
::COLON_STATE_TEXT
;
2466 # Slash may be followed by >?
2467 $state = self
::COLON_STATE_TAGSLASH
;
2473 case 2: # self::COLON_STATE_TAGSTART:
2476 $state = self
::COLON_STATE_CLOSETAG
;
2479 $state = self
::COLON_STATE_COMMENT
;
2482 # Illegal early close? This shouldn't happen D:
2483 $state = self
::COLON_STATE_TEXT
;
2486 $state = self
::COLON_STATE_TAG
;
2489 case 3: # self::COLON_STATE_CLOSETAG:
2494 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2495 wfProfileOut( __METHOD__
);
2498 $state = self
::COLON_STATE_TEXT
;
2501 case self
::COLON_STATE_TAGSLASH
:
2503 # Yes, a self-closed tag <blah/>
2504 $state = self
::COLON_STATE_TEXT
;
2506 # Probably we're jumping the gun, and this is an attribute
2507 $state = self
::COLON_STATE_TAG
;
2510 case 5: # self::COLON_STATE_COMMENT:
2512 $state = self
::COLON_STATE_COMMENTDASH
;
2515 case self
::COLON_STATE_COMMENTDASH
:
2517 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2519 $state = self
::COLON_STATE_COMMENT
;
2522 case self
::COLON_STATE_COMMENTDASHDASH
:
2524 $state = self
::COLON_STATE_TEXT
;
2526 $state = self
::COLON_STATE_COMMENT
;
2530 throw new MWException( "State machine error in " . __METHOD__
);
2534 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2535 wfProfileOut( __METHOD__
);
2538 wfProfileOut( __METHOD__
);
2543 * Return value of a magic variable (like PAGENAME)
2547 * @param $index integer
2548 * @param $frame PPFrame
2550 function getVariableValue( $index, $frame=false ) {
2551 global $wgContLang, $wgSitename, $wgServer;
2552 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2555 * Some of these require message or data lookups and can be
2556 * expensive to check many times.
2558 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2559 if ( isset( $this->mVarCache
[$index] ) ) {
2560 return $this->mVarCache
[$index];
2564 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2565 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2568 global $wgLocaltimezone;
2569 if ( isset( $wgLocaltimezone ) ) {
2570 $oldtz = date_default_timezone_get();
2571 date_default_timezone_set( $wgLocaltimezone );
2574 $localTimestamp = date( 'YmdHis', $ts );
2575 $localMonth = date( 'm', $ts );
2576 $localMonth1 = date( 'n', $ts );
2577 $localMonthName = date( 'n', $ts );
2578 $localDay = date( 'j', $ts );
2579 $localDay2 = date( 'd', $ts );
2580 $localDayOfWeek = date( 'w', $ts );
2581 $localWeek = date( 'W', $ts );
2582 $localYear = date( 'Y', $ts );
2583 $localHour = date( 'H', $ts );
2584 if ( isset( $wgLocaltimezone ) ) {
2585 date_default_timezone_set( $oldtz );
2589 case 'currentmonth':
2590 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2592 case 'currentmonth1':
2593 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2595 case 'currentmonthname':
2596 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2598 case 'currentmonthnamegen':
2599 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2601 case 'currentmonthabbrev':
2602 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2605 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2608 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2611 $value = $wgContLang->formatNum( $localMonth );
2614 $value = $wgContLang->formatNum( $localMonth1 );
2616 case 'localmonthname':
2617 $value = $wgContLang->getMonthName( $localMonthName );
2619 case 'localmonthnamegen':
2620 $value = $wgContLang->getMonthNameGen( $localMonthName );
2622 case 'localmonthabbrev':
2623 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2626 $value = $wgContLang->formatNum( $localDay );
2629 $value = $wgContLang->formatNum( $localDay2 );
2632 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2635 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2637 case 'fullpagename':
2638 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2640 case 'fullpagenamee':
2641 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2644 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2646 case 'subpagenamee':
2647 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2649 case 'basepagename':
2650 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2652 case 'basepagenamee':
2653 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2655 case 'talkpagename':
2656 if ( $this->mTitle
->canTalk() ) {
2657 $talkPage = $this->mTitle
->getTalkPage();
2658 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2663 case 'talkpagenamee':
2664 if ( $this->mTitle
->canTalk() ) {
2665 $talkPage = $this->mTitle
->getTalkPage();
2666 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2671 case 'subjectpagename':
2672 $subjPage = $this->mTitle
->getSubjectPage();
2673 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2675 case 'subjectpagenamee':
2676 $subjPage = $this->mTitle
->getSubjectPage();
2677 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2680 # Let the edit saving system know we should parse the page
2681 # *after* a revision ID has been assigned.
2682 $this->mOutput
->setFlag( 'vary-revision' );
2683 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2684 $value = $this->mRevisionId
;
2687 # Let the edit saving system know we should parse the page
2688 # *after* a revision ID has been assigned. This is for null edits.
2689 $this->mOutput
->setFlag( 'vary-revision' );
2690 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2691 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2693 case 'revisionday2':
2694 # Let the edit saving system know we should parse the page
2695 # *after* a revision ID has been assigned. This is for null edits.
2696 $this->mOutput
->setFlag( 'vary-revision' );
2697 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2698 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2700 case 'revisionmonth':
2701 # Let the edit saving system know we should parse the page
2702 # *after* a revision ID has been assigned. This is for null edits.
2703 $this->mOutput
->setFlag( 'vary-revision' );
2704 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2705 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2707 case 'revisionmonth1':
2708 # Let the edit saving system know we should parse the page
2709 # *after* a revision ID has been assigned. This is for null edits.
2710 $this->mOutput
->setFlag( 'vary-revision' );
2711 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2712 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2714 case 'revisionyear':
2715 # Let the edit saving system know we should parse the page
2716 # *after* a revision ID has been assigned. This is for null edits.
2717 $this->mOutput
->setFlag( 'vary-revision' );
2718 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2719 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2721 case 'revisiontimestamp':
2722 # Let the edit saving system know we should parse the page
2723 # *after* a revision ID has been assigned. This is for null edits.
2724 $this->mOutput
->setFlag( 'vary-revision' );
2725 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2726 $value = $this->getRevisionTimestamp();
2728 case 'revisionuser':
2729 # Let the edit saving system know we should parse the page
2730 # *after* a revision ID has been assigned. This is for null edits.
2731 $this->mOutput
->setFlag( 'vary-revision' );
2732 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2733 $value = $this->getRevisionUser();
2736 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2739 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2742 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2745 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2747 case 'subjectspace':
2748 $value = $this->mTitle
->getSubjectNsText();
2750 case 'subjectspacee':
2751 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2753 case 'currentdayname':
2754 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2757 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2760 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2763 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2766 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2767 # int to remove the padding
2768 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2771 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2773 case 'localdayname':
2774 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2777 $value = $wgContLang->formatNum( $localYear, true );
2780 $value = $wgContLang->time( $localTimestamp, false, false );
2783 $value = $wgContLang->formatNum( $localHour, true );
2786 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2787 # int to remove the padding
2788 $value = $wgContLang->formatNum( (int)$localWeek );
2791 $value = $wgContLang->formatNum( $localDayOfWeek );
2793 case 'numberofarticles':
2794 $value = $wgContLang->formatNum( SiteStats
::articles() );
2796 case 'numberoffiles':
2797 $value = $wgContLang->formatNum( SiteStats
::images() );
2799 case 'numberofusers':
2800 $value = $wgContLang->formatNum( SiteStats
::users() );
2802 case 'numberofactiveusers':
2803 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2805 case 'numberofpages':
2806 $value = $wgContLang->formatNum( SiteStats
::pages() );
2808 case 'numberofadmins':
2809 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2811 case 'numberofedits':
2812 $value = $wgContLang->formatNum( SiteStats
::edits() );
2814 case 'numberofviews':
2815 $value = $wgContLang->formatNum( SiteStats
::views() );
2817 case 'currenttimestamp':
2818 $value = wfTimestamp( TS_MW
, $ts );
2820 case 'localtimestamp':
2821 $value = $localTimestamp;
2823 case 'currentversion':
2824 $value = SpecialVersion
::getVersion();
2827 return $wgArticlePath;
2833 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2834 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2835 wfRestoreWarnings();
2836 return $serverName ?
$serverName : $wgServer;
2838 return $wgScriptPath;
2840 return $wgStylePath;
2841 case 'directionmark':
2842 return $wgContLang->getDirMark();
2843 case 'contentlanguage':
2844 global $wgLanguageCode;
2845 return $wgLanguageCode;
2848 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2856 $this->mVarCache
[$index] = $value;
2862 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2866 function initialiseVariables() {
2867 wfProfileIn( __METHOD__
);
2868 $variableIDs = MagicWord
::getVariableIDs();
2869 $substIDs = MagicWord
::getSubstIDs();
2871 $this->mVariables
= new MagicWordArray( $variableIDs );
2872 $this->mSubstWords
= new MagicWordArray( $substIDs );
2873 wfProfileOut( __METHOD__
);
2877 * Preprocess some wikitext and return the document tree.
2878 * This is the ghost of replace_variables().
2880 * @param $text String: The text to parse
2881 * @param $flags Integer: bitwise combination of:
2882 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2883 * included. Default is to assume a direct page view.
2885 * The generated DOM tree must depend only on the input text and the flags.
2886 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2888 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2889 * change in the DOM tree for a given text, must be passed through the section identifier
2890 * in the section edit link and thus back to extractSections().
2892 * The output of this function is currently only cached in process memory, but a persistent
2893 * cache may be implemented at a later date which takes further advantage of these strict
2894 * dependency requirements.
2900 function preprocessToDom( $text, $flags = 0 ) {
2901 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2906 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2910 public static function splitWhitespace( $s ) {
2911 $ltrimmed = ltrim( $s );
2912 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2913 $trimmed = rtrim( $ltrimmed );
2914 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2916 $w2 = substr( $ltrimmed, -$diff );
2920 return array( $w1, $trimmed, $w2 );
2924 * Replace magic variables, templates, and template arguments
2925 * with the appropriate text. Templates are substituted recursively,
2926 * taking care to avoid infinite loops.
2928 * Note that the substitution depends on value of $mOutputType:
2929 * self::OT_WIKI: only {{subst:}} templates
2930 * self::OT_PREPROCESS: templates but not extension tags
2931 * self::OT_HTML: all templates and extension tags
2933 * @param $text String: the text to transform
2934 * @param $frame PPFrame Object describing the arguments passed to the template.
2935 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2936 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2937 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2942 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2943 # Is there any text? Also, Prevent too big inclusions!
2944 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2947 wfProfileIn( __METHOD__
);
2949 if ( $frame === false ) {
2950 $frame = $this->getPreprocessor()->newFrame();
2951 } elseif ( !( $frame instanceof PPFrame
) ) {
2952 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2953 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2956 $dom = $this->preprocessToDom( $text );
2957 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2958 $text = $frame->expand( $dom, $flags );
2960 wfProfileOut( __METHOD__
);
2965 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2969 static function createAssocArgs( $args ) {
2970 $assocArgs = array();
2972 foreach ( $args as $arg ) {
2973 $eqpos = strpos( $arg, '=' );
2974 if ( $eqpos === false ) {
2975 $assocArgs[$index++
] = $arg;
2977 $name = trim( substr( $arg, 0, $eqpos ) );
2978 $value = trim( substr( $arg, $eqpos+
1 ) );
2979 if ( $value === false ) {
2982 if ( $name !== false ) {
2983 $assocArgs[$name] = $value;
2992 * Warn the user when a parser limitation is reached
2993 * Will warn at most once the user per limitation type
2995 * @param $limitationType String: should be one of:
2996 * 'expensive-parserfunction' (corresponding messages:
2997 * 'expensive-parserfunction-warning',
2998 * 'expensive-parserfunction-category')
2999 * 'post-expand-template-argument' (corresponding messages:
3000 * 'post-expand-template-argument-warning',
3001 * 'post-expand-template-argument-category')
3002 * 'post-expand-template-inclusion' (corresponding messages:
3003 * 'post-expand-template-inclusion-warning',
3004 * 'post-expand-template-inclusion-category')
3005 * @param $current Current value
3006 * @param $max Maximum allowed, when an explicit limit has been
3007 * exceeded, provide the values (optional)
3009 function limitationWarn( $limitationType, $current=null, $max=null) {
3010 # does no harm if $current and $max are present but are unnecessary for the message
3011 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3012 $this->mOutput
->addWarning( $warning );
3013 $this->addTrackingCategory( "$limitationType-category" );
3017 * Return the text of a template, after recursively
3018 * replacing any variables or templates within the template.
3020 * @param $piece Array: the parts of the template
3021 * $piece['title']: the title, i.e. the part before the |
3022 * $piece['parts']: the parameter array
3023 * $piece['lineStart']: whether the brace was at the start of a line
3024 * @param $frame PPFrame The current frame, contains template arguments
3025 * @return String: the text of the template
3028 function braceSubstitution( $piece, $frame ) {
3029 global $wgContLang, $wgNonincludableNamespaces;
3030 wfProfileIn( __METHOD__
);
3031 wfProfileIn( __METHOD__
.'-setup' );
3034 $found = false; # $text has been filled
3035 $nowiki = false; # wiki markup in $text should be escaped
3036 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3037 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3038 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3039 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3041 # Title object, where $text came from
3044 # $part1 is the bit before the first |, and must contain only title characters.
3045 # Various prefixes will be stripped from it later.
3046 $titleWithSpaces = $frame->expand( $piece['title'] );
3047 $part1 = trim( $titleWithSpaces );
3050 # Original title text preserved for various purposes
3051 $originalTitle = $part1;
3053 # $args is a list of argument nodes, starting from index 0, not including $part1
3054 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3055 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3056 wfProfileOut( __METHOD__
.'-setup' );
3057 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3060 wfProfileIn( __METHOD__
.'-modifiers' );
3063 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3065 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3066 # Decide whether to expand template or keep wikitext as-is.
3067 if ( $this->ot
['wiki'] ) {
3068 if ( $substMatch === false ) {
3069 $literal = true; # literal when in PST with no prefix
3071 $literal = false; # expand when in PST with subst: or safesubst:
3074 if ( $substMatch == 'subst' ) {
3075 $literal = true; # literal when not in PST with plain subst:
3077 $literal = false; # expand when not in PST with safesubst: or no prefix
3081 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3088 if ( !$found && $args->getLength() == 0 ) {
3089 $id = $this->mVariables
->matchStartToEnd( $part1 );
3090 if ( $id !== false ) {
3091 $text = $this->getVariableValue( $id, $frame );
3092 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3093 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3099 # MSG, MSGNW and RAW
3102 $mwMsgnw = MagicWord
::get( 'msgnw' );
3103 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3106 # Remove obsolete MSG:
3107 $mwMsg = MagicWord
::get( 'msg' );
3108 $mwMsg->matchStartAndRemove( $part1 );
3112 $mwRaw = MagicWord
::get( 'raw' );
3113 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3114 $forceRawInterwiki = true;
3117 wfProfileOut( __METHOD__
.'-modifiers' );
3121 wfProfileIn( __METHOD__
. '-pfunc' );
3123 $colonPos = strpos( $part1, ':' );
3124 if ( $colonPos !== false ) {
3125 # Case sensitive functions
3126 $function = substr( $part1, 0, $colonPos );
3127 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3128 $function = $this->mFunctionSynonyms
[1][$function];
3130 # Case insensitive functions
3131 $function = $wgContLang->lc( $function );
3132 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3133 $function = $this->mFunctionSynonyms
[0][$function];
3139 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3140 $initialArgs = array( &$this );
3141 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3142 if ( $flags & SFH_OBJECT_ARGS
) {
3143 # Add a frame parameter, and pass the arguments as an array
3144 $allArgs = $initialArgs;
3145 $allArgs[] = $frame;
3146 for ( $i = 0; $i < $args->getLength(); $i++
) {
3147 $funcArgs[] = $args->item( $i );
3149 $allArgs[] = $funcArgs;
3151 # Convert arguments to plain text
3152 for ( $i = 0; $i < $args->getLength(); $i++
) {
3153 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3155 $allArgs = array_merge( $initialArgs, $funcArgs );
3158 # Workaround for PHP bug 35229 and similar
3159 if ( !is_callable( $callback ) ) {
3160 wfProfileOut( __METHOD__
. '-pfunc' );
3161 wfProfileOut( __METHOD__
);
3162 throw new MWException( "Tag hook for $function is not callable\n" );
3164 $result = call_user_func_array( $callback, $allArgs );
3167 $preprocessFlags = 0;
3169 if ( is_array( $result ) ) {
3170 if ( isset( $result[0] ) ) {
3172 unset( $result[0] );
3175 # Extract flags into the local scope
3176 # This allows callers to set flags such as nowiki, found, etc.
3182 $text = $this->preprocessToDom( $text, $preprocessFlags );
3187 wfProfileOut( __METHOD__
. '-pfunc' );
3190 # Finish mangling title and then check for loops.
3191 # Set $title to a Title object and $titleText to the PDBK
3194 # Split the title into page and subpage
3196 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3197 if ( $subpage !== '' ) {
3198 $ns = $this->mTitle
->getNamespace();
3200 $title = Title
::newFromText( $part1, $ns );
3202 $titleText = $title->getPrefixedText();
3203 # Check for language variants if the template is not found
3204 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3205 $wgContLang->findVariantLink( $part1, $title, true );
3207 # Do recursion depth check
3208 $limit = $this->mOptions
->getMaxTemplateDepth();
3209 if ( $frame->depth
>= $limit ) {
3211 $text = '<span class="error">'
3212 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3218 # Load from database
3219 if ( !$found && $title ) {
3220 wfProfileIn( __METHOD__
. '-loadtpl' );
3221 if ( !$title->isExternal() ) {
3222 if ( $title->getNamespace() == NS_SPECIAL
3223 && $this->mOptions
->getAllowSpecialInclusion()
3224 && $this->ot
['html'] )
3226 $text = SpecialPageFactory
::capturePath( $title );
3227 if ( is_string( $text ) ) {
3230 $this->disableCache();
3232 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3233 $found = false; # access denied
3234 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3236 list( $text, $title ) = $this->getTemplateDom( $title );
3237 if ( $text !== false ) {
3243 # If the title is valid but undisplayable, make a link to it
3244 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3245 $text = "[[:$titleText]]";
3248 } elseif ( $title->isTrans() ) {
3249 # Interwiki transclusion
3250 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3251 $text = $this->interwikiTransclude( $title, 'render' );
3254 $text = $this->interwikiTransclude( $title, 'raw' );
3255 # Preprocess it like a template
3256 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3262 # Do infinite loop check
3263 # This has to be done after redirect resolution to avoid infinite loops via redirects
3264 if ( !$frame->loopCheck( $title ) ) {
3266 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3267 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3269 wfProfileOut( __METHOD__
. '-loadtpl' );
3272 # If we haven't found text to substitute by now, we're done
3273 # Recover the source wikitext and return it
3275 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3276 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3277 wfProfileOut( __METHOD__
);
3278 return array( 'object' => $text );
3281 # Expand DOM-style return values in a child frame
3282 if ( $isChildObj ) {
3283 # Clean up argument array
3284 $newFrame = $frame->newChild( $args, $title );
3287 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3288 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3289 # Expansion is eligible for the empty-frame cache
3290 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3291 $text = $this->mTplExpandCache
[$titleText];
3293 $text = $newFrame->expand( $text );
3294 $this->mTplExpandCache
[$titleText] = $text;
3297 # Uncached expansion
3298 $text = $newFrame->expand( $text );
3301 if ( $isLocalObj && $nowiki ) {
3302 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3303 $isLocalObj = false;
3306 # Replace raw HTML by a placeholder
3307 # Add a blank line preceding, to prevent it from mucking up
3308 # immediately preceding headings
3310 $text = "\n\n" . $this->insertStripItem( $text );
3311 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3312 # Escape nowiki-style return values
3313 $text = wfEscapeWikiText( $text );
3314 } elseif ( is_string( $text )
3315 && !$piece['lineStart']
3316 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3318 # Bug 529: if the template begins with a table or block-level
3319 # element, it should be treated as beginning a new line.
3320 # This behaviour is somewhat controversial.
3321 $text = "\n" . $text;
3324 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3325 # Error, oversize inclusion
3326 if ( $titleText !== false ) {
3327 # Make a working, properly escaped link if possible (bug 23588)
3328 $text = "[[:$titleText]]";
3330 # This will probably not be a working link, but at least it may
3331 # provide some hint of where the problem is
3332 preg_replace( '/^:/', '', $originalTitle );
3333 $text = "[[:$originalTitle]]";
3335 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3336 $this->limitationWarn( 'post-expand-template-inclusion' );
3339 if ( $isLocalObj ) {
3340 $ret = array( 'object' => $text );
3342 $ret = array( 'text' => $text );
3345 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3346 wfProfileOut( __METHOD__
);
3351 * Get the semi-parsed DOM representation of a template with a given title,
3352 * and its redirect destination title. Cached.
3356 function getTemplateDom( $title ) {
3357 $cacheTitle = $title;
3358 $titleText = $title->getPrefixedDBkey();
3360 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3361 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3362 $title = Title
::makeTitle( $ns, $dbk );
3363 $titleText = $title->getPrefixedDBkey();
3365 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3366 return array( $this->mTplDomCache
[$titleText], $title );
3369 # Cache miss, go to the database
3370 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3372 if ( $text === false ) {
3373 $this->mTplDomCache
[$titleText] = false;
3374 return array( false, $title );
3377 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3378 $this->mTplDomCache
[ $titleText ] = $dom;
3380 if ( !$title->equals( $cacheTitle ) ) {
3381 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3382 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3385 return array( $dom, $title );
3389 * Fetch the unparsed text of a template and register a reference to it.
3390 * @param Title $title
3391 * @return Array ( string or false, Title )
3393 function fetchTemplateAndTitle( $title ) {
3394 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3395 $stuff = call_user_func( $templateCb, $title, $this );
3396 $text = $stuff['text'];
3397 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3398 if ( isset( $stuff['deps'] ) ) {
3399 foreach ( $stuff['deps'] as $dep ) {
3400 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3403 return array( $text, $finalTitle );
3407 * Fetch the unparsed text of a template and register a reference to it.
3408 * @param Title $title
3409 * @return mixed string or false
3411 function fetchTemplate( $title ) {
3412 $rv = $this->fetchTemplateAndTitle( $title );
3417 * Static function to get a template
3418 * Can be overridden via ParserOptions::setTemplateCallback().
3422 static function statelessFetchTemplate( $title, $parser = false ) {
3423 $text = $skip = false;
3424 $finalTitle = $title;
3427 # Loop to fetch the article, with up to 1 redirect
3428 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3429 # Give extensions a chance to select the revision instead
3430 $id = false; # Assume current
3431 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3432 array( $parser, $title, &$skip, &$id ) );
3438 'page_id' => $title->getArticleID(),
3445 ? Revision
::newFromId( $id )
3446 : Revision
::newFromTitle( $title );
3447 $rev_id = $rev ?
$rev->getId() : 0;
3448 # If there is no current revision, there is no page
3449 if ( $id === false && !$rev ) {
3450 $linkCache = LinkCache
::singleton();
3451 $linkCache->addBadLinkObj( $title );
3456 'page_id' => $title->getArticleID(),
3457 'rev_id' => $rev_id );
3458 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3459 # We fetched a rev from a different title; register it too...
3461 'title' => $rev->getTitle(),
3462 'page_id' => $rev->getPage(),
3463 'rev_id' => $rev_id );
3467 $text = $rev->getText();
3468 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3470 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3471 if ( !$message->exists() ) {
3475 $text = $message->plain();
3479 if ( $text === false ) {
3483 $finalTitle = $title;
3484 $title = Title
::newFromRedirect( $text );
3488 'finalTitle' => $finalTitle,
3493 * Fetch a file and its title and register a reference to it.
3494 * @param Title $title
3495 * @param string $time MW timestamp
3496 * @param string $sha1 base 36 SHA-1
3497 * @return mixed File or false
3499 function fetchFile( $title, $time = false, $sha1 = false ) {
3500 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3505 * Fetch a file and its title and register a reference to it.
3506 * @param Title $title
3507 * @param string $time MW timestamp
3508 * @param string $sha1 base 36 SHA-1
3509 * @return Array ( File or false, Title of file )
3511 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3512 if ( $time === '0' ) {
3513 $file = false; // broken thumbnail forced by hook
3514 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3515 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3516 } else { // get by (name,timestamp)
3517 $file = wfFindFile( $title, array( 'time' => $time ) );
3519 $time = $file ?
$file->getTimestamp() : false;
3520 $sha1 = $file ?
$file->getSha1() : false;
3521 # Register the file as a dependency...
3522 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3523 if ( $file && !$title->equals( $file->getTitle() ) ) {
3524 # Update fetched file title
3525 $title = $file->getTitle();
3527 return array( $file, $title );
3531 * Transclude an interwiki link.
3533 * @param $title Title
3538 function interwikiTransclude( $title, $action ) {
3539 global $wgEnableScaryTranscluding;
3541 if ( !$wgEnableScaryTranscluding ) {
3542 return wfMsgForContent('scarytranscludedisabled');
3545 $url = $title->getFullUrl( "action=$action" );
3547 if ( strlen( $url ) > 255 ) {
3548 return wfMsgForContent( 'scarytranscludetoolong' );
3550 return $this->fetchScaryTemplateMaybeFromCache( $url );
3554 * @param $url string
3555 * @return Mixed|String
3557 function fetchScaryTemplateMaybeFromCache( $url ) {
3558 global $wgTranscludeCacheExpiry;
3559 $dbr = wfGetDB( DB_SLAVE
);
3560 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3561 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3562 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3564 return $obj->tc_contents
;
3567 $text = Http
::get( $url );
3569 return wfMsgForContent( 'scarytranscludefailed', $url );
3572 $dbw = wfGetDB( DB_MASTER
);
3573 $dbw->replace( 'transcache', array('tc_url'), array(
3575 'tc_time' => $dbw->timestamp( time() ),
3576 'tc_contents' => $text)
3582 * Triple brace replacement -- used for template arguments
3585 * @param $peice array
3586 * @param $frame PPFrame
3590 function argSubstitution( $piece, $frame ) {
3591 wfProfileIn( __METHOD__
);
3594 $parts = $piece['parts'];
3595 $nameWithSpaces = $frame->expand( $piece['title'] );
3596 $argName = trim( $nameWithSpaces );
3598 $text = $frame->getArgument( $argName );
3599 if ( $text === false && $parts->getLength() > 0
3603 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3606 # No match in frame, use the supplied default
3607 $object = $parts->item( 0 )->getChildren();
3609 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3610 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3611 $this->limitationWarn( 'post-expand-template-argument' );
3614 if ( $text === false && $object === false ) {
3616 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3618 if ( $error !== false ) {
3621 if ( $object !== false ) {
3622 $ret = array( 'object' => $object );
3624 $ret = array( 'text' => $text );
3627 wfProfileOut( __METHOD__
);
3632 * Return the text to be used for a given extension tag.
3633 * This is the ghost of strip().
3635 * @param $params Associative array of parameters:
3636 * name PPNode for the tag name
3637 * attr PPNode for unparsed text where tag attributes are thought to be
3638 * attributes Optional associative array of parsed attributes
3639 * inner Contents of extension element
3640 * noClose Original text did not have a close tag
3641 * @param $frame PPFrame
3645 function extensionSubstitution( $params, $frame ) {
3646 $name = $frame->expand( $params['name'] );
3647 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3648 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3649 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3651 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3652 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3653 if ( $isFunctionTag ) {
3654 $markerType = 'none';
3656 $markerType = 'general';
3658 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3659 $name = strtolower( $name );
3660 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3661 if ( isset( $params['attributes'] ) ) {
3662 $attributes = $attributes +
$params['attributes'];
3665 if ( isset( $this->mTagHooks
[$name] ) ) {
3666 # Workaround for PHP bug 35229 and similar
3667 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3668 throw new MWException( "Tag hook for $name is not callable\n" );
3670 $output = call_user_func_array( $this->mTagHooks
[$name],
3671 array( $content, $attributes, $this, $frame ) );
3672 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3673 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3674 if ( !is_callable( $callback ) ) {
3675 throw new MWException( "Tag hook for $name is not callable\n" );
3678 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3680 $output = '<span class="error">Invalid tag extension name: ' .
3681 htmlspecialchars( $name ) . '</span>';
3684 if ( is_array( $output ) ) {
3685 # Extract flags to local scope (to override $markerType)
3687 $output = $flags[0];
3692 if ( is_null( $attrText ) ) {
3695 if ( isset( $params['attributes'] ) ) {
3696 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3697 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3698 htmlspecialchars( $attrValue ) . '"';
3701 if ( $content === null ) {
3702 $output = "<$name$attrText/>";
3704 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3705 $output = "<$name$attrText>$content$close";
3709 if ( $markerType === 'none' ) {
3711 } elseif ( $markerType === 'nowiki' ) {
3712 $this->mStripState
->addNoWiki( $marker, $output );
3713 } elseif ( $markerType === 'general' ) {
3714 $this->mStripState
->addGeneral( $marker, $output );
3716 throw new MWException( __METHOD__
.': invalid marker type' );
3722 * Increment an include size counter
3724 * @param $type String: the type of expansion
3725 * @param $size Integer: the size of the text
3726 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3728 function incrementIncludeSize( $type, $size ) {
3729 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3732 $this->mIncludeSizes
[$type] +
= $size;
3738 * Increment the expensive function count
3740 * @return Boolean: false if the limit has been exceeded
3742 function incrementExpensiveFunctionCount() {
3743 global $wgExpensiveParserFunctionLimit;
3744 $this->mExpensiveFunctionCount++
;
3745 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3752 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3753 * Fills $this->mDoubleUnderscores, returns the modified text
3755 function doDoubleUnderscore( $text ) {
3756 wfProfileIn( __METHOD__
);
3758 # The position of __TOC__ needs to be recorded
3759 $mw = MagicWord
::get( 'toc' );
3760 if ( $mw->match( $text ) ) {
3761 $this->mShowToc
= true;
3762 $this->mForceTocPosition
= true;
3764 # Set a placeholder. At the end we'll fill it in with the TOC.
3765 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3767 # Only keep the first one.
3768 $text = $mw->replace( '', $text );
3771 # Now match and remove the rest of them
3772 $mwa = MagicWord
::getDoubleUnderscoreArray();
3773 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3775 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3776 $this->mOutput
->mNoGallery
= true;
3778 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3779 $this->mShowToc
= false;
3781 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3782 $this->addTrackingCategory( 'hidden-category-category' );
3784 # (bug 8068) Allow control over whether robots index a page.
3786 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3787 # is not desirable, the last one on the page should win.
3788 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3789 $this->mOutput
->setIndexPolicy( 'noindex' );
3790 $this->addTrackingCategory( 'noindex-category' );
3792 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3793 $this->mOutput
->setIndexPolicy( 'index' );
3794 $this->addTrackingCategory( 'index-category' );
3797 # Cache all double underscores in the database
3798 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3799 $this->mOutput
->setProperty( $key, '' );
3802 wfProfileOut( __METHOD__
);
3807 * Add a tracking category, getting the title from a system message,
3808 * or print a debug message if the title is invalid.
3810 * @param $msg String: message key
3811 * @return Boolean: whether the addition was successful
3813 protected function addTrackingCategory( $msg ) {
3814 $cat = wfMsgForContent( $msg );
3816 # Allow tracking categories to be disabled by setting them to "-"
3817 if ( $cat === '-' ) {
3821 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3822 if ( $containerCategory ) {
3823 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3826 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3832 * This function accomplishes several tasks:
3833 * 1) Auto-number headings if that option is enabled
3834 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3835 * 3) Add a Table of contents on the top for users who have enabled the option
3836 * 4) Auto-anchor headings
3838 * It loops through all headlines, collects the necessary data, then splits up the
3839 * string and re-inserts the newly formatted headlines.
3841 * @param $text String
3842 * @param $origText String: original, untouched wikitext
3843 * @param $isMain Boolean
3846 function formatHeadings( $text, $origText, $isMain=true ) {
3847 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3849 # Inhibit editsection links if requested in the page
3850 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3853 $showEditLink = $this->mOptions
->getEditSection();
3855 if ( $showEditLink ) {
3856 $this->mOutput
->setEditSectionTokens( true );
3859 # Get all headlines for numbering them and adding funky stuff like [edit]
3860 # links - this is for later, but we need the number of headlines right now
3862 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3864 # if there are fewer than 4 headlines in the article, do not show TOC
3865 # unless it's been explicitly enabled.
3866 $enoughToc = $this->mShowToc
&&
3867 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3869 # Allow user to stipulate that a page should have a "new section"
3870 # link added via __NEWSECTIONLINK__
3871 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3872 $this->mOutput
->setNewSection( true );
3875 # Allow user to remove the "new section"
3876 # link via __NONEWSECTIONLINK__
3877 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3878 $this->mOutput
->hideNewSection( true );
3881 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3882 # override above conditions and always show TOC above first header
3883 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3884 $this->mShowToc
= true;
3892 # Ugh .. the TOC should have neat indentation levels which can be
3893 # passed to the skin functions. These are determined here
3897 $sublevelCount = array();
3898 $levelCount = array();
3903 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3904 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3905 $oldType = $this->mOutputType
;
3906 $this->setOutputType( self
::OT_WIKI
);
3907 $frame = $this->getPreprocessor()->newFrame();
3908 $root = $this->preprocessToDom( $origText );
3909 $node = $root->getFirstChild();
3914 foreach ( $matches[3] as $headline ) {
3915 $isTemplate = false;
3917 $sectionIndex = false;
3919 $markerMatches = array();
3920 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3921 $serial = $markerMatches[1];
3922 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3923 $isTemplate = ( $titleText != $baseTitleText );
3924 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3928 $prevlevel = $level;
3930 $level = $matches[1][$headlineCount];
3932 if ( $level > $prevlevel ) {
3933 # Increase TOC level
3935 $sublevelCount[$toclevel] = 0;
3936 if ( $toclevel<$wgMaxTocLevel ) {
3937 $prevtoclevel = $toclevel;
3938 $toc .= Linker
::tocIndent();
3941 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3942 # Decrease TOC level, find level to jump to
3944 for ( $i = $toclevel; $i > 0; $i-- ) {
3945 if ( $levelCount[$i] == $level ) {
3946 # Found last matching level
3949 } elseif ( $levelCount[$i] < $level ) {
3950 # Found first matching level below current level
3958 if ( $toclevel<$wgMaxTocLevel ) {
3959 if ( $prevtoclevel < $wgMaxTocLevel ) {
3960 # Unindent only if the previous toc level was shown :p
3961 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3962 $prevtoclevel = $toclevel;
3964 $toc .= Linker
::tocLineEnd();
3968 # No change in level, end TOC line
3969 if ( $toclevel<$wgMaxTocLevel ) {
3970 $toc .= Linker
::tocLineEnd();
3974 $levelCount[$toclevel] = $level;
3976 # count number of headlines for each level
3977 @$sublevelCount[$toclevel]++
;
3979 for( $i = 1; $i <= $toclevel; $i++
) {
3980 if ( !empty( $sublevelCount[$i] ) ) {
3984 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3989 # The safe header is a version of the header text safe to use for links
3990 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3991 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3993 # Remove link placeholders by the link text.
3994 # <!--LINK number-->
3996 # link text with suffix
3997 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3999 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4000 $tocline = preg_replace(
4001 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4002 array( '', '<$1>' ),
4005 $tocline = trim( $tocline );
4007 # For the anchor, strip out HTML-y stuff period
4008 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4009 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4011 # Save headline for section edit hint before it's escaped
4012 $headlineHint = $safeHeadline;
4014 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4015 # For reverse compatibility, provide an id that's
4016 # HTML4-compatible, like we used to.
4018 # It may be worth noting, academically, that it's possible for
4019 # the legacy anchor to conflict with a non-legacy headline
4020 # anchor on the page. In this case likely the "correct" thing
4021 # would be to either drop the legacy anchors or make sure
4022 # they're numbered first. However, this would require people
4023 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4024 # manually, so let's not bother worrying about it.
4025 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4026 array( 'noninitial', 'legacy' ) );
4027 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4029 if ( $legacyHeadline == $safeHeadline ) {
4030 # No reason to have both (in fact, we can't)
4031 $legacyHeadline = false;
4034 $legacyHeadline = false;
4035 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4039 # HTML names must be case-insensitively unique (bug 10721).
4040 # This does not apply to Unicode characters per
4041 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4042 # @todo FIXME: We may be changing them depending on the current locale.
4043 $arrayKey = strtolower( $safeHeadline );
4044 if ( $legacyHeadline === false ) {
4045 $legacyArrayKey = false;
4047 $legacyArrayKey = strtolower( $legacyHeadline );
4050 # count how many in assoc. array so we can track dupes in anchors
4051 if ( isset( $refers[$arrayKey] ) ) {
4052 $refers[$arrayKey]++
;
4054 $refers[$arrayKey] = 1;
4056 if ( isset( $refers[$legacyArrayKey] ) ) {
4057 $refers[$legacyArrayKey]++
;
4059 $refers[$legacyArrayKey] = 1;
4062 # Don't number the heading if it is the only one (looks silly)
4063 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4064 # the two are different if the line contains a link
4065 $headline = $numbering . ' ' . $headline;
4068 # Create the anchor for linking from the TOC to the section
4069 $anchor = $safeHeadline;
4070 $legacyAnchor = $legacyHeadline;
4071 if ( $refers[$arrayKey] > 1 ) {
4072 $anchor .= '_' . $refers[$arrayKey];
4074 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4075 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4077 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4078 $toc .= Linker
::tocLine( $anchor, $tocline,
4079 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4082 # Add the section to the section tree
4083 # Find the DOM node for this header
4084 while ( $node && !$isTemplate ) {
4085 if ( $node->getName() === 'h' ) {
4086 $bits = $node->splitHeading();
4087 if ( $bits['i'] == $sectionIndex ) {
4091 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4092 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4093 $node = $node->getNextSibling();
4096 'toclevel' => $toclevel,
4099 'number' => $numbering,
4100 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4101 'fromtitle' => $titleText,
4102 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4103 'anchor' => $anchor,
4106 # give headline the correct <h#> tag
4107 if ( $showEditLink && $sectionIndex !== false ) {
4108 // Output edit section links as markers with styles that can be customized by skins
4109 if ( $isTemplate ) {
4110 # Put a T flag in the section identifier, to indicate to extractSections()
4111 # that sections inside <includeonly> should be counted.
4112 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4114 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4116 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4117 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4118 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4119 // so we don't have to worry about a user trying to input one of these markers directly.
4120 // We use a page and section attribute to stop the language converter from converting these important bits
4121 // of data, but put the headline hint inside a content block because the language converter is supposed to
4122 // be able to convert that piece of data.
4123 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4124 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4125 if ( isset($editlinkArgs[2]) ) {
4126 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4133 $head[$headlineCount] = Linker
::makeHeadline( $level,
4134 $matches['attrib'][$headlineCount], $anchor, $headline,
4135 $editlink, $legacyAnchor );
4140 $this->setOutputType( $oldType );
4142 # Never ever show TOC if no headers
4143 if ( $numVisible < 1 ) {
4148 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4149 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4151 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4152 $this->mOutput
->setTOCHTML( $toc );
4156 $this->mOutput
->setSections( $tocraw );
4159 # split up and insert constructed headlines
4161 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4164 foreach ( $blocks as $block ) {
4165 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4166 # This is the [edit] link that appears for the top block of text when
4167 # section editing is enabled
4169 # Disabled because it broke block formatting
4170 # For example, a bullet point in the top line
4171 # $full .= $sk->editSectionLink(0);
4174 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4175 # Top anchor now in skin
4179 if ( !empty( $head[$i] ) ) {
4184 if ( $this->mForceTocPosition
) {
4185 return str_replace( '<!--MWTOC-->', $toc, $full );
4192 * Transform wiki markup when saving a page by doing \r\n -> \n
4193 * conversion, substitting signatures, {{subst:}} templates, etc.
4195 * @param $text String: the text to transform
4196 * @param $title Title: the Title object for the current article
4197 * @param $user User: the User object describing the current user
4198 * @param $options ParserOptions: parsing options
4199 * @param $clearState Boolean: whether to clear the parser state first
4200 * @return String: the altered wiki markup
4202 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4203 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4204 $this->setUser( $user );
4209 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4210 if( $options->getPreSaveTransform() ) {
4211 $text = $this->pstPass2( $text, $user );
4213 $text = $this->mStripState
->unstripBoth( $text );
4215 $this->setUser( null ); #Reset
4221 * Pre-save transform helper function
4224 function pstPass2( $text, $user ) {
4225 global $wgContLang, $wgLocaltimezone;
4227 # Note: This is the timestamp saved as hardcoded wikitext to
4228 # the database, we use $wgContLang here in order to give
4229 # everyone the same signature and use the default one rather
4230 # than the one selected in each user's preferences.
4231 # (see also bug 12815)
4232 $ts = $this->mOptions
->getTimestamp();
4233 if ( isset( $wgLocaltimezone ) ) {
4234 $tz = $wgLocaltimezone;
4236 $tz = date_default_timezone_get();
4239 $unixts = wfTimestamp( TS_UNIX
, $ts );
4240 $oldtz = date_default_timezone_get();
4241 date_default_timezone_set( $tz );
4242 $ts = date( 'YmdHis', $unixts );
4243 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4245 # Allow translation of timezones through wiki. date() can return
4246 # whatever crap the system uses, localised or not, so we cannot
4247 # ship premade translations.
4248 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4249 $msg = wfMessage( $key )->inContentLanguage();
4250 if ( $msg->exists() ) {
4251 $tzMsg = $msg->text();
4254 date_default_timezone_set( $oldtz );
4256 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4258 # Variable replacement
4259 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4260 $text = $this->replaceVariables( $text );
4262 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4263 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4266 $sigText = $this->getUserSig( $user );
4267 $text = strtr( $text, array(
4269 '~~~~' => "$sigText $d",
4273 # Context links: [[|name]] and [[name (context)|]]
4274 global $wgLegalTitleChars;
4275 $tc = "[$wgLegalTitleChars]";
4276 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4278 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4279 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4280 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4281 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4283 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4284 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4285 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4286 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4288 $t = $this->mTitle
->getText();
4290 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4291 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4292 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4293 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4295 # if there's no context, don't bother duplicating the title
4296 $text = preg_replace( $p2, '[[\\1]]', $text );
4299 # Trim trailing whitespace
4300 $text = rtrim( $text );
4306 * Fetch the user's signature text, if any, and normalize to
4307 * validated, ready-to-insert wikitext.
4308 * If you have pre-fetched the nickname or the fancySig option, you can
4309 * specify them here to save a database query.
4310 * Do not reuse this parser instance after calling getUserSig(),
4311 * as it may have changed if it's the $wgParser.
4314 * @param $nickname String: nickname to use or false to use user's default nickname
4315 * @param $fancySig Boolean: whether the nicknname is the complete signature
4316 * or null to use default value
4319 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4320 global $wgMaxSigChars;
4322 $username = $user->getName();
4324 # If not given, retrieve from the user object.
4325 if ( $nickname === false )
4326 $nickname = $user->getOption( 'nickname' );
4328 if ( is_null( $fancySig ) ) {
4329 $fancySig = $user->getBoolOption( 'fancysig' );
4332 $nickname = $nickname == null ?
$username : $nickname;
4334 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4335 $nickname = $username;
4336 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4337 } elseif ( $fancySig !== false ) {
4338 # Sig. might contain markup; validate this
4339 if ( $this->validateSig( $nickname ) !== false ) {
4340 # Validated; clean up (if needed) and return it
4341 return $this->cleanSig( $nickname, true );
4343 # Failed to validate; fall back to the default
4344 $nickname = $username;
4345 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4349 # Make sure nickname doesnt get a sig in a sig
4350 $nickname = $this->cleanSigInSig( $nickname );
4352 # If we're still here, make it a link to the user page
4353 $userText = wfEscapeWikiText( $username );
4354 $nickText = wfEscapeWikiText( $nickname );
4355 if ( $user->isAnon() ) {
4356 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4358 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4363 * Check that the user's signature contains no bad XML
4365 * @param $text String
4366 * @return mixed An expanded string, or false if invalid.
4368 function validateSig( $text ) {
4369 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4373 * Clean up signature text
4375 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4376 * 2) Substitute all transclusions
4378 * @param $text String
4379 * @param $parsing Whether we're cleaning (preferences save) or parsing
4380 * @return String: signature text
4382 function cleanSig( $text, $parsing = false ) {
4385 $this->mOptions
= new ParserOptions
;
4386 $this->clearState();
4387 $this->setTitle( $wgTitle );
4388 $this->setOutputType
= self
::OT_PREPROCESS
;
4391 # Option to disable this feature
4392 if ( !$this->mOptions
->getCleanSignatures() ) {
4396 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4397 # => Move this logic to braceSubstitution()
4398 $substWord = MagicWord
::get( 'subst' );
4399 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4400 $substText = '{{' . $substWord->getSynonym( 0 );
4402 $text = preg_replace( $substRegex, $substText, $text );
4403 $text = $this->cleanSigInSig( $text );
4404 $dom = $this->preprocessToDom( $text );
4405 $frame = $this->getPreprocessor()->newFrame();
4406 $text = $frame->expand( $dom );
4409 $text = $this->mStripState
->unstripBoth( $text );
4416 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4418 * @param $text String
4419 * @return String: signature text with /~{3,5}/ removed
4421 function cleanSigInSig( $text ) {
4422 $text = preg_replace( '/~{3,5}/', '', $text );
4427 * Set up some variables which are usually set up in parse()
4428 * so that an external function can call some class members with confidence
4430 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4431 $this->startParse( $title, $options, $outputType, $clearState );
4434 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4435 $this->setTitle( $title );
4436 $this->mOptions
= $options;
4437 $this->setOutputType( $outputType );
4438 if ( $clearState ) {
4439 $this->clearState();
4444 * Wrapper for preprocess()
4446 * @param $text String: the text to preprocess
4447 * @param $options ParserOptions: options
4448 * @param $title Title object or null to use $wgTitle
4451 public function transformMsg( $text, $options, $title = null ) {
4452 static $executing = false;
4454 # Guard against infinite recursion
4460 wfProfileIn( __METHOD__
);
4466 # It's not uncommon having a null $wgTitle in scripts. See r80898
4467 # Create a ghost title in such case
4468 $title = Title
::newFromText( 'Dwimmerlaik' );
4470 $text = $this->preprocess( $text, $title, $options );
4473 wfProfileOut( __METHOD__
);
4478 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4479 * The callback should have the following form:
4480 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4482 * Transform and return $text. Use $parser for any required context, e.g. use
4483 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4485 * Hooks may return extended information by returning an array, of which the
4486 * first numbered element (index 0) must be the return string, and all other
4487 * entries are extracted into local variables within an internal function
4488 * in the Parser class.
4490 * This interface (introduced r61913) appears to be undocumented, but
4491 * 'markerName' is used by some core tag hooks to override which strip
4492 * array their results are placed in. **Use great caution if attempting
4493 * this interface, as it is not documented and injudicious use could smash
4494 * private variables.**
4496 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4497 * @param $callback Mixed: the callback function (and object) to use for the tag
4498 * @return The old value of the mTagHooks array associated with the hook
4500 public function setHook( $tag, $callback ) {
4501 $tag = strtolower( $tag );
4502 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4503 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4504 $this->mTagHooks
[$tag] = $callback;
4505 if ( !in_array( $tag, $this->mStripList
) ) {
4506 $this->mStripList
[] = $tag;
4513 * As setHook(), but letting the contents be parsed.
4515 * Transparent tag hooks are like regular XML-style tag hooks, except they
4516 * operate late in the transformation sequence, on HTML instead of wikitext.
4518 * This is probably obsoleted by things dealing with parser frames?
4519 * The only extension currently using it is geoserver.
4522 * @todo better document or deprecate this
4524 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4525 * @param $callback Mixed: the callback function (and object) to use for the tag
4526 * @return The old value of the mTagHooks array associated with the hook
4528 function setTransparentTagHook( $tag, $callback ) {
4529 $tag = strtolower( $tag );
4530 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4531 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4532 $this->mTransparentTagHooks
[$tag] = $callback;
4538 * Remove all tag hooks
4540 function clearTagHooks() {
4541 $this->mTagHooks
= array();
4542 $this->mStripList
= $this->mDefaultStripList
;
4546 * Remove a specific tag hook. Should not be called on $wgParser.
4547 * Does not change the strip list.
4549 * @param string $tag
4552 function clearTagHook( $tag ) {
4553 if ( isset( $this->mTagHooks
[$tag] ) ) {
4554 unset( $this->mTagHooks
[$tag] );
4559 * Create a function, e.g. {{sum:1|2|3}}
4560 * The callback function should have the form:
4561 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4563 * Or with SFH_OBJECT_ARGS:
4564 * function myParserFunction( $parser, $frame, $args ) { ... }
4566 * The callback may either return the text result of the function, or an array with the text
4567 * in element 0, and a number of flags in the other elements. The names of the flags are
4568 * specified in the keys. Valid flags are:
4569 * found The text returned is valid, stop processing the template. This
4571 * nowiki Wiki markup in the return value should be escaped
4572 * isHTML The returned text is HTML, armour it against wikitext transformation
4574 * @param $id String: The magic word ID
4575 * @param $callback Mixed: the callback function (and object) to use
4576 * @param $flags Integer: a combination of the following flags:
4577 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4579 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4580 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4581 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4582 * the arguments, and to control the way they are expanded.
4584 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4585 * arguments, for instance:
4586 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4588 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4589 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4590 * working if/when this is changed.
4592 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4595 * Please read the documentation in includes/parser/Preprocessor.php for more information
4596 * about the methods available in PPFrame and PPNode.
4598 * @return The old callback function for this name, if any
4600 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4603 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4604 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4606 # Add to function cache
4607 $mw = MagicWord
::get( $id );
4609 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4611 $synonyms = $mw->getSynonyms();
4612 $sensitive = intval( $mw->isCaseSensitive() );
4614 foreach ( $synonyms as $syn ) {
4616 if ( !$sensitive ) {
4617 $syn = $wgContLang->lc( $syn );
4620 if ( !( $flags & SFH_NO_HASH
) ) {
4623 # Remove trailing colon
4624 if ( substr( $syn, -1, 1 ) === ':' ) {
4625 $syn = substr( $syn, 0, -1 );
4627 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4633 * Get all registered function hook identifiers
4637 function getFunctionHooks() {
4638 return array_keys( $this->mFunctionHooks
);
4642 * Create a tag function, e.g. <test>some stuff</test>.
4643 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4644 * Unlike parser functions, their content is not preprocessed.
4646 function setFunctionTagHook( $tag, $callback, $flags ) {
4647 $tag = strtolower( $tag );
4648 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4649 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4650 $this->mFunctionTagHooks
[$tag] : null;
4651 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4653 if ( !in_array( $tag, $this->mStripList
) ) {
4654 $this->mStripList
[] = $tag;
4661 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4662 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4663 * Placeholders created in Skin::makeLinkObj()
4664 * Returns an array of link CSS classes, indexed by PDBK.
4666 function replaceLinkHolders( &$text, $options = 0 ) {
4667 return $this->mLinkHolders
->replace( $text );
4671 * Replace <!--LINK--> link placeholders with plain text of links
4672 * (not HTML-formatted).
4674 * @param $text String
4677 function replaceLinkHoldersText( $text ) {
4678 return $this->mLinkHolders
->replaceText( $text );
4682 * Renders an image gallery from a text with one line per image.
4683 * text labels may be given by using |-style alternative text. E.g.
4684 * Image:one.jpg|The number "1"
4685 * Image:tree.jpg|A tree
4686 * given as text will return the HTML of a gallery with two images,
4687 * labeled 'The number "1"' and
4690 * @param string $text
4691 * @param array $param
4692 * @return string HTML
4694 function renderImageGallery( $text, $params ) {
4695 $ig = new ImageGallery();
4696 $ig->setContextTitle( $this->mTitle
);
4697 $ig->setShowBytes( false );
4698 $ig->setShowFilename( false );
4699 $ig->setParser( $this );
4700 $ig->setHideBadImages();
4701 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4703 if ( isset( $params['showfilename'] ) ) {
4704 $ig->setShowFilename( true );
4706 $ig->setShowFilename( false );
4708 if ( isset( $params['caption'] ) ) {
4709 $caption = $params['caption'];
4710 $caption = htmlspecialchars( $caption );
4711 $caption = $this->replaceInternalLinks( $caption );
4712 $ig->setCaptionHtml( $caption );
4714 if ( isset( $params['perrow'] ) ) {
4715 $ig->setPerRow( $params['perrow'] );
4717 if ( isset( $params['widths'] ) ) {
4718 $ig->setWidths( $params['widths'] );
4720 if ( isset( $params['heights'] ) ) {
4721 $ig->setHeights( $params['heights'] );
4724 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4726 $lines = StringUtils
::explode( "\n", $text );
4727 foreach ( $lines as $line ) {
4728 # match lines like these:
4729 # Image:someimage.jpg|This is some image
4731 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4733 if ( count( $matches ) == 0 ) {
4737 if ( strpos( $matches[0], '%' ) !== false ) {
4738 $matches[1] = rawurldecode( $matches[1] );
4740 $title = Title
::newFromText( $matches[1], NS_FILE
);
4741 if ( is_null( $title ) ) {
4742 # Bogus title. Ignore these so we don't bomb out later.
4748 if ( isset( $matches[3] ) ) {
4749 // look for an |alt= definition while trying not to break existing
4750 // captions with multiple pipes (|) in it, until a more sensible grammar
4751 // is defined for images in galleries
4753 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4754 $altmatches = StringUtils
::explode('|', $matches[3]);
4755 $magicWordAlt = MagicWord
::get( 'img_alt' );
4757 foreach ( $altmatches as $altmatch ) {
4758 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4760 $alt = $this->stripAltText( $match, false );
4763 // concatenate all other pipes
4764 $label .= '|' . $altmatch;
4767 // remove the first pipe
4768 $label = substr( $label, 1 );
4771 $ig->add( $title, $label, $alt );
4773 return $ig->toHTML();
4776 function getImageParams( $handler ) {
4778 $handlerClass = get_class( $handler );
4782 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4783 # Initialise static lists
4784 static $internalParamNames = array(
4785 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4786 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4787 'bottom', 'text-bottom' ),
4788 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4789 'upright', 'border', 'link', 'alt' ),
4791 static $internalParamMap;
4792 if ( !$internalParamMap ) {
4793 $internalParamMap = array();
4794 foreach ( $internalParamNames as $type => $names ) {
4795 foreach ( $names as $name ) {
4796 $magicName = str_replace( '-', '_', "img_$name" );
4797 $internalParamMap[$magicName] = array( $type, $name );
4802 # Add handler params
4803 $paramMap = $internalParamMap;
4805 $handlerParamMap = $handler->getParamMap();
4806 foreach ( $handlerParamMap as $magic => $paramName ) {
4807 $paramMap[$magic] = array( 'handler', $paramName );
4810 $this->mImageParams
[$handlerClass] = $paramMap;
4811 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4813 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4817 * Parse image options text and use it to make an image
4819 * @param $title Title
4820 * @param $options String
4821 * @param $holders LinkHolderArray
4822 * @return string HTML
4824 function makeImage( $title, $options, $holders = false ) {
4825 # Check if the options text is of the form "options|alt text"
4827 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4828 # * left no resizing, just left align. label is used for alt= only
4829 # * right same, but right aligned
4830 # * none same, but not aligned
4831 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4832 # * center center the image
4833 # * frame Keep original image size, no magnify-button.
4834 # * framed Same as "frame"
4835 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4836 # * upright reduce width for upright images, rounded to full __0 px
4837 # * border draw a 1px border around the image
4838 # * alt Text for HTML alt attribute (defaults to empty)
4839 # * link Set the target of the image link. Can be external, interwiki, or local
4840 # vertical-align values (no % or length right now):
4850 $parts = StringUtils
::explode( "|", $options );
4852 # Give extensions a chance to select the file revision for us
4853 $time = $sha1 = $descQuery = false;
4854 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4855 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4856 # Fetch and register the file (file title may be different via hooks)
4857 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4860 $handler = $file ?
$file->getHandler() : false;
4862 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4865 $this->addTrackingCategory( 'broken-file-category' );
4868 # Process the input parameters
4870 $params = array( 'frame' => array(), 'handler' => array(),
4871 'horizAlign' => array(), 'vertAlign' => array() );
4872 foreach ( $parts as $part ) {
4873 $part = trim( $part );
4874 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4876 if ( isset( $paramMap[$magicName] ) ) {
4877 list( $type, $paramName ) = $paramMap[$magicName];
4879 # Special case; width and height come in one variable together
4880 if ( $type === 'handler' && $paramName === 'width' ) {
4882 # (bug 13500) In both cases (width/height and width only),
4883 # permit trailing "px" for backward compatibility.
4884 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4885 $width = intval( $m[1] );
4886 $height = intval( $m[2] );
4887 if ( $handler->validateParam( 'width', $width ) ) {
4888 $params[$type]['width'] = $width;
4891 if ( $handler->validateParam( 'height', $height ) ) {
4892 $params[$type]['height'] = $height;
4895 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4896 $width = intval( $value );
4897 if ( $handler->validateParam( 'width', $width ) ) {
4898 $params[$type]['width'] = $width;
4901 } # else no validation -- bug 13436
4903 if ( $type === 'handler' ) {
4904 # Validate handler parameter
4905 $validated = $handler->validateParam( $paramName, $value );
4907 # Validate internal parameters
4908 switch( $paramName ) {
4911 # @todo FIXME: Possibly check validity here for
4912 # manualthumb? downstream behavior seems odd with
4913 # missing manual thumbs.
4915 $value = $this->stripAltText( $value, $holders );
4918 $chars = self
::EXT_LINK_URL_CLASS
;
4919 $prots = $this->mUrlProtocols
;
4920 if ( $value === '' ) {
4921 $paramName = 'no-link';
4924 } elseif ( preg_match( "/^$prots/", $value ) ) {
4925 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4926 $paramName = 'link-url';
4927 $this->mOutput
->addExternalLink( $value );
4928 if ( $this->mOptions
->getExternalLinkTarget() ) {
4929 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4934 $linkTitle = Title
::newFromText( $value );
4936 $paramName = 'link-title';
4937 $value = $linkTitle;
4938 $this->mOutput
->addLink( $linkTitle );
4944 # Most other things appear to be empty or numeric...
4945 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4950 $params[$type][$paramName] = $value;
4954 if ( !$validated ) {
4959 # Process alignment parameters
4960 if ( $params['horizAlign'] ) {
4961 $params['frame']['align'] = key( $params['horizAlign'] );
4963 if ( $params['vertAlign'] ) {
4964 $params['frame']['valign'] = key( $params['vertAlign'] );
4967 $params['frame']['caption'] = $caption;
4969 # Will the image be presented in a frame, with the caption below?
4970 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4971 isset( $params['frame']['framed'] ) ||
4972 isset( $params['frame']['thumbnail'] ) ||
4973 isset( $params['frame']['manualthumb'] );
4975 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4976 # came to also set the caption, ordinary text after the image -- which
4977 # makes no sense, because that just repeats the text multiple times in
4978 # screen readers. It *also* came to set the title attribute.
4980 # Now that we have an alt attribute, we should not set the alt text to
4981 # equal the caption: that's worse than useless, it just repeats the
4982 # text. This is the framed/thumbnail case. If there's no caption, we
4983 # use the unnamed parameter for alt text as well, just for the time be-
4984 # ing, if the unnamed param is set and the alt param is not.
4986 # For the future, we need to figure out if we want to tweak this more,
4987 # e.g., introducing a title= parameter for the title; ignoring the un-
4988 # named parameter entirely for images without a caption; adding an ex-
4989 # plicit caption= parameter and preserving the old magic unnamed para-
4991 if ( $imageIsFramed ) { # Framed image
4992 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4993 # No caption or alt text, add the filename as the alt text so
4994 # that screen readers at least get some description of the image
4995 $params['frame']['alt'] = $title->getText();
4997 # Do not set $params['frame']['title'] because tooltips don't make sense
4999 } else { # Inline image
5000 if ( !isset( $params['frame']['alt'] ) ) {
5001 # No alt text, use the "caption" for the alt text
5002 if ( $caption !== '') {
5003 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5005 # No caption, fall back to using the filename for the
5007 $params['frame']['alt'] = $title->getText();
5010 # Use the "caption" for the tooltip text
5011 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5014 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5016 # Linker does the rest
5017 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5018 $time, $descQuery, $this->mOptions
->getThumbSize() );
5020 # Give the handler a chance to modify the parser object
5022 $handler->parserTransformHook( $this, $file );
5030 * @param $holders LinkHolderArray
5031 * @return mixed|String
5033 protected function stripAltText( $caption, $holders ) {
5034 # Strip bad stuff out of the title (tooltip). We can't just use
5035 # replaceLinkHoldersText() here, because if this function is called
5036 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5038 $tooltip = $holders->replaceText( $caption );
5040 $tooltip = $this->replaceLinkHoldersText( $caption );
5043 # make sure there are no placeholders in thumbnail attributes
5044 # that are later expanded to html- so expand them now and
5046 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5047 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5053 * Set a flag in the output object indicating that the content is dynamic and
5054 * shouldn't be cached.
5056 function disableCache() {
5057 wfDebug( "Parser output marked as uncacheable.\n" );
5058 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5059 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5063 * Callback from the Sanitizer for expanding items found in HTML attribute
5064 * values, so they can be safely tested and escaped.
5066 * @param $text String
5067 * @param $frame PPFrame
5070 function attributeStripCallback( &$text, $frame = false ) {
5071 $text = $this->replaceVariables( $text, $frame );
5072 $text = $this->mStripState
->unstripBoth( $text );
5081 function getTags() {
5082 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5086 * Replace transparent tags in $text with the values given by the callbacks.
5088 * Transparent tag hooks are like regular XML-style tag hooks, except they
5089 * operate late in the transformation sequence, on HTML instead of wikitext.
5091 function replaceTransparentTags( $text ) {
5093 $elements = array_keys( $this->mTransparentTagHooks
);
5094 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5096 foreach ( $matches as $marker => $data ) {
5097 list( $element, $content, $params, $tag ) = $data;
5098 $tagName = strtolower( $element );
5099 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5100 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5104 $this->mStripState
->addGeneral( $marker, $output );
5110 * Break wikitext input into sections, and either pull or replace
5111 * some particular section's text.
5113 * External callers should use the getSection and replaceSection methods.
5115 * @param $text String: Page wikitext
5116 * @param $section String: a section identifier string of the form:
5117 * <flag1> - <flag2> - ... - <section number>
5119 * Currently the only recognised flag is "T", which means the target section number
5120 * was derived during a template inclusion parse, in other words this is a template
5121 * section edit link. If no flags are given, it was an ordinary section edit link.
5122 * This flag is required to avoid a section numbering mismatch when a section is
5123 * enclosed by <includeonly> (bug 6563).
5125 * The section number 0 pulls the text before the first heading; other numbers will
5126 * pull the given section along with its lower-level subsections. If the section is
5127 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5129 * @param $mode String: one of "get" or "replace"
5130 * @param $newText String: replacement text for section data.
5131 * @return String: for "get", the extracted section text.
5132 * for "replace", the whole page with the section replaced.
5134 private function extractSections( $text, $section, $mode, $newText='' ) {
5135 global $wgTitle; # not generally used but removes an ugly failure mode
5136 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5138 $frame = $this->getPreprocessor()->newFrame();
5140 # Process section extraction flags
5142 $sectionParts = explode( '-', $section );
5143 $sectionIndex = array_pop( $sectionParts );
5144 foreach ( $sectionParts as $part ) {
5145 if ( $part === 'T' ) {
5146 $flags |
= self
::PTD_FOR_INCLUSION
;
5149 # Preprocess the text
5150 $root = $this->preprocessToDom( $text, $flags );
5152 # <h> nodes indicate section breaks
5153 # They can only occur at the top level, so we can find them by iterating the root's children
5154 $node = $root->getFirstChild();
5156 # Find the target section
5157 if ( $sectionIndex == 0 ) {
5158 # Section zero doesn't nest, level=big
5159 $targetLevel = 1000;
5161 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5166 if ( $node->getName() === 'h' ) {
5167 $bits = $node->splitHeading();
5168 if ( $bits['i'] == $sectionIndex ) {
5169 $targetLevel = $bits['level'];
5173 if ( $mode === 'replace' ) {
5174 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5176 $node = $node->getNextSibling();
5182 if ( $mode === 'get' ) {
5189 # Find the end of the section, including nested sections
5191 if ( $node->getName() === 'h' ) {
5192 $bits = $node->splitHeading();
5193 $curLevel = $bits['level'];
5194 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5198 if ( $mode === 'get' ) {
5199 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5201 $node = $node->getNextSibling();
5204 # Write out the remainder (in replace mode only)
5205 if ( $mode === 'replace' ) {
5206 # Output the replacement text
5207 # Add two newlines on -- trailing whitespace in $newText is conventionally
5208 # stripped by the editor, so we need both newlines to restore the paragraph gap
5209 # Only add trailing whitespace if there is newText
5210 if ( $newText != "" ) {
5211 $outText .= $newText . "\n\n";
5215 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5216 $node = $node->getNextSibling();
5220 if ( is_string( $outText ) ) {
5221 # Re-insert stripped tags
5222 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5229 * This function returns the text of a section, specified by a number ($section).
5230 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5231 * the first section before any such heading (section 0).
5233 * If a section contains subsections, these are also returned.
5235 * @param $text String: text to look in
5236 * @param $section String: section identifier
5237 * @param $deftext String: default to return if section is not found
5238 * @return string text of the requested section
5240 public function getSection( $text, $section, $deftext='' ) {
5241 return $this->extractSections( $text, $section, "get", $deftext );
5245 * This function returns $oldtext after the content of the section
5246 * specified by $section has been replaced with $text.
5248 * @param $oldtext String: former text of the article
5249 * @param $section Numeric: section identifier
5250 * @param $text String: replacing text
5251 * @return String: modified text
5253 public function replaceSection( $oldtext, $section, $text ) {
5254 return $this->extractSections( $oldtext, $section, "replace", $text );
5258 * Get the ID of the revision we are parsing
5260 * @return Mixed: integer or null
5262 function getRevisionId() {
5263 return $this->mRevisionId
;
5267 * Get the revision object for $this->mRevisionId
5269 * @return Revision|null either a Revision object or null
5271 protected function getRevisionObject() {
5272 if ( !is_null( $this->mRevisionObject
) ) {
5273 return $this->mRevisionObject
;
5275 if ( is_null( $this->mRevisionId
) ) {
5279 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5280 return $this->mRevisionObject
;
5284 * Get the timestamp associated with the current revision, adjusted for
5285 * the default server-local timestamp
5287 function getRevisionTimestamp() {
5288 if ( is_null( $this->mRevisionTimestamp
) ) {
5289 wfProfileIn( __METHOD__
);
5291 $revObject = $this->getRevisionObject();
5292 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5294 if( $timestamp !== false ) {
5297 # The cryptic '' timezone parameter tells to use the site-default
5298 # timezone offset instead of the user settings.
5300 # Since this value will be saved into the parser cache, served
5301 # to other users, and potentially even used inside links and such,
5302 # it needs to be consistent for all visitors.
5303 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5306 wfProfileOut( __METHOD__
);
5308 return $this->mRevisionTimestamp
;
5312 * Get the name of the user that edited the last revision
5314 * @return String: user name
5316 function getRevisionUser() {
5317 if( is_null( $this->mRevisionUser
) ) {
5318 $revObject = $this->getRevisionObject();
5320 # if this template is subst: the revision id will be blank,
5321 # so just use the current user's name
5323 $this->mRevisionUser
= $revObject->getUserText();
5324 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5325 $this->mRevisionUser
= $this->getUser()->getName();
5328 return $this->mRevisionUser
;
5332 * Mutator for $mDefaultSort
5334 * @param $sort New value
5336 public function setDefaultSort( $sort ) {
5337 $this->mDefaultSort
= $sort;
5338 $this->mOutput
->setProperty( 'defaultsort', $sort );
5342 * Accessor for $mDefaultSort
5343 * Will use the empty string if none is set.
5345 * This value is treated as a prefix, so the
5346 * empty string is equivalent to sorting by
5351 public function getDefaultSort() {
5352 if ( $this->mDefaultSort
!== false ) {
5353 return $this->mDefaultSort
;
5360 * Accessor for $mDefaultSort
5361 * Unlike getDefaultSort(), will return false if none is set
5363 * @return string or false
5365 public function getCustomDefaultSort() {
5366 return $this->mDefaultSort
;
5370 * Try to guess the section anchor name based on a wikitext fragment
5371 * presumably extracted from a heading, for example "Header" from
5374 public function guessSectionNameFromWikiText( $text ) {
5375 # Strip out wikitext links(they break the anchor)
5376 $text = $this->stripSectionName( $text );
5377 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5378 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5382 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5383 * instead. For use in redirects, since IE6 interprets Redirect: headers
5384 * as something other than UTF-8 (apparently?), resulting in breakage.
5386 * @param $text String: The section name
5387 * @return string An anchor
5389 public function guessLegacySectionNameFromWikiText( $text ) {
5390 # Strip out wikitext links(they break the anchor)
5391 $text = $this->stripSectionName( $text );
5392 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5393 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5397 * Strips a text string of wikitext for use in a section anchor
5399 * Accepts a text string and then removes all wikitext from the
5400 * string and leaves only the resultant text (i.e. the result of
5401 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5402 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5403 * to create valid section anchors by mimicing the output of the
5404 * parser when headings are parsed.
5406 * @param $text String: text string to be stripped of wikitext
5407 * for use in a Section anchor
5408 * @return Filtered text string
5410 public function stripSectionName( $text ) {
5411 # Strip internal link markup
5412 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5413 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5415 # Strip external link markup
5416 # @todo FIXME: Not tolerant to blank link text
5417 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5418 # on how many empty links there are on the page - need to figure that out.
5419 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5421 # Parse wikitext quotes (italics & bold)
5422 $text = $this->doQuotes( $text );
5425 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5430 * strip/replaceVariables/unstrip for preprocessor regression testing
5434 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5435 if ( !$title instanceof Title
) {
5436 $title = Title
::newFromText( $title );
5438 $this->startParse( $title, $options, $outputType, true );
5440 $text = $this->replaceVariables( $text );
5441 $text = $this->mStripState
->unstripBoth( $text );
5442 $text = Sanitizer
::removeHTMLtags( $text );
5446 function testPst( $text, $title, $options ) {
5448 if ( !$title instanceof Title
) {
5449 $title = Title
::newFromText( $title );
5451 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5454 function testPreprocess( $text, $title, $options ) {
5455 if ( !$title instanceof Title
) {
5456 $title = Title
::newFromText( $title );
5458 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5462 * Call a callback function on all regions of the given text that are not
5463 * inside strip markers, and replace those regions with the return value
5464 * of the callback. For example, with input:
5468 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5469 * two strings will be replaced with the value returned by the callback in
5474 function markerSkipCallback( $s, $callback ) {
5477 while ( $i < strlen( $s ) ) {
5478 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5479 if ( $markerStart === false ) {
5480 $out .= call_user_func( $callback, substr( $s, $i ) );
5483 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5484 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5485 if ( $markerEnd === false ) {
5486 $out .= substr( $s, $markerStart );
5489 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5490 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5499 * Save the parser state required to convert the given half-parsed text to
5500 * HTML. "Half-parsed" in this context means the output of
5501 * recursiveTagParse() or internalParse(). This output has strip markers
5502 * from replaceVariables (extensionSubstitution() etc.), and link
5503 * placeholders from replaceLinkHolders().
5505 * Returns an array which can be serialized and stored persistently. This
5506 * array can later be loaded into another parser instance with
5507 * unserializeHalfParsedText(). The text can then be safely incorporated into
5508 * the return value of a parser hook.
5512 function serializeHalfParsedText( $text ) {
5513 wfProfileIn( __METHOD__
);
5516 'version' => self
::HALF_PARSED_VERSION
,
5517 'stripState' => $this->mStripState
->getSubState( $text ),
5518 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5520 wfProfileOut( __METHOD__
);
5525 * Load the parser state given in the $data array, which is assumed to
5526 * have been generated by serializeHalfParsedText(). The text contents is
5527 * extracted from the array, and its markers are transformed into markers
5528 * appropriate for the current Parser instance. This transformed text is
5529 * returned, and can be safely included in the return value of a parser
5532 * If the $data array has been stored persistently, the caller should first
5533 * check whether it is still valid, by calling isValidHalfParsedText().
5535 * @param $data Serialized data
5538 function unserializeHalfParsedText( $data ) {
5539 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5540 throw new MWException( __METHOD__
.': invalid version' );
5543 # First, extract the strip state.
5544 $texts = array( $data['text'] );
5545 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5547 # Now renumber links
5548 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5550 # Should be good to go.
5555 * Returns true if the given array, presumed to be generated by
5556 * serializeHalfParsedText(), is compatible with the current version of the
5559 * @param $data Array
5563 function isValidHalfParsedText( $data ) {
5564 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;