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()
116 * @var MagicWordArray
121 * @var MagicWordArray
124 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
126 # Cleared with clearState():
131 var $mAutonumber, $mDTopen;
138 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
140 * @var LinkHolderArray
145 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
146 var $mTplExpandCache; # empty-frame expansion cache
147 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
148 var $mExpensiveFunctionCount; # number of expensive parser function calls
153 var $mUser; # User object; only used when doing pre-save transform
156 # These are variables reset at least once per parse regardless of $clearState
166 var $mTitle; # Title context, used for self-link rendering and similar things
167 var $mOutputType; # Output type, one of the OT_xxx constants
168 var $ot; # Shortcut alias, see setOutputType()
169 var $mRevisionObject; # The revision object of the specified revision ID
170 var $mRevisionId; # ID to display in {{REVISIONID}} tags
171 var $mRevisionTimestamp; # The timestamp of the specified revision ID
172 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
173 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
183 public function __construct( $conf = array() ) {
184 $this->mConf
= $conf;
185 $this->mUrlProtocols
= wfUrlProtocols();
186 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
187 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
188 if ( isset( $conf['preprocessorClass'] ) ) {
189 $this->mPreprocessorClass
= $conf['preprocessorClass'];
190 } elseif ( extension_loaded( 'domxml' ) ) {
191 # PECL extension that conflicts with the core DOM extension (bug 13770)
192 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
193 $this->mPreprocessorClass
= 'Preprocessor_Hash';
194 } elseif ( extension_loaded( 'dom' ) ) {
195 $this->mPreprocessorClass
= 'Preprocessor_DOM';
197 $this->mPreprocessorClass
= 'Preprocessor_Hash';
202 * Reduce memory usage to reduce the impact of circular references
204 function __destruct() {
205 if ( isset( $this->mLinkHolders
) ) {
206 unset( $this->mLinkHolders
);
208 foreach ( $this as $name => $value ) {
209 unset( $this->$name );
214 * Do various kinds of initialisation on the first call of the parser
216 function firstCallInit() {
217 if ( !$this->mFirstCall
) {
220 $this->mFirstCall
= false;
222 wfProfileIn( __METHOD__
);
224 CoreParserFunctions
::register( $this );
225 CoreTagHooks
::register( $this );
226 $this->initialiseVariables();
228 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
229 wfProfileOut( __METHOD__
);
237 function clearState() {
238 wfProfileIn( __METHOD__
);
239 if ( $this->mFirstCall
) {
240 $this->firstCallInit();
242 $this->mOutput
= new ParserOutput
;
243 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
244 $this->mAutonumber
= 0;
245 $this->mLastSection
= '';
246 $this->mDTopen
= false;
247 $this->mIncludeCount
= array();
248 $this->mArgStack
= false;
249 $this->mInPre
= false;
250 $this->mLinkHolders
= new LinkHolderArray( $this );
252 $this->mRevisionObject
= $this->mRevisionTimestamp
=
253 $this->mRevisionId
= $this->mRevisionUser
= null;
254 $this->mVarCache
= array();
258 * Prefix for temporary replacement strings for the multipass parser.
259 * \x07 should never appear in input as it's disallowed in XML.
260 * Using it at the front also gives us a little extra robustness
261 * since it shouldn't match when butted up against identifier-like
264 * Must not consist of all title characters, or else it will change
265 * the behaviour of <nowiki> in a link.
267 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
268 # Changed to \x7f to allow XML double-parsing -- TS
269 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
270 $this->mStripState
= new StripState( $this->mUniqPrefix
);
273 # Clear these on every parse, bug 4549
274 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
276 $this->mShowToc
= true;
277 $this->mForceTocPosition
= false;
278 $this->mIncludeSizes
= array(
282 $this->mPPNodeCount
= 0;
283 $this->mDefaultSort
= false;
284 $this->mHeadings
= array();
285 $this->mDoubleUnderscores
= array();
286 $this->mExpensiveFunctionCount
= 0;
289 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
290 $this->mPreprocessor
= null;
293 wfRunHooks( 'ParserClearState', array( &$this ) );
294 wfProfileOut( __METHOD__
);
298 * Convert wikitext to HTML
299 * Do not call this function recursively.
301 * @param $text String: text we want to parse
302 * @param $title Title object
303 * @param $options ParserOptions
304 * @param $linestart boolean
305 * @param $clearState boolean
306 * @param $revid Int: number to pass in {{REVISIONID}}
307 * @return ParserOutput a ParserOutput
309 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
311 * First pass--just handle <nowiki> sections, pass the rest off
312 * to internalParse() which does all the real work.
315 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
316 $fname = __METHOD__
.'-' . wfGetCaller();
317 wfProfileIn( __METHOD__
);
318 wfProfileIn( $fname );
320 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
322 $oldRevisionId = $this->mRevisionId
;
323 $oldRevisionObject = $this->mRevisionObject
;
324 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
325 $oldRevisionUser = $this->mRevisionUser
;
326 if ( $revid !== null ) {
327 $this->mRevisionId
= $revid;
328 $this->mRevisionObject
= null;
329 $this->mRevisionTimestamp
= null;
330 $this->mRevisionUser
= null;
333 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
335 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
336 $text = $this->internalParse( $text );
338 $text = $this->mStripState
->unstripGeneral( $text );
340 # Clean up special characters, only run once, next-to-last before doBlockLevels
342 # french spaces, last one Guillemet-left
343 # only if there is something before the space
344 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
345 # french spaces, Guillemet-right
346 '/(\\302\\253) /' => '\\1 ',
347 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
349 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
351 $text = $this->doBlockLevels( $text, $linestart );
353 $this->replaceLinkHolders( $text );
356 * The page doesn't get language converted if
358 * b) Content isn't converted
359 * c) It's a conversion table
361 if ( !( $wgDisableLangConversion
362 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
363 ||
$this->mTitle
->isConversionTable() ) ) {
365 # The position of the convert() call should not be changed. it
366 # assumes that the links are all replaced and the only thing left
367 # is the <nowiki> mark.
369 $text = $wgContLang->convert( $text );
373 * A converted title will be provided in the output object if title and
374 * content conversion are enabled, the article text does not contain
375 * a conversion-suppressing double-underscore tag, and no
376 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
377 * automatic link conversion.
379 if ( !( $wgDisableLangConversion
380 ||
$wgDisableTitleConversion
381 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
382 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
383 ||
$this->mOutput
->getDisplayTitle() !== false ) )
385 $convruletitle = $wgContLang->getConvRuleTitle();
386 if ( $convruletitle ) {
387 $this->mOutput
->setTitleText( $convruletitle );
389 $titleText = $wgContLang->convertTitle( $title );
390 $this->mOutput
->setTitleText( $titleText );
394 $text = $this->mStripState
->unstripNoWiki( $text );
396 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
398 $text = $this->replaceTransparentTags( $text );
399 $text = $this->mStripState
->unstripGeneral( $text );
401 $text = Sanitizer
::normalizeCharReferences( $text );
403 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
404 $text = MWTidy
::tidy( $text );
406 # attempt to sanitize at least some nesting problems
407 # (bug #2702 and quite a few others)
409 # ''Something [http://www.cool.com cool''] -->
410 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
411 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
412 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
413 # fix up an anchor inside another anchor, only
414 # at least for a single single nested link (bug 3695)
415 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
416 '\\1\\2</a>\\3</a>\\1\\4</a>',
417 # fix div inside inline elements- doBlockLevels won't wrap a line which
418 # contains a div, so fix it up here; replace
419 # div with escaped text
420 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
421 '\\1\\3<div\\5>\\6</div>\\8\\9',
422 # remove empty italic or bold tag pairs, some
423 # introduced by rules above
424 '/<([bi])><\/\\1>/' => '',
427 $text = preg_replace(
428 array_keys( $tidyregs ),
429 array_values( $tidyregs ),
432 global $wgExpensiveParserFunctionLimit;
433 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
434 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
437 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
439 # Information on include size limits, for the benefit of users who try to skirt them
440 if ( $this->mOptions
->getEnableLimitReport() ) {
441 $max = $this->mOptions
->getMaxIncludeSize();
442 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
444 "NewPP limit report\n" .
445 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
446 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
447 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
449 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
450 $text .= "\n<!-- \n$limitReport-->\n";
452 $this->mOutput
->setText( $text );
454 $this->mRevisionId
= $oldRevisionId;
455 $this->mRevisionObject
= $oldRevisionObject;
456 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
457 $this->mRevisionUser
= $oldRevisionUser;
458 wfProfileOut( $fname );
459 wfProfileOut( __METHOD__
);
461 return $this->mOutput
;
465 * Recursive parser entry point that can be called from an extension tag
468 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
470 * @param $text String: text extension wants to have parsed
471 * @param $frame PPFrame: The frame to use for expanding any template variables
473 function recursiveTagParse( $text, $frame=false ) {
474 wfProfileIn( __METHOD__
);
475 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
476 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
477 $text = $this->internalParse( $text, false, $frame );
478 wfProfileOut( __METHOD__
);
483 * Expand templates and variables in the text, producing valid, static wikitext.
484 * Also removes comments.
486 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
487 wfProfileIn( __METHOD__
);
488 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
489 if ( $revid !== null ) {
490 $this->mRevisionId
= $revid;
492 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
493 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
494 $text = $this->replaceVariables( $text );
495 $text = $this->mStripState
->unstripBoth( $text );
496 wfProfileOut( __METHOD__
);
501 * Process the wikitext for the ?preload= feature. (bug 5210)
503 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
504 * comments, templates, arguments, tags hooks and parser functions are untouched.
506 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
507 # Parser (re)initialisation
508 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
510 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
511 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
512 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
513 $text = $this->mStripState
->unstripBoth( $text );
518 * Get a random string
522 static public function getRandomString() {
523 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
527 * Set the current user.
528 * Should only be used when doing pre-save transform.
530 * @param $user Mixed: User object or null (to reset)
532 function setUser( $user ) {
533 $this->mUser
= $user;
537 * Accessor for mUniqPrefix.
541 public function uniqPrefix() {
542 if ( !isset( $this->mUniqPrefix
) ) {
543 # @todo FIXME: This is probably *horribly wrong*
544 # LanguageConverter seems to want $wgParser's uniqPrefix, however
545 # if this is called for a parser cache hit, the parser may not
546 # have ever been initialized in the first place.
547 # Not really sure what the heck is supposed to be going on here.
549 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
551 return $this->mUniqPrefix
;
555 * Set the context title
559 function setTitle( $t ) {
560 if ( !$t ||
$t instanceof FakeTitle
) {
561 $t = Title
::newFromText( 'NO TITLE' );
564 if ( strval( $t->getFragment() ) !== '' ) {
565 # Strip the fragment to avoid various odd effects
566 $this->mTitle
= clone $t;
567 $this->mTitle
->setFragment( '' );
574 * Accessor for the Title object
576 * @return Title object
578 function getTitle() {
579 return $this->mTitle
;
583 * Accessor/mutator for the Title object
585 * @param $x New Title object or null to just get the current one
586 * @return Title object
588 function Title( $x = null ) {
589 return wfSetVar( $this->mTitle
, $x );
593 * Set the output type
595 * @param $ot Integer: new value
597 function setOutputType( $ot ) {
598 $this->mOutputType
= $ot;
601 'html' => $ot == self
::OT_HTML
,
602 'wiki' => $ot == self
::OT_WIKI
,
603 'pre' => $ot == self
::OT_PREPROCESS
,
604 'plain' => $ot == self
::OT_PLAIN
,
609 * Accessor/mutator for the output type
611 * @param $x New value or null to just get the current one
614 function OutputType( $x = null ) {
615 return wfSetVar( $this->mOutputType
, $x );
619 * Get the ParserOutput object
621 * @return ParserOutput object
623 function getOutput() {
624 return $this->mOutput
;
628 * Get the ParserOptions object
630 * @return ParserOptions object
632 function getOptions() {
633 return $this->mOptions
;
637 * Accessor/mutator for the ParserOptions object
639 * @param $x New value or null to just get the current one
640 * @return Current ParserOptions object
642 function Options( $x = null ) {
643 return wfSetVar( $this->mOptions
, $x );
649 function nextLinkID() {
650 return $this->mLinkID++
;
656 function setLinkID( $id ) {
657 $this->mLinkID
= $id;
663 function getFunctionLang() {
664 global $wgLang, $wgContLang;
666 $target = $this->mOptions
->getTargetLanguage();
667 if ( $target !== null ) {
670 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
675 * Get a User object either from $this->mUser, if set, or from the
676 * ParserOptions object otherwise
678 * @return User object
681 if ( !is_null( $this->mUser
) ) {
684 return $this->mOptions
->getUser();
688 * Get a preprocessor object
690 * @return Preprocessor instance
692 function getPreprocessor() {
693 if ( !isset( $this->mPreprocessor
) ) {
694 $class = $this->mPreprocessorClass
;
695 $this->mPreprocessor
= new $class( $this );
697 return $this->mPreprocessor
;
701 * Replaces all occurrences of HTML-style comments and the given tags
702 * in the text with a random marker and returns the next text. The output
703 * parameter $matches will be an associative array filled with data in
705 * 'UNIQ-xxxxx' => array(
708 * array( 'param' => 'x' ),
709 * '<element param="x">tag content</element>' ) )
711 * @param $elements array list of element names. Comments are always extracted.
712 * @param $text string Source text string.
713 * @param $matches array Out parameter, Array: extracted tags
714 * @param $uniq_prefix string
715 * @return String: stripped text
717 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
722 $taglist = implode( '|', $elements );
723 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
725 while ( $text != '' ) {
726 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
728 if ( count( $p ) < 5 ) {
731 if ( count( $p ) > 5 ) {
745 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
746 $stripped .= $marker;
748 if ( $close === '/>' ) {
749 # Empty element tag, <tag />
754 if ( $element === '!--' ) {
757 $end = "/(<\\/$element\\s*>)/i";
759 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
761 if ( count( $q ) < 3 ) {
762 # No end tag -- let it run out to the end of the text.
771 $matches[$marker] = array( $element,
773 Sanitizer
::decodeTagAttributes( $attributes ),
774 "<$element$attributes$close$content$tail" );
780 * Get a list of strippable XML-like elements
784 function getStripList() {
785 return $this->mStripList
;
789 * Add an item to the strip state
790 * Returns the unique tag which must be inserted into the stripped text
791 * The tag will be replaced with the original text in unstrip()
795 function insertStripItem( $text ) {
796 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
797 $this->mMarkerIndex++
;
798 $this->mStripState
->addGeneral( $rnd, $text );
803 * parse the wiki syntax used to render tables
807 function doTableStuff( $text ) {
808 wfProfileIn( __METHOD__
);
810 $lines = StringUtils
::explode( "\n", $text );
814 foreach ( $lines as $outLine ) {
815 $line = trim( $outLine );
817 # empty line, go to next line,
818 # but only append \n if outside of table
820 $output .= $outLine . "\n";
823 $firstChars = $line[0];
824 if ( strlen( $line ) > 1 ) {
825 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
829 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
831 $table =& $this->last( $tables );
832 $table[0] = array(); // first row
833 $currentRow =& $table[0];
834 $table['indent'] = strlen( $matches[1] );
836 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
837 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
839 if ( $attributes !== '' ) {
840 $table['attributes'] = $attributes;
842 } else if ( !isset( $tables[0] ) ) {
843 // we're outside the table
845 $out .= $outLine . "\n";
846 } else if ( $firstChars === '|}' ) {
847 // trim the |} code from the line
848 $line = substr ( $line , 2 );
850 // Shorthand for last row
851 $lastRow =& $this->last( $table );
853 // a thead at the end becomes a tfoot, unless there is only one row
854 // Do this before deleting empty last lines to allow headers at the bottom of tables
855 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
856 $lastRow['type'] = 'tfoot';
857 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
858 $lastRow[$i]['type'] = 'th';
862 // Delete empty last lines
863 if ( empty( $lastRow ) ) {
867 $curtable = array_pop( $tables );
869 #Add a line-ending before the table, but only if there isn't one already
870 if ( substr( $out, -1 ) !== "\n" ) {
873 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
875 if ( count( $tables ) > 0 ) {
876 $table =& $this->last( $tables );
877 $currentRow =& $this->last( $table );
878 $currentElement =& $this->last( $currentRow );
880 $output =& $currentElement['content'];
887 } else if ( $firstChars === '|-' ) {
888 // start a new row element
889 // but only when we haven't started one already
890 if ( count( $currentRow ) != 0 ) {
892 $currentRow =& $this->last( $table );
894 // Get the attributes, there's nothing else useful in $line now
895 $line = substr ( $line , 2 );
896 $attributes = $this->mStripState
->unstripBoth( $line );
897 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
898 if ( $attributes !== '' ) {
899 $currentRow['attributes'] = $attributes;
902 } else if ( $firstChars === '|+' ) {
903 // a table caption, but only proceed if there isn't one already
904 if ( !isset ( $table['caption'] ) ) {
905 $line = substr ( $line , 2 );
907 $c = $this->getCellAttr( $line , 'caption' );
908 $table['caption'] = array();
909 $table['caption']['content'] = $c[0];
910 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
912 $output =& $table['caption']['content'];
914 } else if ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
915 // Which kind of cells are we dealing with
917 $line = substr ( $line , 1 );
919 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
920 $line = str_replace ( '!!' , '||' , $line );
924 // Split up multiple cells on the same line.
925 $cells = StringUtils
::explodeMarkup( '||' , $line );
926 $line = ''; // save memory
928 // decide whether thead to tbody
929 if ( !array_key_exists( 'type', $currentRow ) ) {
930 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
931 } else if ( $firstChars === '|' ) {
932 $currentRow['type'] = 'tbody';
935 // Loop through each table cell
936 foreach ( $cells as $cell ) {
938 $currentRow[] = array();
939 $currentElement =& $this->last( $currentRow );
941 $currentElement['type'] = $currentTag;
943 $c = $this->getCellAttr( $cell , $currentTag );
944 $currentElement['content'] = $c[0];
945 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
948 $output =& $currentElement['content'];
951 $output .= "\n$outLine";
955 # Remove trailing line-ending (b/c)
956 if ( substr( $out, -1 ) === "\n" ) {
957 $out = substr( $out, 0, -1 );
960 # Close any unclosed tables
961 if ( isset( $tables ) && count( $tables ) > 0 ) {
962 for ( $i = 0; $i < count( $tables ); $i++
) {
963 $curtable = array_pop( $tables );
964 $curtable = $this->generateTableHTML( $curtable );
965 #Add a line-ending before the table, but only if there isn't one already
966 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
973 wfProfileOut( __METHOD__
);
979 * Helper function for doTableStuff() separating the contents of cells from
980 * attributes. Particularly useful as there's a possible bug and this action
988 function getCellAttr ( $cell, $tagName ) {
991 $cell = trim ( $cell );
993 // A cell could contain both parameters and data
994 $cellData = explode ( '|' , $cell , 2 );
996 // Bug 553: Note that a '|' inside an invalid link should not
997 // be mistaken as delimiting cell parameters
998 if ( strpos( $cellData[0], '[[' ) !== false ) {
999 $content = trim ( $cell );
1001 else if ( count ( $cellData ) == 1 ) {
1002 $content = trim ( $cellData[0] );
1004 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
1005 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
1007 $content = trim ( $cellData[1] );
1009 return array( $content, $attributes );
1014 * Helper function for doTableStuff(). This converts the structured array into html.
1018 function generateTableHTML ( &$table ) {
1020 $return .= str_repeat( '<dl><dd>' , $table['indent'] );
1021 $return .= '<table';
1022 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1024 unset( $table['attributes'] );
1026 if ( isset( $table['caption'] ) ) {
1027 $return .= "\n<caption";
1028 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1030 $return .= $table['caption']['content'];
1031 $return .= "\n</caption>";
1037 // If we only have tbodies, mark table as simple
1038 for ( $i = 0; isset( $table[$i] ); $i++
) {
1039 if ( !count( $table[$i] ) ) continue;
1040 if ( !isset( $table[$i]['type'] ) ) $table[$i]['type'] = 'tbody';
1041 if ( !$lastSection ) {
1042 $lastSection = $table[$i]['type'];
1043 } else if ( $lastSection != $table[$i]['type'] ) {
1049 for ( $i = 0; isset( $table[$i] ); $i++
) {
1050 // Check for empty tables
1051 if ( count( $table[$i] ) ) {
1056 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1057 $return .= "\n<" . $table[$i]['type'] . '>';
1061 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1063 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1064 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1065 $return .= "\n<" . $table[$i][$j]['type'];
1066 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1069 $return .= $table[$i][$j]['content'];
1070 if ( $table[$i][$j]['content'] != '' )
1073 $return .= '</' . $table[$i][$j]['type'] . '>';
1074 unset( $table[$i][$j] );
1076 $return .= "\n</tr>";
1078 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && isset( $table[$i +
1]['type'] ) && $table[$i]['type'] != $table[$i +
1]['type'] ) ) {
1079 $return .= '</' . $table[$i]['type'] . '>';
1081 $lastSection = $table[$i]['type'];
1082 unset( $table[$i] );
1085 if ( isset( $table['caption'] ) ) {
1086 $return .= "\n<tr><td></td></tr>";
1091 $return .= "\n</table>";
1092 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1098 * like end() but only works on the numeric array index and php's internal pointers
1099 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1100 * ignores associative elements and will create a 0 key will a NULL value if there were
1101 * no numric elements and an array itself if not previously defined.
1105 function &last ( &$arr ) {
1106 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1111 * Helper function for parse() that transforms wiki markup into
1112 * HTML. Only called for $mOutputType == self::OT_HTML.
1116 function internalParse( $text, $isMain = true, $frame=false ) {
1117 wfProfileIn( __METHOD__
);
1121 # Hook to suspend the parser in this state
1122 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1123 wfProfileOut( __METHOD__
);
1127 # if $frame is provided, then use $frame for replacing any variables
1129 # use frame depth to infer how include/noinclude tags should be handled
1130 # depth=0 means this is the top-level document; otherwise it's an included document
1131 if ( !$frame->depth
) {
1134 $flag = Parser
::PTD_FOR_INCLUSION
;
1136 $dom = $this->preprocessToDom( $text, $flag );
1137 $text = $frame->expand( $dom );
1139 # if $frame is not provided, then use old-style replaceVariables
1140 $text = $this->replaceVariables( $text );
1143 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1144 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1146 # Tables need to come after variable replacement for things to work
1147 # properly; putting them before other transformations should keep
1148 # exciting things like link expansions from showing up in surprising
1150 $text = $this->doTableStuff( $text );
1152 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1154 $text = $this->doDoubleUnderscore( $text );
1156 $text = $this->doHeadings( $text );
1157 if ( $this->mOptions
->getUseDynamicDates() ) {
1158 $df = DateFormatter
::getInstance();
1159 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1161 $text = $this->replaceInternalLinks( $text );
1162 $text = $this->doAllQuotes( $text );
1163 $text = $this->replaceExternalLinks( $text );
1165 # replaceInternalLinks may sometimes leave behind
1166 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1167 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1169 $text = $this->doMagicLinks( $text );
1170 $text = $this->formatHeadings( $text, $origText, $isMain );
1172 wfProfileOut( __METHOD__
);
1177 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1178 * magic external links.
1183 function doMagicLinks( $text ) {
1184 wfProfileIn( __METHOD__
);
1185 $prots = $this->mUrlProtocols
;
1186 $urlChar = self
::EXT_LINK_URL_CLASS
;
1187 $text = preg_replace_callback(
1189 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1190 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1191 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1192 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1193 ISBN\s+(\b # m[5]: ISBN, capture number
1194 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1195 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1196 [0-9Xx] # check digit
1198 )!x', array( &$this, 'magicLinkCallback' ), $text );
1199 wfProfileOut( __METHOD__
);
1204 * @throws MWException
1206 * @return HTML|string
1208 function magicLinkCallback( $m ) {
1209 if ( isset( $m[1] ) && $m[1] !== '' ) {
1212 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1215 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1216 # Free external link
1217 return $this->makeFreeExternalLink( $m[0] );
1218 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1220 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1223 $CssClass = 'mw-magiclink-rfc';
1225 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1227 $urlmsg = 'pubmedurl';
1228 $CssClass = 'mw-magiclink-pmid';
1231 throw new MWException( __METHOD__
.': unrecognised match type "' .
1232 substr( $m[0], 0, 20 ) . '"' );
1234 $url = wfMsgForContent( $urlmsg, $id );
1235 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1236 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1239 $num = strtr( $isbn, array(
1244 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1246 $titleObj->escapeLocalUrl() .
1247 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1254 * Make a free external link, given a user-supplied URL
1258 function makeFreeExternalLink( $url ) {
1260 wfProfileIn( __METHOD__
);
1264 # The characters '<' and '>' (which were escaped by
1265 # removeHTMLtags()) should not be included in
1266 # URLs, per RFC 2396.
1268 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1269 $trail = substr( $url, $m2[0][1] ) . $trail;
1270 $url = substr( $url, 0, $m2[0][1] );
1273 # Move trailing punctuation to $trail
1275 # If there is no left bracket, then consider right brackets fair game too
1276 if ( strpos( $url, '(' ) === false ) {
1280 $numSepChars = strspn( strrev( $url ), $sep );
1281 if ( $numSepChars ) {
1282 $trail = substr( $url, -$numSepChars ) . $trail;
1283 $url = substr( $url, 0, -$numSepChars );
1286 $url = Sanitizer
::cleanUrl( $url );
1288 # Is this an external image?
1289 $text = $this->maybeMakeExternalImage( $url );
1290 if ( $text === false ) {
1291 # Not an image, make a link
1292 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1293 $this->getExternalLinkAttribs( $url ) );
1294 # Register it in the output object...
1295 # Replace unnecessary URL escape codes with their equivalent characters
1296 $pasteurized = self
::replaceUnusualEscapes( $url );
1297 $this->mOutput
->addExternalLink( $pasteurized );
1299 wfProfileOut( __METHOD__
);
1300 return $text . $trail;
1305 * Parse headers and return html
1309 function doHeadings( $text ) {
1310 wfProfileIn( __METHOD__
);
1311 for ( $i = 6; $i >= 1; --$i ) {
1312 $h = str_repeat( '=', $i );
1313 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1314 "<h$i>\\1</h$i>", $text );
1316 wfProfileOut( __METHOD__
);
1321 * Replace single quotes with HTML markup
1323 * @return string the altered text
1325 function doAllQuotes( $text ) {
1326 wfProfileIn( __METHOD__
);
1328 $lines = StringUtils
::explode( "\n", $text );
1329 foreach ( $lines as $line ) {
1330 $outtext .= $this->doQuotes( $line ) . "\n";
1332 $outtext = substr( $outtext, 0,-1 );
1333 wfProfileOut( __METHOD__
);
1338 * Helper function for doAllQuotes()
1340 public function doQuotes( $text ) {
1341 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1342 if ( count( $arr ) == 1 ) {
1345 # First, do some preliminary work. This may shift some apostrophes from
1346 # being mark-up to being text. It also counts the number of occurrences
1347 # of bold and italics mark-ups.
1350 for ( $i = 0; $i < count( $arr ); $i++
) {
1351 if ( ( $i %
2 ) == 1 ) {
1352 # If there are ever four apostrophes, assume the first is supposed to
1353 # be text, and the remaining three constitute mark-up for bold text.
1354 if ( strlen( $arr[$i] ) == 4 ) {
1357 } elseif ( strlen( $arr[$i] ) > 5 ) {
1358 # If there are more than 5 apostrophes in a row, assume they're all
1359 # text except for the last 5.
1360 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1363 # Count the number of occurrences of bold and italics mark-ups.
1364 # We are not counting sequences of five apostrophes.
1365 if ( strlen( $arr[$i] ) == 2 ) {
1367 } elseif ( strlen( $arr[$i] ) == 3 ) {
1369 } elseif ( strlen( $arr[$i] ) == 5 ) {
1376 # If there is an odd number of both bold and italics, it is likely
1377 # that one of the bold ones was meant to be an apostrophe followed
1378 # by italics. Which one we cannot know for certain, but it is more
1379 # likely to be one that has a single-letter word before it.
1380 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1382 $firstsingleletterword = -1;
1383 $firstmultiletterword = -1;
1385 foreach ( $arr as $r ) {
1386 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1387 $x1 = substr( $arr[$i-1], -1 );
1388 $x2 = substr( $arr[$i-1], -2, 1 );
1389 if ( $x1 === ' ' ) {
1390 if ( $firstspace == -1 ) {
1393 } elseif ( $x2 === ' ') {
1394 if ( $firstsingleletterword == -1 ) {
1395 $firstsingleletterword = $i;
1398 if ( $firstmultiletterword == -1 ) {
1399 $firstmultiletterword = $i;
1406 # If there is a single-letter word, use it!
1407 if ( $firstsingleletterword > -1 ) {
1408 $arr[$firstsingleletterword] = "''";
1409 $arr[$firstsingleletterword-1] .= "'";
1410 } elseif ( $firstmultiletterword > -1 ) {
1411 # If not, but there's a multi-letter word, use that one.
1412 $arr[$firstmultiletterword] = "''";
1413 $arr[$firstmultiletterword-1] .= "'";
1414 } elseif ( $firstspace > -1 ) {
1415 # ... otherwise use the first one that has neither.
1416 # (notice that it is possible for all three to be -1 if, for example,
1417 # there is only one pentuple-apostrophe in the line)
1418 $arr[$firstspace] = "''";
1419 $arr[$firstspace-1] .= "'";
1423 # Now let's actually convert our apostrophic mush to HTML!
1428 foreach ( $arr as $r ) {
1429 if ( ( $i %
2 ) == 0 ) {
1430 if ( $state === 'both' ) {
1436 if ( strlen( $r ) == 2 ) {
1437 if ( $state === 'i' ) {
1438 $output .= '</i>'; $state = '';
1439 } elseif ( $state === 'bi' ) {
1440 $output .= '</i>'; $state = 'b';
1441 } elseif ( $state === 'ib' ) {
1442 $output .= '</b></i><b>'; $state = 'b';
1443 } elseif ( $state === 'both' ) {
1444 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1445 } else { # $state can be 'b' or ''
1446 $output .= '<i>'; $state .= 'i';
1448 } elseif ( strlen( $r ) == 3 ) {
1449 if ( $state === 'b' ) {
1450 $output .= '</b>'; $state = '';
1451 } elseif ( $state === 'bi' ) {
1452 $output .= '</i></b><i>'; $state = 'i';
1453 } elseif ( $state === 'ib' ) {
1454 $output .= '</b>'; $state = 'i';
1455 } elseif ( $state === 'both' ) {
1456 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1457 } else { # $state can be 'i' or ''
1458 $output .= '<b>'; $state .= 'b';
1460 } elseif ( strlen( $r ) == 5 ) {
1461 if ( $state === 'b' ) {
1462 $output .= '</b><i>'; $state = 'i';
1463 } elseif ( $state === 'i' ) {
1464 $output .= '</i><b>'; $state = 'b';
1465 } elseif ( $state === 'bi' ) {
1466 $output .= '</i></b>'; $state = '';
1467 } elseif ( $state === 'ib' ) {
1468 $output .= '</b></i>'; $state = '';
1469 } elseif ( $state === 'both' ) {
1470 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1471 } else { # ($state == '')
1472 $buffer = ''; $state = 'both';
1478 # Now close all remaining tags. Notice that the order is important.
1479 if ( $state === 'b' ||
$state === 'ib' ) {
1482 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1485 if ( $state === 'bi' ) {
1488 # There might be lonely ''''', so make sure we have a buffer
1489 if ( $state === 'both' && $buffer ) {
1490 $output .= '<b><i>'.$buffer.'</i></b>';
1497 * Replace external links (REL)
1499 * Note: this is all very hackish and the order of execution matters a lot.
1500 * Make sure to run maintenance/parserTests.php if you change this code.
1504 function replaceExternalLinks( $text ) {
1506 wfProfileIn( __METHOD__
);
1508 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1509 $s = array_shift( $bits );
1512 while ( $i<count( $bits ) ) {
1514 $protocol = $bits[$i++
];
1515 $text = $bits[$i++
];
1516 $trail = $bits[$i++
];
1518 # The characters '<' and '>' (which were escaped by
1519 # removeHTMLtags()) should not be included in
1520 # URLs, per RFC 2396.
1522 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1523 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1524 $url = substr( $url, 0, $m2[0][1] );
1527 # If the link text is an image URL, replace it with an <img> tag
1528 # This happened by accident in the original parser, but some people used it extensively
1529 $img = $this->maybeMakeExternalImage( $text );
1530 if ( $img !== false ) {
1536 # Set linktype for CSS - if URL==text, link is essentially free
1537 $linktype = ( $text === $url ) ?
'free' : 'text';
1539 # No link text, e.g. [http://domain.tld/some.link]
1540 if ( $text == '' ) {
1541 # Autonumber if allowed. See bug #5918
1542 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1543 $langObj = $this->getFunctionLang();
1544 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1545 $linktype = 'autonumber';
1547 # Otherwise just use the URL
1548 $text = htmlspecialchars( $url );
1552 # Have link text, e.g. [http://domain.tld/some.link text]s
1554 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1557 $text = $wgContLang->markNoConversion( $text );
1559 $url = Sanitizer
::cleanUrl( $url );
1561 # Use the encoded URL
1562 # This means that users can paste URLs directly into the text
1563 # Funny characters like ö aren't valid in URLs anyway
1564 # This was changed in August 2004
1565 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1566 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1568 # Register link in the output object.
1569 # Replace unnecessary URL escape codes with the referenced character
1570 # This prevents spammers from hiding links from the filters
1571 $pasteurized = self
::replaceUnusualEscapes( $url );
1572 $this->mOutput
->addExternalLink( $pasteurized );
1575 wfProfileOut( __METHOD__
);
1580 * Get an associative array of additional HTML attributes appropriate for a
1581 * particular external link. This currently may include rel => nofollow
1582 * (depending on configuration, namespace, and the URL's domain) and/or a
1583 * target attribute (depending on configuration).
1585 * @param $url String: optional URL, to extract the domain from for rel =>
1586 * nofollow if appropriate
1587 * @return Array: associative array of HTML attributes
1589 function getExternalLinkAttribs( $url = false ) {
1591 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1592 $ns = $this->mTitle
->getNamespace();
1593 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1594 $attribs['rel'] = 'nofollow';
1596 global $wgNoFollowDomainExceptions;
1597 if ( $wgNoFollowDomainExceptions ) {
1598 $bits = wfParseUrl( $url );
1599 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1600 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1601 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1602 unset( $attribs['rel'] );
1609 if ( $this->mOptions
->getExternalLinkTarget() ) {
1610 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1616 * Replace unusual URL escape codes with their equivalent characters
1618 * @param $url String
1621 * @todo This can merge genuinely required bits in the path or query string,
1622 * breaking legit URLs. A proper fix would treat the various parts of
1623 * the URL differently; as a workaround, just use the output for
1624 * statistical records, not for actual linking/output.
1626 static function replaceUnusualEscapes( $url ) {
1627 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1628 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1632 * Callback function used in replaceUnusualEscapes().
1633 * Replaces unusual URL escape codes with their equivalent character
1635 private static function replaceUnusualEscapesCallback( $matches ) {
1636 $char = urldecode( $matches[0] );
1637 $ord = ord( $char );
1638 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1639 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1640 # No, shouldn't be escaped
1643 # Yes, leave it escaped
1649 * make an image if it's allowed, either through the global
1650 * option, through the exception, or through the on-wiki whitelist
1653 function maybeMakeExternalImage( $url ) {
1654 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1655 $imagesexception = !empty( $imagesfrom );
1657 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1658 if ( $imagesexception && is_array( $imagesfrom ) ) {
1659 $imagematch = false;
1660 foreach ( $imagesfrom as $match ) {
1661 if ( strpos( $url, $match ) === 0 ) {
1666 } elseif ( $imagesexception ) {
1667 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1669 $imagematch = false;
1671 if ( $this->mOptions
->getAllowExternalImages()
1672 ||
( $imagesexception && $imagematch ) ) {
1673 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1675 $text = Linker
::makeExternalImage( $url );
1678 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1679 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1680 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1681 foreach ( $whitelist as $entry ) {
1682 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1683 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1686 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1687 # Image matches a whitelist entry
1688 $text = Linker
::makeExternalImage( $url );
1697 * Process [[ ]] wikilinks
1698 * @return String: processed text
1702 function replaceInternalLinks( $s ) {
1703 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1708 * Process [[ ]] wikilinks (RIL)
1709 * @return LinkHolderArray
1713 function replaceInternalLinks2( &$s ) {
1716 wfProfileIn( __METHOD__
);
1718 wfProfileIn( __METHOD__
.'-setup' );
1719 static $tc = FALSE, $e1, $e1_img;
1720 # the % is needed to support urlencoded titles as well
1722 $tc = Title
::legalChars() . '#%';
1723 # Match a link having the form [[namespace:link|alternate]]trail
1724 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1725 # Match cases where there is no "]]", which might still be images
1726 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1729 $holders = new LinkHolderArray( $this );
1731 # split the entire text string on occurences of [[
1732 $a = StringUtils
::explode( '[[', ' ' . $s );
1733 # get the first element (all text up to first [[), and remove the space we added
1736 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1737 $s = substr( $s, 1 );
1739 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1741 if ( $useLinkPrefixExtension ) {
1742 # Match the end of a line for a word that's not followed by whitespace,
1743 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1744 $e2 = wfMsgForContent( 'linkprefix' );
1747 if ( is_null( $this->mTitle
) ) {
1748 wfProfileOut( __METHOD__
.'-setup' );
1749 wfProfileOut( __METHOD__
);
1750 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1752 $nottalk = !$this->mTitle
->isTalkPage();
1754 if ( $useLinkPrefixExtension ) {
1756 if ( preg_match( $e2, $s, $m ) ) {
1757 $first_prefix = $m[2];
1759 $first_prefix = false;
1765 if ( $wgContLang->hasVariants() ) {
1766 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1768 $selflink = array( $this->mTitle
->getPrefixedText() );
1770 $useSubpages = $this->areSubpagesAllowed();
1771 wfProfileOut( __METHOD__
.'-setup' );
1773 # Loop for each link
1774 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1775 # Check for excessive memory usage
1776 if ( $holders->isBig() ) {
1778 # Do the existence check, replace the link holders and clear the array
1779 $holders->replace( $s );
1783 if ( $useLinkPrefixExtension ) {
1784 wfProfileIn( __METHOD__
.'-prefixhandling' );
1785 if ( preg_match( $e2, $s, $m ) ) {
1792 if ( $first_prefix ) {
1793 $prefix = $first_prefix;
1794 $first_prefix = false;
1796 wfProfileOut( __METHOD__
.'-prefixhandling' );
1799 $might_be_img = false;
1801 wfProfileIn( __METHOD__
."-e1" );
1802 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1804 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1805 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1806 # the real problem is with the $e1 regex
1809 # Still some problems for cases where the ] is meant to be outside punctuation,
1810 # and no image is in sight. See bug 2095.
1812 if ( $text !== '' &&
1813 substr( $m[3], 0, 1 ) === ']' &&
1814 strpos( $text, '[' ) !== false
1817 $text .= ']'; # so that replaceExternalLinks($text) works later
1818 $m[3] = substr( $m[3], 1 );
1820 # fix up urlencoded title texts
1821 if ( strpos( $m[1], '%' ) !== false ) {
1822 # Should anchors '#' also be rejected?
1823 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1826 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1827 $might_be_img = true;
1829 if ( strpos( $m[1], '%' ) !== false ) {
1830 $m[1] = rawurldecode( $m[1] );
1833 } else { # Invalid form; output directly
1834 $s .= $prefix . '[[' . $line ;
1835 wfProfileOut( __METHOD__
."-e1" );
1838 wfProfileOut( __METHOD__
."-e1" );
1839 wfProfileIn( __METHOD__
."-misc" );
1841 # Don't allow internal links to pages containing
1842 # PROTO: where PROTO is a valid URL protocol; these
1843 # should be external links.
1844 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1845 $s .= $prefix . '[[' . $line ;
1846 wfProfileOut( __METHOD__
."-misc" );
1850 # Make subpage if necessary
1851 if ( $useSubpages ) {
1852 $link = $this->maybeDoSubpageLink( $m[1], $text );
1857 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1859 # Strip off leading ':'
1860 $link = substr( $link, 1 );
1863 wfProfileOut( __METHOD__
."-misc" );
1864 wfProfileIn( __METHOD__
."-title" );
1865 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1866 if ( $nt === null ) {
1867 $s .= $prefix . '[[' . $line;
1868 wfProfileOut( __METHOD__
."-title" );
1872 $ns = $nt->getNamespace();
1873 $iw = $nt->getInterWiki();
1874 wfProfileOut( __METHOD__
."-title" );
1876 if ( $might_be_img ) { # if this is actually an invalid link
1877 wfProfileIn( __METHOD__
."-might_be_img" );
1878 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1881 # look at the next 'line' to see if we can close it there
1883 $next_line = $a->current();
1884 if ( $next_line === false ||
$next_line === null ) {
1887 $m = explode( ']]', $next_line, 3 );
1888 if ( count( $m ) == 3 ) {
1889 # the first ]] closes the inner link, the second the image
1891 $text .= "[[{$m[0]}]]{$m[1]}";
1894 } elseif ( count( $m ) == 2 ) {
1895 # if there's exactly one ]] that's fine, we'll keep looking
1896 $text .= "[[{$m[0]}]]{$m[1]}";
1898 # if $next_line is invalid too, we need look no further
1899 $text .= '[[' . $next_line;
1904 # we couldn't find the end of this imageLink, so output it raw
1905 # but don't ignore what might be perfectly normal links in the text we've examined
1906 $holders->merge( $this->replaceInternalLinks2( $text ) );
1907 $s .= "{$prefix}[[$link|$text";
1908 # note: no $trail, because without an end, there *is* no trail
1909 wfProfileOut( __METHOD__
."-might_be_img" );
1912 } else { # it's not an image, so output it raw
1913 $s .= "{$prefix}[[$link|$text";
1914 # note: no $trail, because without an end, there *is* no trail
1915 wfProfileOut( __METHOD__
."-might_be_img" );
1918 wfProfileOut( __METHOD__
."-might_be_img" );
1921 $wasblank = ( $text == '' );
1925 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1926 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1927 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1928 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1929 $text = $this->doQuotes( $text );
1932 # Link not escaped by : , create the various objects
1936 wfProfileIn( __METHOD__
."-interwiki" );
1937 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1938 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1939 $s = rtrim( $s . $prefix );
1940 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1941 wfProfileOut( __METHOD__
."-interwiki" );
1944 wfProfileOut( __METHOD__
."-interwiki" );
1946 if ( $ns == NS_FILE
) {
1947 wfProfileIn( __METHOD__
."-image" );
1948 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1950 # if no parameters were passed, $text
1951 # becomes something like "File:Foo.png",
1952 # which we don't want to pass on to the
1956 # recursively parse links inside the image caption
1957 # actually, this will parse them in any other parameters, too,
1958 # but it might be hard to fix that, and it doesn't matter ATM
1959 $text = $this->replaceExternalLinks( $text );
1960 $holders->merge( $this->replaceInternalLinks2( $text ) );
1962 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1963 $s .= $prefix . $this->armorLinks(
1964 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1966 $s .= $prefix . $trail;
1968 wfProfileOut( __METHOD__
."-image" );
1972 if ( $ns == NS_CATEGORY
) {
1973 wfProfileIn( __METHOD__
."-category" );
1974 $s = rtrim( $s . "\n" ); # bug 87
1977 $sortkey = $this->getDefaultSort();
1981 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1982 $sortkey = str_replace( "\n", '', $sortkey );
1983 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1984 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1987 * Strip the whitespace Category links produce, see bug 87
1988 * @todo We might want to use trim($tmp, "\n") here.
1990 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1992 wfProfileOut( __METHOD__
."-category" );
1997 # Self-link checking
1998 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1999 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2000 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2005 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2006 # @todo FIXME: Should do batch file existence checks, see comment below
2007 if ( $ns == NS_MEDIA
) {
2008 wfProfileIn( __METHOD__
."-media" );
2009 # Give extensions a chance to select the file revision for us
2010 $time = $sha1 = $descQuery = false;
2011 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2012 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
2013 # Fetch and register the file (file title may be different via hooks)
2014 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
2015 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2016 $s .= $prefix . $this->armorLinks(
2017 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2018 wfProfileOut( __METHOD__
."-media" );
2022 wfProfileIn( __METHOD__
."-always_known" );
2023 # Some titles, such as valid special pages or files in foreign repos, should
2024 # be shown as bluelinks even though they're not included in the page table
2026 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2027 # batch file existence checks for NS_FILE and NS_MEDIA
2028 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2029 $this->mOutput
->addLink( $nt );
2030 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2032 # Links will be added to the output link list after checking
2033 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2035 wfProfileOut( __METHOD__
."-always_known" );
2037 wfProfileOut( __METHOD__
);
2042 * Render a forced-blue link inline; protect against double expansion of
2043 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2044 * Since this little disaster has to split off the trail text to avoid
2045 * breaking URLs in the following text without breaking trails on the
2046 * wiki links, it's been made into a horrible function.
2049 * @param $text String
2050 * @param $query Array or String
2051 * @param $trail String
2052 * @param $prefix String
2053 * @return String: HTML-wikitext mix oh yuck
2055 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2056 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2058 if ( is_string( $query ) ) {
2059 $query = wfCgiToArray( $query );
2061 if ( $text == '' ) {
2062 $text = htmlspecialchars( $nt->getPrefixedText() );
2065 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2067 return $this->armorLinks( $link ) . $trail;
2071 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2072 * going to go through further parsing steps before inline URL expansion.
2074 * Not needed quite as much as it used to be since free links are a bit
2075 * more sensible these days. But bracketed links are still an issue.
2077 * @param $text String: more-or-less HTML
2078 * @return String: less-or-more HTML with NOPARSE bits
2080 function armorLinks( $text ) {
2081 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2082 "{$this->mUniqPrefix}NOPARSE$1", $text );
2086 * Return true if subpage links should be expanded on this page.
2089 function areSubpagesAllowed() {
2090 # Some namespaces don't allow subpages
2091 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2095 * Handle link to subpage if necessary
2097 * @param $target String: the source of the link
2098 * @param &$text String: the link text, modified as necessary
2099 * @return string the full name of the link
2102 function maybeDoSubpageLink( $target, &$text ) {
2103 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2107 * Used by doBlockLevels()
2112 function closeParagraph() {
2114 if ( $this->mLastSection
!= '' ) {
2115 $result = '</' . $this->mLastSection
. ">\n";
2117 $this->mInPre
= false;
2118 $this->mLastSection
= '';
2123 * getCommon() returns the length of the longest common substring
2124 * of both arguments, starting at the beginning of both.
2127 function getCommon( $st1, $st2 ) {
2128 $fl = strlen( $st1 );
2129 $shorter = strlen( $st2 );
2130 if ( $fl < $shorter ) {
2134 for ( $i = 0; $i < $shorter; ++
$i ) {
2135 if ( $st1[$i] != $st2[$i] ) {
2143 * These next three functions open, continue, and close the list
2144 * element appropriate to the prefix character passed into them.
2149 function openList( $char ) {
2150 $result = $this->closeParagraph();
2152 if ( '*' === $char ) {
2153 $result .= '<ul><li>';
2154 } elseif ( '#' === $char ) {
2155 $result .= '<ol><li>';
2156 } elseif ( ':' === $char ) {
2157 $result .= '<dl><dd>';
2158 } elseif ( ';' === $char ) {
2159 $result .= '<dl><dt>';
2160 $this->mDTopen
= true;
2162 $result = '<!-- ERR 1 -->';
2170 * @param $char String
2175 function nextItem( $char ) {
2176 if ( '*' === $char ||
'#' === $char ) {
2178 } elseif ( ':' === $char ||
';' === $char ) {
2180 if ( $this->mDTopen
) {
2183 if ( ';' === $char ) {
2184 $this->mDTopen
= true;
2185 return $close . '<dt>';
2187 $this->mDTopen
= false;
2188 return $close . '<dd>';
2191 return '<!-- ERR 2 -->';
2196 * @param $char String
2201 function closeList( $char ) {
2202 if ( '*' === $char ) {
2203 $text = '</li></ul>';
2204 } elseif ( '#' === $char ) {
2205 $text = '</li></ol>';
2206 } elseif ( ':' === $char ) {
2207 if ( $this->mDTopen
) {
2208 $this->mDTopen
= false;
2209 $text = '</dt></dl>';
2211 $text = '</dd></dl>';
2214 return '<!-- ERR 3 -->';
2221 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2223 * @param $text String
2224 * @param $linestart Boolean: whether or not this is at the start of a line.
2226 * @return string the lists rendered as HTML
2228 function doBlockLevels( $text, $linestart ) {
2229 wfProfileIn( __METHOD__
);
2231 # Parsing through the text line by line. The main thing
2232 # happening here is handling of block-level elements p, pre,
2233 # and making lists from lines starting with * # : etc.
2235 $textLines = StringUtils
::explode( "\n", $text );
2237 $lastPrefix = $output = '';
2238 $this->mDTopen
= $inBlockElem = false;
2240 $paragraphStack = false;
2242 foreach ( $textLines as $oLine ) {
2244 if ( !$linestart ) {
2254 $lastPrefixLength = strlen( $lastPrefix );
2255 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2256 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2257 # If not in a <pre> element, scan for and figure out what prefixes are there.
2258 if ( !$this->mInPre
) {
2259 # Multiple prefixes may abut each other for nested lists.
2260 $prefixLength = strspn( $oLine, '*#:;' );
2261 $prefix = substr( $oLine, 0, $prefixLength );
2264 # ; and : are both from definition-lists, so they're equivalent
2265 # for the purposes of determining whether or not we need to open/close
2267 $prefix2 = str_replace( ';', ':', $prefix );
2268 $t = substr( $oLine, $prefixLength );
2269 $this->mInPre
= (bool)$preOpenMatch;
2271 # Don't interpret any other prefixes in preformatted text
2273 $prefix = $prefix2 = '';
2278 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2279 # Same as the last item, so no need to deal with nesting or opening stuff
2280 $output .= $this->nextItem( substr( $prefix, -1 ) );
2281 $paragraphStack = false;
2283 if ( substr( $prefix, -1 ) === ';') {
2284 # The one nasty exception: definition lists work like this:
2285 # ; title : definition text
2286 # So we check for : in the remainder text to split up the
2287 # title and definition, without b0rking links.
2289 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2291 $output .= $term . $this->nextItem( ':' );
2294 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2295 # We need to open or close prefixes, or both.
2297 # Either open or close a level...
2298 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2299 $paragraphStack = false;
2301 # Close all the prefixes which aren't shared.
2302 while ( $commonPrefixLength < $lastPrefixLength ) {
2303 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2304 --$lastPrefixLength;
2307 # Continue the current prefix if appropriate.
2308 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2309 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2312 # Open prefixes where appropriate.
2313 while ( $prefixLength > $commonPrefixLength ) {
2314 $char = substr( $prefix, $commonPrefixLength, 1 );
2315 $output .= $this->openList( $char );
2317 if ( ';' === $char ) {
2318 # @todo FIXME: This is dupe of code above
2319 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2321 $output .= $term . $this->nextItem( ':' );
2324 ++
$commonPrefixLength;
2326 $lastPrefix = $prefix2;
2329 # If we have no prefixes, go to paragraph mode.
2330 if ( 0 == $prefixLength ) {
2331 wfProfileIn( __METHOD__
."-paragraph" );
2332 # No prefix (not in list)--go to paragraph mode
2333 # XXX: use a stack for nestable elements like span, table and div
2334 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2335 $closematch = preg_match(
2336 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2337 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2338 if ( $openmatch or $closematch ) {
2339 $paragraphStack = false;
2340 # TODO bug 5718: paragraph closed
2341 $output .= $this->closeParagraph();
2342 if ( $preOpenMatch and !$preCloseMatch ) {
2343 $this->mInPre
= true;
2345 $inBlockElem = !$closematch;
2346 } elseif ( !$inBlockElem && !$this->mInPre
) {
2347 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2349 if ( $this->mLastSection
!== 'pre' ) {
2350 $paragraphStack = false;
2351 $output .= $this->closeParagraph().'<pre>';
2352 $this->mLastSection
= 'pre';
2354 $t = substr( $t, 1 );
2357 if ( trim( $t ) === '' ) {
2358 if ( $paragraphStack ) {
2359 $output .= $paragraphStack.'<br />';
2360 $paragraphStack = false;
2361 $this->mLastSection
= 'p';
2363 if ( $this->mLastSection
!== 'p' ) {
2364 $output .= $this->closeParagraph();
2365 $this->mLastSection
= '';
2366 $paragraphStack = '<p>';
2368 $paragraphStack = '</p><p>';
2372 if ( $paragraphStack ) {
2373 $output .= $paragraphStack;
2374 $paragraphStack = false;
2375 $this->mLastSection
= 'p';
2376 } elseif ( $this->mLastSection
!== 'p' ) {
2377 $output .= $this->closeParagraph().'<p>';
2378 $this->mLastSection
= 'p';
2383 wfProfileOut( __METHOD__
."-paragraph" );
2385 # somewhere above we forget to get out of pre block (bug 785)
2386 if ( $preCloseMatch && $this->mInPre
) {
2387 $this->mInPre
= false;
2389 if ( $paragraphStack === false ) {
2393 while ( $prefixLength ) {
2394 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2397 if ( $this->mLastSection
!= '' ) {
2398 $output .= '</' . $this->mLastSection
. '>';
2399 $this->mLastSection
= '';
2402 wfProfileOut( __METHOD__
);
2407 * Split up a string on ':', ignoring any occurences inside tags
2408 * to prevent illegal overlapping.
2410 * @param $str String: the string to split
2411 * @param &$before String: set to everything before the ':'
2412 * @param &$after String: set to everything after the ':'
2413 * return String: the position of the ':', or false if none found
2415 function findColonNoLinks( $str, &$before, &$after ) {
2416 wfProfileIn( __METHOD__
);
2418 $pos = strpos( $str, ':' );
2419 if ( $pos === false ) {
2421 wfProfileOut( __METHOD__
);
2425 $lt = strpos( $str, '<' );
2426 if ( $lt === false ||
$lt > $pos ) {
2427 # Easy; no tag nesting to worry about
2428 $before = substr( $str, 0, $pos );
2429 $after = substr( $str, $pos+
1 );
2430 wfProfileOut( __METHOD__
);
2434 # Ugly state machine to walk through avoiding tags.
2435 $state = self
::COLON_STATE_TEXT
;
2437 $len = strlen( $str );
2438 for( $i = 0; $i < $len; $i++
) {
2442 # (Using the number is a performance hack for common cases)
2443 case 0: # self::COLON_STATE_TEXT:
2446 # Could be either a <start> tag or an </end> tag
2447 $state = self
::COLON_STATE_TAGSTART
;
2450 if ( $stack == 0 ) {
2452 $before = substr( $str, 0, $i );
2453 $after = substr( $str, $i +
1 );
2454 wfProfileOut( __METHOD__
);
2457 # Embedded in a tag; don't break it.
2460 # Skip ahead looking for something interesting
2461 $colon = strpos( $str, ':', $i );
2462 if ( $colon === false ) {
2463 # Nothing else interesting
2464 wfProfileOut( __METHOD__
);
2467 $lt = strpos( $str, '<', $i );
2468 if ( $stack === 0 ) {
2469 if ( $lt === false ||
$colon < $lt ) {
2471 $before = substr( $str, 0, $colon );
2472 $after = substr( $str, $colon +
1 );
2473 wfProfileOut( __METHOD__
);
2477 if ( $lt === false ) {
2478 # Nothing else interesting to find; abort!
2479 # We're nested, but there's no close tags left. Abort!
2482 # Skip ahead to next tag start
2484 $state = self
::COLON_STATE_TAGSTART
;
2487 case 1: # self::COLON_STATE_TAG:
2492 $state = self
::COLON_STATE_TEXT
;
2495 # Slash may be followed by >?
2496 $state = self
::COLON_STATE_TAGSLASH
;
2502 case 2: # self::COLON_STATE_TAGSTART:
2505 $state = self
::COLON_STATE_CLOSETAG
;
2508 $state = self
::COLON_STATE_COMMENT
;
2511 # Illegal early close? This shouldn't happen D:
2512 $state = self
::COLON_STATE_TEXT
;
2515 $state = self
::COLON_STATE_TAG
;
2518 case 3: # self::COLON_STATE_CLOSETAG:
2523 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2524 wfProfileOut( __METHOD__
);
2527 $state = self
::COLON_STATE_TEXT
;
2530 case self
::COLON_STATE_TAGSLASH
:
2532 # Yes, a self-closed tag <blah/>
2533 $state = self
::COLON_STATE_TEXT
;
2535 # Probably we're jumping the gun, and this is an attribute
2536 $state = self
::COLON_STATE_TAG
;
2539 case 5: # self::COLON_STATE_COMMENT:
2541 $state = self
::COLON_STATE_COMMENTDASH
;
2544 case self
::COLON_STATE_COMMENTDASH
:
2546 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2548 $state = self
::COLON_STATE_COMMENT
;
2551 case self
::COLON_STATE_COMMENTDASHDASH
:
2553 $state = self
::COLON_STATE_TEXT
;
2555 $state = self
::COLON_STATE_COMMENT
;
2559 throw new MWException( "State machine error in " . __METHOD__
);
2563 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2564 wfProfileOut( __METHOD__
);
2567 wfProfileOut( __METHOD__
);
2572 * Return value of a magic variable (like PAGENAME)
2576 * @param $index integer
2577 * @param $frame PPFrame
2579 function getVariableValue( $index, $frame=false ) {
2580 global $wgContLang, $wgSitename, $wgServer;
2581 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2584 * Some of these require message or data lookups and can be
2585 * expensive to check many times.
2587 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2588 if ( isset( $this->mVarCache
[$index] ) ) {
2589 return $this->mVarCache
[$index];
2593 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2594 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2597 global $wgLocaltimezone;
2598 if ( isset( $wgLocaltimezone ) ) {
2599 $oldtz = date_default_timezone_get();
2600 date_default_timezone_set( $wgLocaltimezone );
2603 $localTimestamp = date( 'YmdHis', $ts );
2604 $localMonth = date( 'm', $ts );
2605 $localMonth1 = date( 'n', $ts );
2606 $localMonthName = date( 'n', $ts );
2607 $localDay = date( 'j', $ts );
2608 $localDay2 = date( 'd', $ts );
2609 $localDayOfWeek = date( 'w', $ts );
2610 $localWeek = date( 'W', $ts );
2611 $localYear = date( 'Y', $ts );
2612 $localHour = date( 'H', $ts );
2613 if ( isset( $wgLocaltimezone ) ) {
2614 date_default_timezone_set( $oldtz );
2618 case 'currentmonth':
2619 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2621 case 'currentmonth1':
2622 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2624 case 'currentmonthname':
2625 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2627 case 'currentmonthnamegen':
2628 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2630 case 'currentmonthabbrev':
2631 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2634 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2637 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2640 $value = $wgContLang->formatNum( $localMonth );
2643 $value = $wgContLang->formatNum( $localMonth1 );
2645 case 'localmonthname':
2646 $value = $wgContLang->getMonthName( $localMonthName );
2648 case 'localmonthnamegen':
2649 $value = $wgContLang->getMonthNameGen( $localMonthName );
2651 case 'localmonthabbrev':
2652 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2655 $value = $wgContLang->formatNum( $localDay );
2658 $value = $wgContLang->formatNum( $localDay2 );
2661 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2664 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2666 case 'fullpagename':
2667 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2669 case 'fullpagenamee':
2670 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2673 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2675 case 'subpagenamee':
2676 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2678 case 'basepagename':
2679 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2681 case 'basepagenamee':
2682 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2684 case 'talkpagename':
2685 if ( $this->mTitle
->canTalk() ) {
2686 $talkPage = $this->mTitle
->getTalkPage();
2687 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2692 case 'talkpagenamee':
2693 if ( $this->mTitle
->canTalk() ) {
2694 $talkPage = $this->mTitle
->getTalkPage();
2695 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2700 case 'subjectpagename':
2701 $subjPage = $this->mTitle
->getSubjectPage();
2702 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2704 case 'subjectpagenamee':
2705 $subjPage = $this->mTitle
->getSubjectPage();
2706 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2709 # Let the edit saving system know we should parse the page
2710 # *after* a revision ID has been assigned.
2711 $this->mOutput
->setFlag( 'vary-revision' );
2712 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2713 $value = $this->mRevisionId
;
2716 # Let the edit saving system know we should parse the page
2717 # *after* a revision ID has been assigned. This is for null edits.
2718 $this->mOutput
->setFlag( 'vary-revision' );
2719 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2720 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2722 case 'revisionday2':
2723 # Let the edit saving system know we should parse the page
2724 # *after* a revision ID has been assigned. This is for null edits.
2725 $this->mOutput
->setFlag( 'vary-revision' );
2726 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2727 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2729 case 'revisionmonth':
2730 # Let the edit saving system know we should parse the page
2731 # *after* a revision ID has been assigned. This is for null edits.
2732 $this->mOutput
->setFlag( 'vary-revision' );
2733 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2734 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2736 case 'revisionmonth1':
2737 # Let the edit saving system know we should parse the page
2738 # *after* a revision ID has been assigned. This is for null edits.
2739 $this->mOutput
->setFlag( 'vary-revision' );
2740 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2741 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2743 case 'revisionyear':
2744 # Let the edit saving system know we should parse the page
2745 # *after* a revision ID has been assigned. This is for null edits.
2746 $this->mOutput
->setFlag( 'vary-revision' );
2747 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2748 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2750 case 'revisiontimestamp':
2751 # Let the edit saving system know we should parse the page
2752 # *after* a revision ID has been assigned. This is for null edits.
2753 $this->mOutput
->setFlag( 'vary-revision' );
2754 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2755 $value = $this->getRevisionTimestamp();
2757 case 'revisionuser':
2758 # Let the edit saving system know we should parse the page
2759 # *after* a revision ID has been assigned. This is for null edits.
2760 $this->mOutput
->setFlag( 'vary-revision' );
2761 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2762 $value = $this->getRevisionUser();
2765 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2768 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2771 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2774 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2776 case 'subjectspace':
2777 $value = $this->mTitle
->getSubjectNsText();
2779 case 'subjectspacee':
2780 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2782 case 'currentdayname':
2783 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2786 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2789 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2792 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2795 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2796 # int to remove the padding
2797 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2800 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2802 case 'localdayname':
2803 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2806 $value = $wgContLang->formatNum( $localYear, true );
2809 $value = $wgContLang->time( $localTimestamp, false, false );
2812 $value = $wgContLang->formatNum( $localHour, true );
2815 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2816 # int to remove the padding
2817 $value = $wgContLang->formatNum( (int)$localWeek );
2820 $value = $wgContLang->formatNum( $localDayOfWeek );
2822 case 'numberofarticles':
2823 $value = $wgContLang->formatNum( SiteStats
::articles() );
2825 case 'numberoffiles':
2826 $value = $wgContLang->formatNum( SiteStats
::images() );
2828 case 'numberofusers':
2829 $value = $wgContLang->formatNum( SiteStats
::users() );
2831 case 'numberofactiveusers':
2832 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2834 case 'numberofpages':
2835 $value = $wgContLang->formatNum( SiteStats
::pages() );
2837 case 'numberofadmins':
2838 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2840 case 'numberofedits':
2841 $value = $wgContLang->formatNum( SiteStats
::edits() );
2843 case 'numberofviews':
2844 $value = $wgContLang->formatNum( SiteStats
::views() );
2846 case 'currenttimestamp':
2847 $value = wfTimestamp( TS_MW
, $ts );
2849 case 'localtimestamp':
2850 $value = $localTimestamp;
2852 case 'currentversion':
2853 $value = SpecialVersion
::getVersion();
2856 return $wgArticlePath;
2862 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2863 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2864 wfRestoreWarnings();
2865 return $serverName ?
$serverName : $wgServer;
2867 return $wgScriptPath;
2869 return $wgStylePath;
2870 case 'directionmark':
2871 return $wgContLang->getDirMark();
2872 case 'contentlanguage':
2873 global $wgLanguageCode;
2874 return $wgLanguageCode;
2877 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2885 $this->mVarCache
[$index] = $value;
2891 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2895 function initialiseVariables() {
2896 wfProfileIn( __METHOD__
);
2897 $variableIDs = MagicWord
::getVariableIDs();
2898 $substIDs = MagicWord
::getSubstIDs();
2900 $this->mVariables
= new MagicWordArray( $variableIDs );
2901 $this->mSubstWords
= new MagicWordArray( $substIDs );
2902 wfProfileOut( __METHOD__
);
2906 * Preprocess some wikitext and return the document tree.
2907 * This is the ghost of replace_variables().
2909 * @param $text String: The text to parse
2910 * @param $flags Integer: bitwise combination of:
2911 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2912 * included. Default is to assume a direct page view.
2914 * The generated DOM tree must depend only on the input text and the flags.
2915 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2917 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2918 * change in the DOM tree for a given text, must be passed through the section identifier
2919 * in the section edit link and thus back to extractSections().
2921 * The output of this function is currently only cached in process memory, but a persistent
2922 * cache may be implemented at a later date which takes further advantage of these strict
2923 * dependency requirements.
2929 function preprocessToDom( $text, $flags = 0 ) {
2930 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2935 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2939 public static function splitWhitespace( $s ) {
2940 $ltrimmed = ltrim( $s );
2941 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2942 $trimmed = rtrim( $ltrimmed );
2943 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2945 $w2 = substr( $ltrimmed, -$diff );
2949 return array( $w1, $trimmed, $w2 );
2953 * Replace magic variables, templates, and template arguments
2954 * with the appropriate text. Templates are substituted recursively,
2955 * taking care to avoid infinite loops.
2957 * Note that the substitution depends on value of $mOutputType:
2958 * self::OT_WIKI: only {{subst:}} templates
2959 * self::OT_PREPROCESS: templates but not extension tags
2960 * self::OT_HTML: all templates and extension tags
2962 * @param $text String: the text to transform
2963 * @param $frame PPFrame Object describing the arguments passed to the template.
2964 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2965 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2966 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2971 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2972 # Is there any text? Also, Prevent too big inclusions!
2973 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2976 wfProfileIn( __METHOD__
);
2978 if ( $frame === false ) {
2979 $frame = $this->getPreprocessor()->newFrame();
2980 } elseif ( !( $frame instanceof PPFrame
) ) {
2981 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2982 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2985 $dom = $this->preprocessToDom( $text );
2986 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2987 $text = $frame->expand( $dom, $flags );
2989 wfProfileOut( __METHOD__
);
2994 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2998 static function createAssocArgs( $args ) {
2999 $assocArgs = array();
3001 foreach ( $args as $arg ) {
3002 $eqpos = strpos( $arg, '=' );
3003 if ( $eqpos === false ) {
3004 $assocArgs[$index++
] = $arg;
3006 $name = trim( substr( $arg, 0, $eqpos ) );
3007 $value = trim( substr( $arg, $eqpos+
1 ) );
3008 if ( $value === false ) {
3011 if ( $name !== false ) {
3012 $assocArgs[$name] = $value;
3021 * Warn the user when a parser limitation is reached
3022 * Will warn at most once the user per limitation type
3024 * @param $limitationType String: should be one of:
3025 * 'expensive-parserfunction' (corresponding messages:
3026 * 'expensive-parserfunction-warning',
3027 * 'expensive-parserfunction-category')
3028 * 'post-expand-template-argument' (corresponding messages:
3029 * 'post-expand-template-argument-warning',
3030 * 'post-expand-template-argument-category')
3031 * 'post-expand-template-inclusion' (corresponding messages:
3032 * 'post-expand-template-inclusion-warning',
3033 * 'post-expand-template-inclusion-category')
3034 * @param $current Current value
3035 * @param $max Maximum allowed, when an explicit limit has been
3036 * exceeded, provide the values (optional)
3038 function limitationWarn( $limitationType, $current=null, $max=null) {
3039 # does no harm if $current and $max are present but are unnecessary for the message
3040 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3041 $this->mOutput
->addWarning( $warning );
3042 $this->addTrackingCategory( "$limitationType-category" );
3046 * Return the text of a template, after recursively
3047 * replacing any variables or templates within the template.
3049 * @param $piece Array: the parts of the template
3050 * $piece['title']: the title, i.e. the part before the |
3051 * $piece['parts']: the parameter array
3052 * $piece['lineStart']: whether the brace was at the start of a line
3053 * @param $frame PPFrame The current frame, contains template arguments
3054 * @return String: the text of the template
3057 function braceSubstitution( $piece, $frame ) {
3058 global $wgContLang, $wgNonincludableNamespaces;
3059 wfProfileIn( __METHOD__
);
3060 wfProfileIn( __METHOD__
.'-setup' );
3063 $found = false; # $text has been filled
3064 $nowiki = false; # wiki markup in $text should be escaped
3065 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3066 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3067 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3068 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3070 # Title object, where $text came from
3073 # $part1 is the bit before the first |, and must contain only title characters.
3074 # Various prefixes will be stripped from it later.
3075 $titleWithSpaces = $frame->expand( $piece['title'] );
3076 $part1 = trim( $titleWithSpaces );
3079 # Original title text preserved for various purposes
3080 $originalTitle = $part1;
3082 # $args is a list of argument nodes, starting from index 0, not including $part1
3083 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3084 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3085 wfProfileOut( __METHOD__
.'-setup' );
3086 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3089 wfProfileIn( __METHOD__
.'-modifiers' );
3092 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3094 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3095 # Decide whether to expand template or keep wikitext as-is.
3096 if ( $this->ot
['wiki'] ) {
3097 if ( $substMatch === false ) {
3098 $literal = true; # literal when in PST with no prefix
3100 $literal = false; # expand when in PST with subst: or safesubst:
3103 if ( $substMatch == 'subst' ) {
3104 $literal = true; # literal when not in PST with plain subst:
3106 $literal = false; # expand when not in PST with safesubst: or no prefix
3110 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3117 if ( !$found && $args->getLength() == 0 ) {
3118 $id = $this->mVariables
->matchStartToEnd( $part1 );
3119 if ( $id !== false ) {
3120 $text = $this->getVariableValue( $id, $frame );
3121 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3122 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3128 # MSG, MSGNW and RAW
3131 $mwMsgnw = MagicWord
::get( 'msgnw' );
3132 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3135 # Remove obsolete MSG:
3136 $mwMsg = MagicWord
::get( 'msg' );
3137 $mwMsg->matchStartAndRemove( $part1 );
3141 $mwRaw = MagicWord
::get( 'raw' );
3142 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3143 $forceRawInterwiki = true;
3146 wfProfileOut( __METHOD__
.'-modifiers' );
3150 wfProfileIn( __METHOD__
. '-pfunc' );
3152 $colonPos = strpos( $part1, ':' );
3153 if ( $colonPos !== false ) {
3154 # Case sensitive functions
3155 $function = substr( $part1, 0, $colonPos );
3156 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3157 $function = $this->mFunctionSynonyms
[1][$function];
3159 # Case insensitive functions
3160 $function = $wgContLang->lc( $function );
3161 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3162 $function = $this->mFunctionSynonyms
[0][$function];
3168 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3169 $initialArgs = array( &$this );
3170 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3171 if ( $flags & SFH_OBJECT_ARGS
) {
3172 # Add a frame parameter, and pass the arguments as an array
3173 $allArgs = $initialArgs;
3174 $allArgs[] = $frame;
3175 for ( $i = 0; $i < $args->getLength(); $i++
) {
3176 $funcArgs[] = $args->item( $i );
3178 $allArgs[] = $funcArgs;
3180 # Convert arguments to plain text
3181 for ( $i = 0; $i < $args->getLength(); $i++
) {
3182 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3184 $allArgs = array_merge( $initialArgs, $funcArgs );
3187 # Workaround for PHP bug 35229 and similar
3188 if ( !is_callable( $callback ) ) {
3189 wfProfileOut( __METHOD__
. '-pfunc' );
3190 wfProfileOut( __METHOD__
);
3191 throw new MWException( "Tag hook for $function is not callable\n" );
3193 $result = call_user_func_array( $callback, $allArgs );
3196 $preprocessFlags = 0;
3198 if ( is_array( $result ) ) {
3199 if ( isset( $result[0] ) ) {
3201 unset( $result[0] );
3204 # Extract flags into the local scope
3205 # This allows callers to set flags such as nowiki, found, etc.
3211 $text = $this->preprocessToDom( $text, $preprocessFlags );
3216 wfProfileOut( __METHOD__
. '-pfunc' );
3219 # Finish mangling title and then check for loops.
3220 # Set $title to a Title object and $titleText to the PDBK
3223 # Split the title into page and subpage
3225 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3226 if ( $subpage !== '' ) {
3227 $ns = $this->mTitle
->getNamespace();
3229 $title = Title
::newFromText( $part1, $ns );
3231 $titleText = $title->getPrefixedText();
3232 # Check for language variants if the template is not found
3233 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3234 $wgContLang->findVariantLink( $part1, $title, true );
3236 # Do recursion depth check
3237 $limit = $this->mOptions
->getMaxTemplateDepth();
3238 if ( $frame->depth
>= $limit ) {
3240 $text = '<span class="error">'
3241 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3247 # Load from database
3248 if ( !$found && $title ) {
3249 wfProfileIn( __METHOD__
. '-loadtpl' );
3250 if ( !$title->isExternal() ) {
3251 if ( $title->getNamespace() == NS_SPECIAL
3252 && $this->mOptions
->getAllowSpecialInclusion()
3253 && $this->ot
['html'] )
3255 $text = SpecialPageFactory
::capturePath( $title );
3256 if ( is_string( $text ) ) {
3259 $this->disableCache();
3261 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3262 $found = false; # access denied
3263 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3265 list( $text, $title ) = $this->getTemplateDom( $title );
3266 if ( $text !== false ) {
3272 # If the title is valid but undisplayable, make a link to it
3273 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3274 $text = "[[:$titleText]]";
3277 } elseif ( $title->isTrans() ) {
3278 # Interwiki transclusion
3279 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3280 $text = $this->interwikiTransclude( $title, 'render' );
3283 $text = $this->interwikiTransclude( $title, 'raw' );
3284 # Preprocess it like a template
3285 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3291 # Do infinite loop check
3292 # This has to be done after redirect resolution to avoid infinite loops via redirects
3293 if ( !$frame->loopCheck( $title ) ) {
3295 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3296 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3298 wfProfileOut( __METHOD__
. '-loadtpl' );
3301 # If we haven't found text to substitute by now, we're done
3302 # Recover the source wikitext and return it
3304 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3305 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3306 wfProfileOut( __METHOD__
);
3307 return array( 'object' => $text );
3310 # Expand DOM-style return values in a child frame
3311 if ( $isChildObj ) {
3312 # Clean up argument array
3313 $newFrame = $frame->newChild( $args, $title );
3316 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3317 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3318 # Expansion is eligible for the empty-frame cache
3319 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3320 $text = $this->mTplExpandCache
[$titleText];
3322 $text = $newFrame->expand( $text );
3323 $this->mTplExpandCache
[$titleText] = $text;
3326 # Uncached expansion
3327 $text = $newFrame->expand( $text );
3330 if ( $isLocalObj && $nowiki ) {
3331 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3332 $isLocalObj = false;
3335 # Replace raw HTML by a placeholder
3336 # Add a blank line preceding, to prevent it from mucking up
3337 # immediately preceding headings
3339 $text = "\n\n" . $this->insertStripItem( $text );
3340 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3341 # Escape nowiki-style return values
3342 $text = wfEscapeWikiText( $text );
3343 } elseif ( is_string( $text )
3344 && !$piece['lineStart']
3345 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3347 # Bug 529: if the template begins with a table or block-level
3348 # element, it should be treated as beginning a new line.
3349 # This behaviour is somewhat controversial.
3350 $text = "\n" . $text;
3353 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3354 # Error, oversize inclusion
3355 if ( $titleText !== false ) {
3356 # Make a working, properly escaped link if possible (bug 23588)
3357 $text = "[[:$titleText]]";
3359 # This will probably not be a working link, but at least it may
3360 # provide some hint of where the problem is
3361 preg_replace( '/^:/', '', $originalTitle );
3362 $text = "[[:$originalTitle]]";
3364 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3365 $this->limitationWarn( 'post-expand-template-inclusion' );
3368 if ( $isLocalObj ) {
3369 $ret = array( 'object' => $text );
3371 $ret = array( 'text' => $text );
3374 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3375 wfProfileOut( __METHOD__
);
3380 * Get the semi-parsed DOM representation of a template with a given title,
3381 * and its redirect destination title. Cached.
3385 function getTemplateDom( $title ) {
3386 $cacheTitle = $title;
3387 $titleText = $title->getPrefixedDBkey();
3389 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3390 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3391 $title = Title
::makeTitle( $ns, $dbk );
3392 $titleText = $title->getPrefixedDBkey();
3394 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3395 return array( $this->mTplDomCache
[$titleText], $title );
3398 # Cache miss, go to the database
3399 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3401 if ( $text === false ) {
3402 $this->mTplDomCache
[$titleText] = false;
3403 return array( false, $title );
3406 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3407 $this->mTplDomCache
[ $titleText ] = $dom;
3409 if ( !$title->equals( $cacheTitle ) ) {
3410 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3411 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3414 return array( $dom, $title );
3418 * Fetch the unparsed text of a template and register a reference to it.
3419 * @param Title $title
3420 * @return Array ( string or false, Title )
3422 function fetchTemplateAndTitle( $title ) {
3423 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3424 $stuff = call_user_func( $templateCb, $title, $this );
3425 $text = $stuff['text'];
3426 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3427 if ( isset( $stuff['deps'] ) ) {
3428 foreach ( $stuff['deps'] as $dep ) {
3429 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3432 return array( $text, $finalTitle );
3436 * Fetch the unparsed text of a template and register a reference to it.
3437 * @param Title $title
3438 * @return mixed string or false
3440 function fetchTemplate( $title ) {
3441 $rv = $this->fetchTemplateAndTitle( $title );
3446 * Static function to get a template
3447 * Can be overridden via ParserOptions::setTemplateCallback().
3451 static function statelessFetchTemplate( $title, $parser = false ) {
3452 $text = $skip = false;
3453 $finalTitle = $title;
3456 # Loop to fetch the article, with up to 1 redirect
3457 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3458 # Give extensions a chance to select the revision instead
3459 $id = false; # Assume current
3460 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3461 array( $parser, $title, &$skip, &$id ) );
3467 'page_id' => $title->getArticleID(),
3474 ? Revision
::newFromId( $id )
3475 : Revision
::newFromTitle( $title );
3476 $rev_id = $rev ?
$rev->getId() : 0;
3477 # If there is no current revision, there is no page
3478 if ( $id === false && !$rev ) {
3479 $linkCache = LinkCache
::singleton();
3480 $linkCache->addBadLinkObj( $title );
3485 'page_id' => $title->getArticleID(),
3486 'rev_id' => $rev_id );
3487 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3488 # We fetched a rev from a different title; register it too...
3490 'title' => $rev->getTitle(),
3491 'page_id' => $rev->getPage(),
3492 'rev_id' => $rev_id );
3496 $text = $rev->getText();
3497 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3499 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3500 if ( !$message->exists() ) {
3504 $text = $message->plain();
3508 if ( $text === false ) {
3512 $finalTitle = $title;
3513 $title = Title
::newFromRedirect( $text );
3517 'finalTitle' => $finalTitle,
3522 * Fetch a file and its title and register a reference to it.
3523 * @param Title $title
3524 * @param string $time MW timestamp
3525 * @param string $sha1 base 36 SHA-1
3526 * @return mixed File or false
3528 function fetchFile( $title, $time = false, $sha1 = false ) {
3529 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3534 * Fetch a file and its title and register a reference to it.
3535 * @param Title $title
3536 * @param string $time MW timestamp
3537 * @param string $sha1 base 36 SHA-1
3538 * @return Array ( File or false, Title of file )
3540 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3541 if ( $time === '0' ) {
3542 $file = false; // broken thumbnail forced by hook
3543 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3544 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3545 } else { // get by (name,timestamp)
3546 $file = wfFindFile( $title, array( 'time' => $time ) );
3548 $time = $file ?
$file->getTimestamp() : false;
3549 $sha1 = $file ?
$file->getSha1() : false;
3550 # Register the file as a dependency...
3551 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3552 if ( $file && !$title->equals( $file->getTitle() ) ) {
3553 # Update fetched file title
3554 $title = $file->getTitle();
3556 return array( $file, $title );
3560 * Transclude an interwiki link.
3562 * @param $title Title
3567 function interwikiTransclude( $title, $action ) {
3568 global $wgEnableScaryTranscluding;
3570 if ( !$wgEnableScaryTranscluding ) {
3571 return wfMsgForContent('scarytranscludedisabled');
3574 $url = $title->getFullUrl( "action=$action" );
3576 if ( strlen( $url ) > 255 ) {
3577 return wfMsgForContent( 'scarytranscludetoolong' );
3579 return $this->fetchScaryTemplateMaybeFromCache( $url );
3583 * @param $url string
3584 * @return Mixed|String
3586 function fetchScaryTemplateMaybeFromCache( $url ) {
3587 global $wgTranscludeCacheExpiry;
3588 $dbr = wfGetDB( DB_SLAVE
);
3589 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3590 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3591 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3593 return $obj->tc_contents
;
3596 $text = Http
::get( $url );
3598 return wfMsgForContent( 'scarytranscludefailed', $url );
3601 $dbw = wfGetDB( DB_MASTER
);
3602 $dbw->replace( 'transcache', array('tc_url'), array(
3604 'tc_time' => $dbw->timestamp( time() ),
3605 'tc_contents' => $text)
3611 * Triple brace replacement -- used for template arguments
3614 * @param $peice array
3615 * @param $frame PPFrame
3619 function argSubstitution( $piece, $frame ) {
3620 wfProfileIn( __METHOD__
);
3623 $parts = $piece['parts'];
3624 $nameWithSpaces = $frame->expand( $piece['title'] );
3625 $argName = trim( $nameWithSpaces );
3627 $text = $frame->getArgument( $argName );
3628 if ( $text === false && $parts->getLength() > 0
3632 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3635 # No match in frame, use the supplied default
3636 $object = $parts->item( 0 )->getChildren();
3638 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3639 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3640 $this->limitationWarn( 'post-expand-template-argument' );
3643 if ( $text === false && $object === false ) {
3645 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3647 if ( $error !== false ) {
3650 if ( $object !== false ) {
3651 $ret = array( 'object' => $object );
3653 $ret = array( 'text' => $text );
3656 wfProfileOut( __METHOD__
);
3661 * Return the text to be used for a given extension tag.
3662 * This is the ghost of strip().
3664 * @param $params Associative array of parameters:
3665 * name PPNode for the tag name
3666 * attr PPNode for unparsed text where tag attributes are thought to be
3667 * attributes Optional associative array of parsed attributes
3668 * inner Contents of extension element
3669 * noClose Original text did not have a close tag
3670 * @param $frame PPFrame
3674 function extensionSubstitution( $params, $frame ) {
3675 $name = $frame->expand( $params['name'] );
3676 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3677 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3678 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3680 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3681 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3682 if ( $isFunctionTag ) {
3683 $markerType = 'none';
3685 $markerType = 'general';
3687 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3688 $name = strtolower( $name );
3689 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3690 if ( isset( $params['attributes'] ) ) {
3691 $attributes = $attributes +
$params['attributes'];
3694 if ( isset( $this->mTagHooks
[$name] ) ) {
3695 # Workaround for PHP bug 35229 and similar
3696 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3697 throw new MWException( "Tag hook for $name is not callable\n" );
3699 $output = call_user_func_array( $this->mTagHooks
[$name],
3700 array( $content, $attributes, $this, $frame ) );
3701 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3702 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3703 if ( !is_callable( $callback ) ) {
3704 throw new MWException( "Tag hook for $name is not callable\n" );
3707 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3709 $output = '<span class="error">Invalid tag extension name: ' .
3710 htmlspecialchars( $name ) . '</span>';
3713 if ( is_array( $output ) ) {
3714 # Extract flags to local scope (to override $markerType)
3716 $output = $flags[0];
3721 if ( is_null( $attrText ) ) {
3724 if ( isset( $params['attributes'] ) ) {
3725 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3726 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3727 htmlspecialchars( $attrValue ) . '"';
3730 if ( $content === null ) {
3731 $output = "<$name$attrText/>";
3733 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3734 $output = "<$name$attrText>$content$close";
3738 if ( $markerType === 'none' ) {
3740 } elseif ( $markerType === 'nowiki' ) {
3741 $this->mStripState
->addNoWiki( $marker, $output );
3742 } elseif ( $markerType === 'general' ) {
3743 $this->mStripState
->addGeneral( $marker, $output );
3745 throw new MWException( __METHOD__
.': invalid marker type' );
3751 * Increment an include size counter
3753 * @param $type String: the type of expansion
3754 * @param $size Integer: the size of the text
3755 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3757 function incrementIncludeSize( $type, $size ) {
3758 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3761 $this->mIncludeSizes
[$type] +
= $size;
3767 * Increment the expensive function count
3769 * @return Boolean: false if the limit has been exceeded
3771 function incrementExpensiveFunctionCount() {
3772 global $wgExpensiveParserFunctionLimit;
3773 $this->mExpensiveFunctionCount++
;
3774 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3781 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3782 * Fills $this->mDoubleUnderscores, returns the modified text
3784 function doDoubleUnderscore( $text ) {
3785 wfProfileIn( __METHOD__
);
3787 # The position of __TOC__ needs to be recorded
3788 $mw = MagicWord
::get( 'toc' );
3789 if ( $mw->match( $text ) ) {
3790 $this->mShowToc
= true;
3791 $this->mForceTocPosition
= true;
3793 # Set a placeholder. At the end we'll fill it in with the TOC.
3794 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3796 # Only keep the first one.
3797 $text = $mw->replace( '', $text );
3800 # Now match and remove the rest of them
3801 $mwa = MagicWord
::getDoubleUnderscoreArray();
3802 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3804 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3805 $this->mOutput
->mNoGallery
= true;
3807 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3808 $this->mShowToc
= false;
3810 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3811 $this->addTrackingCategory( 'hidden-category-category' );
3813 # (bug 8068) Allow control over whether robots index a page.
3815 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3816 # is not desirable, the last one on the page should win.
3817 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3818 $this->mOutput
->setIndexPolicy( 'noindex' );
3819 $this->addTrackingCategory( 'noindex-category' );
3821 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3822 $this->mOutput
->setIndexPolicy( 'index' );
3823 $this->addTrackingCategory( 'index-category' );
3826 # Cache all double underscores in the database
3827 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3828 $this->mOutput
->setProperty( $key, '' );
3831 wfProfileOut( __METHOD__
);
3836 * Add a tracking category, getting the title from a system message,
3837 * or print a debug message if the title is invalid.
3839 * @param $msg String: message key
3840 * @return Boolean: whether the addition was successful
3842 protected function addTrackingCategory( $msg ) {
3843 $cat = wfMsgForContent( $msg );
3845 # Allow tracking categories to be disabled by setting them to "-"
3846 if ( $cat === '-' ) {
3850 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3851 if ( $containerCategory ) {
3852 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3855 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3861 * This function accomplishes several tasks:
3862 * 1) Auto-number headings if that option is enabled
3863 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3864 * 3) Add a Table of contents on the top for users who have enabled the option
3865 * 4) Auto-anchor headings
3867 * It loops through all headlines, collects the necessary data, then splits up the
3868 * string and re-inserts the newly formatted headlines.
3870 * @param $text String
3871 * @param $origText String: original, untouched wikitext
3872 * @param $isMain Boolean
3875 function formatHeadings( $text, $origText, $isMain=true ) {
3876 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3878 # Inhibit editsection links if requested in the page
3879 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3882 $showEditLink = $this->mOptions
->getEditSection();
3884 if ( $showEditLink ) {
3885 $this->mOutput
->setEditSectionTokens( true );
3888 # Get all headlines for numbering them and adding funky stuff like [edit]
3889 # links - this is for later, but we need the number of headlines right now
3891 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3893 # if there are fewer than 4 headlines in the article, do not show TOC
3894 # unless it's been explicitly enabled.
3895 $enoughToc = $this->mShowToc
&&
3896 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3898 # Allow user to stipulate that a page should have a "new section"
3899 # link added via __NEWSECTIONLINK__
3900 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3901 $this->mOutput
->setNewSection( true );
3904 # Allow user to remove the "new section"
3905 # link via __NONEWSECTIONLINK__
3906 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3907 $this->mOutput
->hideNewSection( true );
3910 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3911 # override above conditions and always show TOC above first header
3912 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3913 $this->mShowToc
= true;
3921 # Ugh .. the TOC should have neat indentation levels which can be
3922 # passed to the skin functions. These are determined here
3926 $sublevelCount = array();
3927 $levelCount = array();
3932 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3933 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3934 $oldType = $this->mOutputType
;
3935 $this->setOutputType( self
::OT_WIKI
);
3936 $frame = $this->getPreprocessor()->newFrame();
3937 $root = $this->preprocessToDom( $origText );
3938 $node = $root->getFirstChild();
3943 foreach ( $matches[3] as $headline ) {
3944 $isTemplate = false;
3946 $sectionIndex = false;
3948 $markerMatches = array();
3949 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3950 $serial = $markerMatches[1];
3951 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3952 $isTemplate = ( $titleText != $baseTitleText );
3953 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3957 $prevlevel = $level;
3959 $level = $matches[1][$headlineCount];
3961 if ( $level > $prevlevel ) {
3962 # Increase TOC level
3964 $sublevelCount[$toclevel] = 0;
3965 if ( $toclevel<$wgMaxTocLevel ) {
3966 $prevtoclevel = $toclevel;
3967 $toc .= Linker
::tocIndent();
3970 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3971 # Decrease TOC level, find level to jump to
3973 for ( $i = $toclevel; $i > 0; $i-- ) {
3974 if ( $levelCount[$i] == $level ) {
3975 # Found last matching level
3978 } elseif ( $levelCount[$i] < $level ) {
3979 # Found first matching level below current level
3987 if ( $toclevel<$wgMaxTocLevel ) {
3988 if ( $prevtoclevel < $wgMaxTocLevel ) {
3989 # Unindent only if the previous toc level was shown :p
3990 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3991 $prevtoclevel = $toclevel;
3993 $toc .= Linker
::tocLineEnd();
3997 # No change in level, end TOC line
3998 if ( $toclevel<$wgMaxTocLevel ) {
3999 $toc .= Linker
::tocLineEnd();
4003 $levelCount[$toclevel] = $level;
4005 # count number of headlines for each level
4006 @$sublevelCount[$toclevel]++
;
4008 for( $i = 1; $i <= $toclevel; $i++
) {
4009 if ( !empty( $sublevelCount[$i] ) ) {
4013 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
4018 # The safe header is a version of the header text safe to use for links
4019 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4020 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4022 # Remove link placeholders by the link text.
4023 # <!--LINK number-->
4025 # link text with suffix
4026 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4028 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4029 $tocline = preg_replace(
4030 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4031 array( '', '<$1>' ),
4034 $tocline = trim( $tocline );
4036 # For the anchor, strip out HTML-y stuff period
4037 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4038 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4040 # Save headline for section edit hint before it's escaped
4041 $headlineHint = $safeHeadline;
4043 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4044 # For reverse compatibility, provide an id that's
4045 # HTML4-compatible, like we used to.
4047 # It may be worth noting, academically, that it's possible for
4048 # the legacy anchor to conflict with a non-legacy headline
4049 # anchor on the page. In this case likely the "correct" thing
4050 # would be to either drop the legacy anchors or make sure
4051 # they're numbered first. However, this would require people
4052 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4053 # manually, so let's not bother worrying about it.
4054 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4055 array( 'noninitial', 'legacy' ) );
4056 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4058 if ( $legacyHeadline == $safeHeadline ) {
4059 # No reason to have both (in fact, we can't)
4060 $legacyHeadline = false;
4063 $legacyHeadline = false;
4064 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4068 # HTML names must be case-insensitively unique (bug 10721).
4069 # This does not apply to Unicode characters per
4070 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4071 # @todo FIXME: We may be changing them depending on the current locale.
4072 $arrayKey = strtolower( $safeHeadline );
4073 if ( $legacyHeadline === false ) {
4074 $legacyArrayKey = false;
4076 $legacyArrayKey = strtolower( $legacyHeadline );
4079 # count how many in assoc. array so we can track dupes in anchors
4080 if ( isset( $refers[$arrayKey] ) ) {
4081 $refers[$arrayKey]++
;
4083 $refers[$arrayKey] = 1;
4085 if ( isset( $refers[$legacyArrayKey] ) ) {
4086 $refers[$legacyArrayKey]++
;
4088 $refers[$legacyArrayKey] = 1;
4091 # Don't number the heading if it is the only one (looks silly)
4092 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4093 # the two are different if the line contains a link
4094 $headline = $numbering . ' ' . $headline;
4097 # Create the anchor for linking from the TOC to the section
4098 $anchor = $safeHeadline;
4099 $legacyAnchor = $legacyHeadline;
4100 if ( $refers[$arrayKey] > 1 ) {
4101 $anchor .= '_' . $refers[$arrayKey];
4103 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4104 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4106 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4107 $toc .= Linker
::tocLine( $anchor, $tocline,
4108 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4111 # Add the section to the section tree
4112 # Find the DOM node for this header
4113 while ( $node && !$isTemplate ) {
4114 if ( $node->getName() === 'h' ) {
4115 $bits = $node->splitHeading();
4116 if ( $bits['i'] == $sectionIndex ) {
4120 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4121 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4122 $node = $node->getNextSibling();
4125 'toclevel' => $toclevel,
4128 'number' => $numbering,
4129 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4130 'fromtitle' => $titleText,
4131 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4132 'anchor' => $anchor,
4135 # give headline the correct <h#> tag
4136 if ( $showEditLink && $sectionIndex !== false ) {
4137 // Output edit section links as markers with styles that can be customized by skins
4138 if ( $isTemplate ) {
4139 # Put a T flag in the section identifier, to indicate to extractSections()
4140 # that sections inside <includeonly> should be counted.
4141 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4143 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4145 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4146 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4147 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4148 // so we don't have to worry about a user trying to input one of these markers directly.
4149 // We use a page and section attribute to stop the language converter from converting these important bits
4150 // of data, but put the headline hint inside a content block because the language converter is supposed to
4151 // be able to convert that piece of data.
4152 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4153 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4154 if ( isset($editlinkArgs[2]) ) {
4155 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4162 $head[$headlineCount] = Linker
::makeHeadline( $level,
4163 $matches['attrib'][$headlineCount], $anchor, $headline,
4164 $editlink, $legacyAnchor );
4169 $this->setOutputType( $oldType );
4171 # Never ever show TOC if no headers
4172 if ( $numVisible < 1 ) {
4177 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4178 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4180 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4181 $this->mOutput
->setTOCHTML( $toc );
4185 $this->mOutput
->setSections( $tocraw );
4188 # split up and insert constructed headlines
4190 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4193 foreach ( $blocks as $block ) {
4194 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4195 # This is the [edit] link that appears for the top block of text when
4196 # section editing is enabled
4198 # Disabled because it broke block formatting
4199 # For example, a bullet point in the top line
4200 # $full .= $sk->editSectionLink(0);
4203 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4204 # Top anchor now in skin
4208 if ( !empty( $head[$i] ) ) {
4213 if ( $this->mForceTocPosition
) {
4214 return str_replace( '<!--MWTOC-->', $toc, $full );
4221 * Transform wiki markup when saving a page by doing \r\n -> \n
4222 * conversion, substitting signatures, {{subst:}} templates, etc.
4224 * @param $text String: the text to transform
4225 * @param $title Title: the Title object for the current article
4226 * @param $user User: the User object describing the current user
4227 * @param $options ParserOptions: parsing options
4228 * @param $clearState Boolean: whether to clear the parser state first
4229 * @return String: the altered wiki markup
4231 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4232 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4233 $this->setUser( $user );
4238 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4239 if( $options->getPreSaveTransform() ) {
4240 $text = $this->pstPass2( $text, $user );
4242 $text = $this->mStripState
->unstripBoth( $text );
4244 $this->setUser( null ); #Reset
4250 * Pre-save transform helper function
4253 function pstPass2( $text, $user ) {
4254 global $wgContLang, $wgLocaltimezone;
4256 # Note: This is the timestamp saved as hardcoded wikitext to
4257 # the database, we use $wgContLang here in order to give
4258 # everyone the same signature and use the default one rather
4259 # than the one selected in each user's preferences.
4260 # (see also bug 12815)
4261 $ts = $this->mOptions
->getTimestamp();
4262 if ( isset( $wgLocaltimezone ) ) {
4263 $tz = $wgLocaltimezone;
4265 $tz = date_default_timezone_get();
4268 $unixts = wfTimestamp( TS_UNIX
, $ts );
4269 $oldtz = date_default_timezone_get();
4270 date_default_timezone_set( $tz );
4271 $ts = date( 'YmdHis', $unixts );
4272 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4274 # Allow translation of timezones through wiki. date() can return
4275 # whatever crap the system uses, localised or not, so we cannot
4276 # ship premade translations.
4277 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4278 $msg = wfMessage( $key )->inContentLanguage();
4279 if ( $msg->exists() ) {
4280 $tzMsg = $msg->text();
4283 date_default_timezone_set( $oldtz );
4285 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4287 # Variable replacement
4288 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4289 $text = $this->replaceVariables( $text );
4291 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4292 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4295 $sigText = $this->getUserSig( $user );
4296 $text = strtr( $text, array(
4298 '~~~~' => "$sigText $d",
4302 # Context links: [[|name]] and [[name (context)|]]
4303 global $wgLegalTitleChars;
4304 $tc = "[$wgLegalTitleChars]";
4305 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4307 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4308 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4309 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4310 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4312 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4313 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4314 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4315 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4317 $t = $this->mTitle
->getText();
4319 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4320 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4321 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4322 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4324 # if there's no context, don't bother duplicating the title
4325 $text = preg_replace( $p2, '[[\\1]]', $text );
4328 # Trim trailing whitespace
4329 $text = rtrim( $text );
4335 * Fetch the user's signature text, if any, and normalize to
4336 * validated, ready-to-insert wikitext.
4337 * If you have pre-fetched the nickname or the fancySig option, you can
4338 * specify them here to save a database query.
4339 * Do not reuse this parser instance after calling getUserSig(),
4340 * as it may have changed if it's the $wgParser.
4343 * @param $nickname String: nickname to use or false to use user's default nickname
4344 * @param $fancySig Boolean: whether the nicknname is the complete signature
4345 * or null to use default value
4348 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4349 global $wgMaxSigChars;
4351 $username = $user->getName();
4353 # If not given, retrieve from the user object.
4354 if ( $nickname === false )
4355 $nickname = $user->getOption( 'nickname' );
4357 if ( is_null( $fancySig ) ) {
4358 $fancySig = $user->getBoolOption( 'fancysig' );
4361 $nickname = $nickname == null ?
$username : $nickname;
4363 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4364 $nickname = $username;
4365 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4366 } elseif ( $fancySig !== false ) {
4367 # Sig. might contain markup; validate this
4368 if ( $this->validateSig( $nickname ) !== false ) {
4369 # Validated; clean up (if needed) and return it
4370 return $this->cleanSig( $nickname, true );
4372 # Failed to validate; fall back to the default
4373 $nickname = $username;
4374 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4378 # Make sure nickname doesnt get a sig in a sig
4379 $nickname = $this->cleanSigInSig( $nickname );
4381 # If we're still here, make it a link to the user page
4382 $userText = wfEscapeWikiText( $username );
4383 $nickText = wfEscapeWikiText( $nickname );
4384 if ( $user->isAnon() ) {
4385 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4387 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4392 * Check that the user's signature contains no bad XML
4394 * @param $text String
4395 * @return mixed An expanded string, or false if invalid.
4397 function validateSig( $text ) {
4398 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4402 * Clean up signature text
4404 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4405 * 2) Substitute all transclusions
4407 * @param $text String
4408 * @param $parsing Whether we're cleaning (preferences save) or parsing
4409 * @return String: signature text
4411 function cleanSig( $text, $parsing = false ) {
4414 $this->mOptions
= new ParserOptions
;
4415 $this->clearState();
4416 $this->setTitle( $wgTitle );
4417 $this->setOutputType
= self
::OT_PREPROCESS
;
4420 # Option to disable this feature
4421 if ( !$this->mOptions
->getCleanSignatures() ) {
4425 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4426 # => Move this logic to braceSubstitution()
4427 $substWord = MagicWord
::get( 'subst' );
4428 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4429 $substText = '{{' . $substWord->getSynonym( 0 );
4431 $text = preg_replace( $substRegex, $substText, $text );
4432 $text = $this->cleanSigInSig( $text );
4433 $dom = $this->preprocessToDom( $text );
4434 $frame = $this->getPreprocessor()->newFrame();
4435 $text = $frame->expand( $dom );
4438 $text = $this->mStripState
->unstripBoth( $text );
4445 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4447 * @param $text String
4448 * @return String: signature text with /~{3,5}/ removed
4450 function cleanSigInSig( $text ) {
4451 $text = preg_replace( '/~{3,5}/', '', $text );
4456 * Set up some variables which are usually set up in parse()
4457 * so that an external function can call some class members with confidence
4459 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4460 $this->startParse( $title, $options, $outputType, $clearState );
4463 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4464 $this->setTitle( $title );
4465 $this->mOptions
= $options;
4466 $this->setOutputType( $outputType );
4467 if ( $clearState ) {
4468 $this->clearState();
4473 * Wrapper for preprocess()
4475 * @param $text String: the text to preprocess
4476 * @param $options ParserOptions: options
4477 * @param $title Title object or null to use $wgTitle
4480 public function transformMsg( $text, $options, $title = null ) {
4481 static $executing = false;
4483 # Guard against infinite recursion
4489 wfProfileIn( __METHOD__
);
4495 # It's not uncommon having a null $wgTitle in scripts. See r80898
4496 # Create a ghost title in such case
4497 $title = Title
::newFromText( 'Dwimmerlaik' );
4499 $text = $this->preprocess( $text, $title, $options );
4502 wfProfileOut( __METHOD__
);
4507 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4508 * The callback should have the following form:
4509 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4511 * Transform and return $text. Use $parser for any required context, e.g. use
4512 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4514 * Hooks may return extended information by returning an array, of which the
4515 * first numbered element (index 0) must be the return string, and all other
4516 * entries are extracted into local variables within an internal function
4517 * in the Parser class.
4519 * This interface (introduced r61913) appears to be undocumented, but
4520 * 'markerName' is used by some core tag hooks to override which strip
4521 * array their results are placed in. **Use great caution if attempting
4522 * this interface, as it is not documented and injudicious use could smash
4523 * private variables.**
4525 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4526 * @param $callback Mixed: the callback function (and object) to use for the tag
4527 * @return The old value of the mTagHooks array associated with the hook
4529 public function setHook( $tag, $callback ) {
4530 $tag = strtolower( $tag );
4531 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4532 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4533 $this->mTagHooks
[$tag] = $callback;
4534 if ( !in_array( $tag, $this->mStripList
) ) {
4535 $this->mStripList
[] = $tag;
4542 * As setHook(), but letting the contents be parsed.
4544 * Transparent tag hooks are like regular XML-style tag hooks, except they
4545 * operate late in the transformation sequence, on HTML instead of wikitext.
4547 * This is probably obsoleted by things dealing with parser frames?
4548 * The only extension currently using it is geoserver.
4551 * @todo better document or deprecate this
4553 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4554 * @param $callback Mixed: the callback function (and object) to use for the tag
4555 * @return The old value of the mTagHooks array associated with the hook
4557 function setTransparentTagHook( $tag, $callback ) {
4558 $tag = strtolower( $tag );
4559 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4560 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4561 $this->mTransparentTagHooks
[$tag] = $callback;
4567 * Remove all tag hooks
4569 function clearTagHooks() {
4570 $this->mTagHooks
= array();
4571 $this->mStripList
= $this->mDefaultStripList
;
4575 * Remove a specific tag hook. Should not be called on $wgParser.
4576 * Does not change the strip list.
4578 * @param string $tag
4581 function clearTagHook( $tag ) {
4582 if ( isset( $this->mTagHooks
[$tag] ) ) {
4583 unset( $this->mTagHooks
[$tag] );
4588 * Create a function, e.g. {{sum:1|2|3}}
4589 * The callback function should have the form:
4590 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4592 * Or with SFH_OBJECT_ARGS:
4593 * function myParserFunction( $parser, $frame, $args ) { ... }
4595 * The callback may either return the text result of the function, or an array with the text
4596 * in element 0, and a number of flags in the other elements. The names of the flags are
4597 * specified in the keys. Valid flags are:
4598 * found The text returned is valid, stop processing the template. This
4600 * nowiki Wiki markup in the return value should be escaped
4601 * isHTML The returned text is HTML, armour it against wikitext transformation
4603 * @param $id String: The magic word ID
4604 * @param $callback Mixed: the callback function (and object) to use
4605 * @param $flags Integer: a combination of the following flags:
4606 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4608 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4609 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4610 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4611 * the arguments, and to control the way they are expanded.
4613 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4614 * arguments, for instance:
4615 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4617 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4618 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4619 * working if/when this is changed.
4621 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4624 * Please read the documentation in includes/parser/Preprocessor.php for more information
4625 * about the methods available in PPFrame and PPNode.
4627 * @return The old callback function for this name, if any
4629 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4632 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4633 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4635 # Add to function cache
4636 $mw = MagicWord
::get( $id );
4638 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4640 $synonyms = $mw->getSynonyms();
4641 $sensitive = intval( $mw->isCaseSensitive() );
4643 foreach ( $synonyms as $syn ) {
4645 if ( !$sensitive ) {
4646 $syn = $wgContLang->lc( $syn );
4649 if ( !( $flags & SFH_NO_HASH
) ) {
4652 # Remove trailing colon
4653 if ( substr( $syn, -1, 1 ) === ':' ) {
4654 $syn = substr( $syn, 0, -1 );
4656 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4662 * Get all registered function hook identifiers
4666 function getFunctionHooks() {
4667 return array_keys( $this->mFunctionHooks
);
4671 * Create a tag function, e.g. <test>some stuff</test>.
4672 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4673 * Unlike parser functions, their content is not preprocessed.
4675 function setFunctionTagHook( $tag, $callback, $flags ) {
4676 $tag = strtolower( $tag );
4677 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4678 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4679 $this->mFunctionTagHooks
[$tag] : null;
4680 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4682 if ( !in_array( $tag, $this->mStripList
) ) {
4683 $this->mStripList
[] = $tag;
4690 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4691 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4692 * Placeholders created in Skin::makeLinkObj()
4693 * Returns an array of link CSS classes, indexed by PDBK.
4695 function replaceLinkHolders( &$text, $options = 0 ) {
4696 return $this->mLinkHolders
->replace( $text );
4700 * Replace <!--LINK--> link placeholders with plain text of links
4701 * (not HTML-formatted).
4703 * @param $text String
4706 function replaceLinkHoldersText( $text ) {
4707 return $this->mLinkHolders
->replaceText( $text );
4711 * Renders an image gallery from a text with one line per image.
4712 * text labels may be given by using |-style alternative text. E.g.
4713 * Image:one.jpg|The number "1"
4714 * Image:tree.jpg|A tree
4715 * given as text will return the HTML of a gallery with two images,
4716 * labeled 'The number "1"' and
4719 * @param string $text
4720 * @param array $param
4721 * @return string HTML
4723 function renderImageGallery( $text, $params ) {
4724 $ig = new ImageGallery();
4725 $ig->setContextTitle( $this->mTitle
);
4726 $ig->setShowBytes( false );
4727 $ig->setShowFilename( false );
4728 $ig->setParser( $this );
4729 $ig->setHideBadImages();
4730 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4732 if ( isset( $params['showfilename'] ) ) {
4733 $ig->setShowFilename( true );
4735 $ig->setShowFilename( false );
4737 if ( isset( $params['caption'] ) ) {
4738 $caption = $params['caption'];
4739 $caption = htmlspecialchars( $caption );
4740 $caption = $this->replaceInternalLinks( $caption );
4741 $ig->setCaptionHtml( $caption );
4743 if ( isset( $params['perrow'] ) ) {
4744 $ig->setPerRow( $params['perrow'] );
4746 if ( isset( $params['widths'] ) ) {
4747 $ig->setWidths( $params['widths'] );
4749 if ( isset( $params['heights'] ) ) {
4750 $ig->setHeights( $params['heights'] );
4753 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4755 $lines = StringUtils
::explode( "\n", $text );
4756 foreach ( $lines as $line ) {
4757 # match lines like these:
4758 # Image:someimage.jpg|This is some image
4760 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4762 if ( count( $matches ) == 0 ) {
4766 if ( strpos( $matches[0], '%' ) !== false ) {
4767 $matches[1] = rawurldecode( $matches[1] );
4769 $title = Title
::newFromText( $matches[1], NS_FILE
);
4770 if ( is_null( $title ) ) {
4771 # Bogus title. Ignore these so we don't bomb out later.
4777 if ( isset( $matches[3] ) ) {
4778 // look for an |alt= definition while trying not to break existing
4779 // captions with multiple pipes (|) in it, until a more sensible grammar
4780 // is defined for images in galleries
4782 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4783 $altmatches = StringUtils
::explode('|', $matches[3]);
4784 $magicWordAlt = MagicWord
::get( 'img_alt' );
4786 foreach ( $altmatches as $altmatch ) {
4787 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4789 $alt = $this->stripAltText( $match, false );
4792 // concatenate all other pipes
4793 $label .= '|' . $altmatch;
4796 // remove the first pipe
4797 $label = substr( $label, 1 );
4800 $ig->add( $title, $label, $alt );
4802 return $ig->toHTML();
4805 function getImageParams( $handler ) {
4807 $handlerClass = get_class( $handler );
4811 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4812 # Initialise static lists
4813 static $internalParamNames = array(
4814 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4815 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4816 'bottom', 'text-bottom' ),
4817 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4818 'upright', 'border', 'link', 'alt' ),
4820 static $internalParamMap;
4821 if ( !$internalParamMap ) {
4822 $internalParamMap = array();
4823 foreach ( $internalParamNames as $type => $names ) {
4824 foreach ( $names as $name ) {
4825 $magicName = str_replace( '-', '_', "img_$name" );
4826 $internalParamMap[$magicName] = array( $type, $name );
4831 # Add handler params
4832 $paramMap = $internalParamMap;
4834 $handlerParamMap = $handler->getParamMap();
4835 foreach ( $handlerParamMap as $magic => $paramName ) {
4836 $paramMap[$magic] = array( 'handler', $paramName );
4839 $this->mImageParams
[$handlerClass] = $paramMap;
4840 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4842 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4846 * Parse image options text and use it to make an image
4848 * @param $title Title
4849 * @param $options String
4850 * @param $holders LinkHolderArray
4851 * @return string HTML
4853 function makeImage( $title, $options, $holders = false ) {
4854 # Check if the options text is of the form "options|alt text"
4856 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4857 # * left no resizing, just left align. label is used for alt= only
4858 # * right same, but right aligned
4859 # * none same, but not aligned
4860 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4861 # * center center the image
4862 # * frame Keep original image size, no magnify-button.
4863 # * framed Same as "frame"
4864 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4865 # * upright reduce width for upright images, rounded to full __0 px
4866 # * border draw a 1px border around the image
4867 # * alt Text for HTML alt attribute (defaults to empty)
4868 # * link Set the target of the image link. Can be external, interwiki, or local
4869 # vertical-align values (no % or length right now):
4879 $parts = StringUtils
::explode( "|", $options );
4881 # Give extensions a chance to select the file revision for us
4882 $time = $sha1 = $descQuery = false;
4883 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4884 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4885 # Fetch and register the file (file title may be different via hooks)
4886 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4889 $handler = $file ?
$file->getHandler() : false;
4891 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4894 $this->addTrackingCategory( 'broken-file-category' );
4897 # Process the input parameters
4899 $params = array( 'frame' => array(), 'handler' => array(),
4900 'horizAlign' => array(), 'vertAlign' => array() );
4901 foreach ( $parts as $part ) {
4902 $part = trim( $part );
4903 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4905 if ( isset( $paramMap[$magicName] ) ) {
4906 list( $type, $paramName ) = $paramMap[$magicName];
4908 # Special case; width and height come in one variable together
4909 if ( $type === 'handler' && $paramName === 'width' ) {
4911 # (bug 13500) In both cases (width/height and width only),
4912 # permit trailing "px" for backward compatibility.
4913 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4914 $width = intval( $m[1] );
4915 $height = intval( $m[2] );
4916 if ( $handler->validateParam( 'width', $width ) ) {
4917 $params[$type]['width'] = $width;
4920 if ( $handler->validateParam( 'height', $height ) ) {
4921 $params[$type]['height'] = $height;
4924 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4925 $width = intval( $value );
4926 if ( $handler->validateParam( 'width', $width ) ) {
4927 $params[$type]['width'] = $width;
4930 } # else no validation -- bug 13436
4932 if ( $type === 'handler' ) {
4933 # Validate handler parameter
4934 $validated = $handler->validateParam( $paramName, $value );
4936 # Validate internal parameters
4937 switch( $paramName ) {
4940 # @todo FIXME: Possibly check validity here for
4941 # manualthumb? downstream behavior seems odd with
4942 # missing manual thumbs.
4944 $value = $this->stripAltText( $value, $holders );
4947 $chars = self
::EXT_LINK_URL_CLASS
;
4948 $prots = $this->mUrlProtocols
;
4949 if ( $value === '' ) {
4950 $paramName = 'no-link';
4953 } elseif ( preg_match( "/^$prots/", $value ) ) {
4954 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4955 $paramName = 'link-url';
4956 $this->mOutput
->addExternalLink( $value );
4957 if ( $this->mOptions
->getExternalLinkTarget() ) {
4958 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4963 $linkTitle = Title
::newFromText( $value );
4965 $paramName = 'link-title';
4966 $value = $linkTitle;
4967 $this->mOutput
->addLink( $linkTitle );
4973 # Most other things appear to be empty or numeric...
4974 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4979 $params[$type][$paramName] = $value;
4983 if ( !$validated ) {
4988 # Process alignment parameters
4989 if ( $params['horizAlign'] ) {
4990 $params['frame']['align'] = key( $params['horizAlign'] );
4992 if ( $params['vertAlign'] ) {
4993 $params['frame']['valign'] = key( $params['vertAlign'] );
4996 $params['frame']['caption'] = $caption;
4998 # Will the image be presented in a frame, with the caption below?
4999 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5000 isset( $params['frame']['framed'] ) ||
5001 isset( $params['frame']['thumbnail'] ) ||
5002 isset( $params['frame']['manualthumb'] );
5004 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5005 # came to also set the caption, ordinary text after the image -- which
5006 # makes no sense, because that just repeats the text multiple times in
5007 # screen readers. It *also* came to set the title attribute.
5009 # Now that we have an alt attribute, we should not set the alt text to
5010 # equal the caption: that's worse than useless, it just repeats the
5011 # text. This is the framed/thumbnail case. If there's no caption, we
5012 # use the unnamed parameter for alt text as well, just for the time be-
5013 # ing, if the unnamed param is set and the alt param is not.
5015 # For the future, we need to figure out if we want to tweak this more,
5016 # e.g., introducing a title= parameter for the title; ignoring the un-
5017 # named parameter entirely for images without a caption; adding an ex-
5018 # plicit caption= parameter and preserving the old magic unnamed para-
5020 if ( $imageIsFramed ) { # Framed image
5021 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5022 # No caption or alt text, add the filename as the alt text so
5023 # that screen readers at least get some description of the image
5024 $params['frame']['alt'] = $title->getText();
5026 # Do not set $params['frame']['title'] because tooltips don't make sense
5028 } else { # Inline image
5029 if ( !isset( $params['frame']['alt'] ) ) {
5030 # No alt text, use the "caption" for the alt text
5031 if ( $caption !== '') {
5032 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5034 # No caption, fall back to using the filename for the
5036 $params['frame']['alt'] = $title->getText();
5039 # Use the "caption" for the tooltip text
5040 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5043 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5045 # Linker does the rest
5046 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5047 $time, $descQuery, $this->mOptions
->getThumbSize() );
5049 # Give the handler a chance to modify the parser object
5051 $handler->parserTransformHook( $this, $file );
5059 * @param $holders LinkHolderArray
5060 * @return mixed|String
5062 protected function stripAltText( $caption, $holders ) {
5063 # Strip bad stuff out of the title (tooltip). We can't just use
5064 # replaceLinkHoldersText() here, because if this function is called
5065 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5067 $tooltip = $holders->replaceText( $caption );
5069 $tooltip = $this->replaceLinkHoldersText( $caption );
5072 # make sure there are no placeholders in thumbnail attributes
5073 # that are later expanded to html- so expand them now and
5075 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5076 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5082 * Set a flag in the output object indicating that the content is dynamic and
5083 * shouldn't be cached.
5085 function disableCache() {
5086 wfDebug( "Parser output marked as uncacheable.\n" );
5087 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5088 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5092 * Callback from the Sanitizer for expanding items found in HTML attribute
5093 * values, so they can be safely tested and escaped.
5095 * @param $text String
5096 * @param $frame PPFrame
5099 function attributeStripCallback( &$text, $frame = false ) {
5100 $text = $this->replaceVariables( $text, $frame );
5101 $text = $this->mStripState
->unstripBoth( $text );
5110 function getTags() {
5111 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5115 * Replace transparent tags in $text with the values given by the callbacks.
5117 * Transparent tag hooks are like regular XML-style tag hooks, except they
5118 * operate late in the transformation sequence, on HTML instead of wikitext.
5120 function replaceTransparentTags( $text ) {
5122 $elements = array_keys( $this->mTransparentTagHooks
);
5123 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5125 foreach ( $matches as $marker => $data ) {
5126 list( $element, $content, $params, $tag ) = $data;
5127 $tagName = strtolower( $element );
5128 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5129 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5133 $this->mStripState
->addGeneral( $marker, $output );
5139 * Break wikitext input into sections, and either pull or replace
5140 * some particular section's text.
5142 * External callers should use the getSection and replaceSection methods.
5144 * @param $text String: Page wikitext
5145 * @param $section String: a section identifier string of the form:
5146 * <flag1> - <flag2> - ... - <section number>
5148 * Currently the only recognised flag is "T", which means the target section number
5149 * was derived during a template inclusion parse, in other words this is a template
5150 * section edit link. If no flags are given, it was an ordinary section edit link.
5151 * This flag is required to avoid a section numbering mismatch when a section is
5152 * enclosed by <includeonly> (bug 6563).
5154 * The section number 0 pulls the text before the first heading; other numbers will
5155 * pull the given section along with its lower-level subsections. If the section is
5156 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5158 * @param $mode String: one of "get" or "replace"
5159 * @param $newText String: replacement text for section data.
5160 * @return String: for "get", the extracted section text.
5161 * for "replace", the whole page with the section replaced.
5163 private function extractSections( $text, $section, $mode, $newText='' ) {
5164 global $wgTitle; # not generally used but removes an ugly failure mode
5165 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5167 $frame = $this->getPreprocessor()->newFrame();
5169 # Process section extraction flags
5171 $sectionParts = explode( '-', $section );
5172 $sectionIndex = array_pop( $sectionParts );
5173 foreach ( $sectionParts as $part ) {
5174 if ( $part === 'T' ) {
5175 $flags |
= self
::PTD_FOR_INCLUSION
;
5178 # Preprocess the text
5179 $root = $this->preprocessToDom( $text, $flags );
5181 # <h> nodes indicate section breaks
5182 # They can only occur at the top level, so we can find them by iterating the root's children
5183 $node = $root->getFirstChild();
5185 # Find the target section
5186 if ( $sectionIndex == 0 ) {
5187 # Section zero doesn't nest, level=big
5188 $targetLevel = 1000;
5190 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5195 if ( $node->getName() === 'h' ) {
5196 $bits = $node->splitHeading();
5197 if ( $bits['i'] == $sectionIndex ) {
5198 $targetLevel = $bits['level'];
5202 if ( $mode === 'replace' ) {
5203 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5205 $node = $node->getNextSibling();
5211 if ( $mode === 'get' ) {
5218 # Find the end of the section, including nested sections
5220 if ( $node->getName() === 'h' ) {
5221 $bits = $node->splitHeading();
5222 $curLevel = $bits['level'];
5223 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5227 if ( $mode === 'get' ) {
5228 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5230 $node = $node->getNextSibling();
5233 # Write out the remainder (in replace mode only)
5234 if ( $mode === 'replace' ) {
5235 # Output the replacement text
5236 # Add two newlines on -- trailing whitespace in $newText is conventionally
5237 # stripped by the editor, so we need both newlines to restore the paragraph gap
5238 # Only add trailing whitespace if there is newText
5239 if ( $newText != "" ) {
5240 $outText .= $newText . "\n\n";
5244 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5245 $node = $node->getNextSibling();
5249 if ( is_string( $outText ) ) {
5250 # Re-insert stripped tags
5251 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5258 * This function returns the text of a section, specified by a number ($section).
5259 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5260 * the first section before any such heading (section 0).
5262 * If a section contains subsections, these are also returned.
5264 * @param $text String: text to look in
5265 * @param $section String: section identifier
5266 * @param $deftext String: default to return if section is not found
5267 * @return string text of the requested section
5269 public function getSection( $text, $section, $deftext='' ) {
5270 return $this->extractSections( $text, $section, "get", $deftext );
5274 * This function returns $oldtext after the content of the section
5275 * specified by $section has been replaced with $text.
5277 * @param $oldtext String: former text of the article
5278 * @param $section Numeric: section identifier
5279 * @param $text String: replacing text
5280 * @return String: modified text
5282 public function replaceSection( $oldtext, $section, $text ) {
5283 return $this->extractSections( $oldtext, $section, "replace", $text );
5287 * Get the ID of the revision we are parsing
5289 * @return Mixed: integer or null
5291 function getRevisionId() {
5292 return $this->mRevisionId
;
5296 * Get the revision object for $this->mRevisionId
5298 * @return Revision|null either a Revision object or null
5300 protected function getRevisionObject() {
5301 if ( !is_null( $this->mRevisionObject
) ) {
5302 return $this->mRevisionObject
;
5304 if ( is_null( $this->mRevisionId
) ) {
5308 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5309 return $this->mRevisionObject
;
5313 * Get the timestamp associated with the current revision, adjusted for
5314 * the default server-local timestamp
5316 function getRevisionTimestamp() {
5317 if ( is_null( $this->mRevisionTimestamp
) ) {
5318 wfProfileIn( __METHOD__
);
5320 $revObject = $this->getRevisionObject();
5321 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5323 if( $timestamp !== false ) {
5326 # The cryptic '' timezone parameter tells to use the site-default
5327 # timezone offset instead of the user settings.
5329 # Since this value will be saved into the parser cache, served
5330 # to other users, and potentially even used inside links and such,
5331 # it needs to be consistent for all visitors.
5332 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5335 wfProfileOut( __METHOD__
);
5337 return $this->mRevisionTimestamp
;
5341 * Get the name of the user that edited the last revision
5343 * @return String: user name
5345 function getRevisionUser() {
5346 if( is_null( $this->mRevisionUser
) ) {
5347 $revObject = $this->getRevisionObject();
5349 # if this template is subst: the revision id will be blank,
5350 # so just use the current user's name
5352 $this->mRevisionUser
= $revObject->getUserText();
5353 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5354 $this->mRevisionUser
= $this->getUser()->getName();
5357 return $this->mRevisionUser
;
5361 * Mutator for $mDefaultSort
5363 * @param $sort New value
5365 public function setDefaultSort( $sort ) {
5366 $this->mDefaultSort
= $sort;
5367 $this->mOutput
->setProperty( 'defaultsort', $sort );
5371 * Accessor for $mDefaultSort
5372 * Will use the empty string if none is set.
5374 * This value is treated as a prefix, so the
5375 * empty string is equivalent to sorting by
5380 public function getDefaultSort() {
5381 if ( $this->mDefaultSort
!== false ) {
5382 return $this->mDefaultSort
;
5389 * Accessor for $mDefaultSort
5390 * Unlike getDefaultSort(), will return false if none is set
5392 * @return string or false
5394 public function getCustomDefaultSort() {
5395 return $this->mDefaultSort
;
5399 * Try to guess the section anchor name based on a wikitext fragment
5400 * presumably extracted from a heading, for example "Header" from
5403 public function guessSectionNameFromWikiText( $text ) {
5404 # Strip out wikitext links(they break the anchor)
5405 $text = $this->stripSectionName( $text );
5406 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5407 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5411 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5412 * instead. For use in redirects, since IE6 interprets Redirect: headers
5413 * as something other than UTF-8 (apparently?), resulting in breakage.
5415 * @param $text String: The section name
5416 * @return string An anchor
5418 public function guessLegacySectionNameFromWikiText( $text ) {
5419 # Strip out wikitext links(they break the anchor)
5420 $text = $this->stripSectionName( $text );
5421 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5422 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5426 * Strips a text string of wikitext for use in a section anchor
5428 * Accepts a text string and then removes all wikitext from the
5429 * string and leaves only the resultant text (i.e. the result of
5430 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5431 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5432 * to create valid section anchors by mimicing the output of the
5433 * parser when headings are parsed.
5435 * @param $text String: text string to be stripped of wikitext
5436 * for use in a Section anchor
5437 * @return Filtered text string
5439 public function stripSectionName( $text ) {
5440 # Strip internal link markup
5441 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5442 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5444 # Strip external link markup
5445 # @todo FIXME: Not tolerant to blank link text
5446 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5447 # on how many empty links there are on the page - need to figure that out.
5448 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5450 # Parse wikitext quotes (italics & bold)
5451 $text = $this->doQuotes( $text );
5454 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5459 * strip/replaceVariables/unstrip for preprocessor regression testing
5463 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5464 $this->startParse( $title, $options, $outputType, true );
5466 $text = $this->replaceVariables( $text );
5467 $text = $this->mStripState
->unstripBoth( $text );
5468 $text = Sanitizer
::removeHTMLtags( $text );
5472 function testPst( $text, $title, $options ) {
5473 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5476 function testPreprocess( $text, $title, $options ) {
5477 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5481 * Call a callback function on all regions of the given text that are not
5482 * inside strip markers, and replace those regions with the return value
5483 * of the callback. For example, with input:
5487 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5488 * two strings will be replaced with the value returned by the callback in
5493 function markerSkipCallback( $s, $callback ) {
5496 while ( $i < strlen( $s ) ) {
5497 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5498 if ( $markerStart === false ) {
5499 $out .= call_user_func( $callback, substr( $s, $i ) );
5502 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5503 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5504 if ( $markerEnd === false ) {
5505 $out .= substr( $s, $markerStart );
5508 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5509 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5518 * Save the parser state required to convert the given half-parsed text to
5519 * HTML. "Half-parsed" in this context means the output of
5520 * recursiveTagParse() or internalParse(). This output has strip markers
5521 * from replaceVariables (extensionSubstitution() etc.), and link
5522 * placeholders from replaceLinkHolders().
5524 * Returns an array which can be serialized and stored persistently. This
5525 * array can later be loaded into another parser instance with
5526 * unserializeHalfParsedText(). The text can then be safely incorporated into
5527 * the return value of a parser hook.
5531 function serializeHalfParsedText( $text ) {
5532 wfProfileIn( __METHOD__
);
5535 'version' => self
::HALF_PARSED_VERSION
,
5536 'stripState' => $this->mStripState
->getSubState( $text ),
5537 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5539 wfProfileOut( __METHOD__
);
5544 * Load the parser state given in the $data array, which is assumed to
5545 * have been generated by serializeHalfParsedText(). The text contents is
5546 * extracted from the array, and its markers are transformed into markers
5547 * appropriate for the current Parser instance. This transformed text is
5548 * returned, and can be safely included in the return value of a parser
5551 * If the $data array has been stored persistently, the caller should first
5552 * check whether it is still valid, by calling isValidHalfParsedText().
5554 * @param $data Serialized data
5557 function unserializeHalfParsedText( $data ) {
5558 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5559 throw new MWException( __METHOD__
.': invalid version' );
5562 # First, extract the strip state.
5563 $texts = array( $data['text'] );
5564 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5566 # Now renumber links
5567 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5569 # Should be good to go.
5574 * Returns true if the given array, presumed to be generated by
5575 * serializeHalfParsedText(), is compatible with the current version of the
5578 * @param $data Array
5582 function isValidHalfParsedText( $data ) {
5583 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;