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
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mSubsts, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex,
95 $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList,
96 $mVarCache, $mConf, $mFunctionTagHooks;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mLinkHolders, $mLinkID;
103 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
104 var $mTplExpandCache; // empty-frame expansion cache
105 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
106 var $mExpensiveFunctionCount; // number of expensive parser function calls
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionTagHooks
= array();
131 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
132 $this->mDefaultStripList
= $this->mStripList
= array();
133 $this->mUrlProtocols
= wfUrlProtocols();
134 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
135 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
136 $this->mVarCache
= array();
137 if ( isset( $conf['preprocessorClass'] ) ) {
138 $this->mPreprocessorClass
= $conf['preprocessorClass'];
139 } elseif ( extension_loaded( 'domxml' ) ) {
140 // PECL extension that conflicts with the core DOM extension (bug 13770)
141 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
142 $this->mPreprocessorClass
= 'Preprocessor_Hash';
143 } elseif ( extension_loaded( 'dom' ) ) {
144 $this->mPreprocessorClass
= 'Preprocessor_DOM';
146 $this->mPreprocessorClass
= 'Preprocessor_Hash';
148 $this->mMarkerIndex
= 0;
149 $this->mFirstCall
= true;
153 * Reduce memory usage to reduce the impact of circular references
155 function __destruct() {
156 if ( isset( $this->mLinkHolders
) ) {
157 $this->mLinkHolders
->__destruct();
159 foreach ( $this as $name => $value ) {
160 unset( $this->$name );
165 * Do various kinds of initialisation on the first call of the parser
167 function firstCallInit() {
168 if ( !$this->mFirstCall
) {
171 $this->mFirstCall
= false;
173 wfProfileIn( __METHOD__
);
175 CoreParserFunctions
::register( $this );
176 CoreTagHooks
::register( $this );
177 $this->initialiseVariables();
179 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
180 wfProfileOut( __METHOD__
);
188 function clearState() {
189 wfProfileIn( __METHOD__
);
190 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= new StripState
;
199 $this->mArgStack
= false;
200 $this->mInPre
= false;
201 $this->mLinkHolders
= new LinkHolderArray( $this );
203 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
204 $this->mVarCache
= array();
207 * Prefix for temporary replacement strings for the multipass parser.
208 * \x07 should never appear in input as it's disallowed in XML.
209 * Using it at the front also gives us a little extra robustness
210 * since it shouldn't match when butted up against identifier-like
213 * Must not consist of all title characters, or else it will change
214 * the behaviour of <nowiki> in a link.
216 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
217 # Changed to \x7f to allow XML double-parsing -- TS
218 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
221 # Clear these on every parse, bug 4549
222 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
224 $this->mShowToc
= true;
225 $this->mForceTocPosition
= false;
226 $this->mIncludeSizes
= array(
230 $this->mPPNodeCount
= 0;
231 $this->mDefaultSort
= false;
232 $this->mHeadings
= array();
233 $this->mDoubleUnderscores
= array();
234 $this->mExpensiveFunctionCount
= 0;
237 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
238 $this->mPreprocessor
= null;
241 wfRunHooks( 'ParserClearState', array( &$this ) );
242 wfProfileOut( __METHOD__
);
245 function setOutputType( $ot ) {
246 $this->mOutputType
= $ot;
249 'html' => $ot == self
::OT_HTML
,
250 'wiki' => $ot == self
::OT_WIKI
,
251 'pre' => $ot == self
::OT_PREPROCESS
,
256 * Set the context title
258 function setTitle( $t ) {
259 if ( !$t ||
$t instanceof FakeTitle
) {
260 $t = Title
::newFromText( 'NO TITLE' );
263 if ( strval( $t->getFragment() ) !== '' ) {
264 # Strip the fragment to avoid various odd effects
265 $this->mTitle
= clone $t;
266 $this->mTitle
->setFragment( '' );
273 * Accessor for mUniqPrefix.
277 function uniqPrefix() {
278 if( !isset( $this->mUniqPrefix
) ) {
279 // @todo Fixme: this is probably *horribly wrong*
280 // LanguageConverter seems to want $wgParser's uniqPrefix, however
281 // if this is called for a parser cache hit, the parser may not
282 // have ever been initialized in the first place.
283 // Not really sure what the heck is supposed to be going on here.
285 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
287 return $this->mUniqPrefix
;
291 * Convert wikitext to HTML
292 * Do not call this function recursively.
294 * @param $text String: text we want to parse
295 * @param $title A title object
296 * @param $options ParserOptions
297 * @param $linestart boolean
298 * @param $clearState boolean
299 * @param $revid Int: number to pass in {{REVISIONID}}
300 * @return ParserOutput a ParserOutput
302 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
304 * First pass--just handle <nowiki> sections, pass the rest off
305 * to internalParse() which does all the real work.
308 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
309 $fname = __METHOD__
.'-' . wfGetCaller();
310 wfProfileIn( __METHOD__
);
311 wfProfileIn( $fname );
317 $this->mOptions
= $options;
318 $this->setTitle( $title ); // Page title has to be set for the pre-processor
320 $oldRevisionId = $this->mRevisionId
;
321 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
322 if( $revid !== null ) {
323 $this->mRevisionId
= $revid;
324 $this->mRevisionTimestamp
= null;
326 $this->setOutputType( self
::OT_HTML
);
327 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
329 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
330 $text = $this->internalParse( $text );
332 $text = $this->mStripState
->unstripGeneral( $text );
334 # Clean up special characters, only run once, next-to-last before doBlockLevels
336 # french spaces, last one Guillemet-left
337 # only if there is something before the space
338 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
339 # french spaces, Guillemet-right
340 '/(\\302\\253) /' => '\\1 ',
341 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
343 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
345 $text = $this->doBlockLevels( $text, $linestart );
347 $this->replaceLinkHolders( $text );
349 // The position of the convert() call should not be changed. it
350 // assumes that the links are all replaced and the only thing left
351 // is the <nowiki> mark.
352 if ( !( $wgDisableLangConversion
353 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
354 ||
$this->mTitle
->isTalkPage()
355 ||
$this->mTitle
->isConversionTable() ) ) {
356 $text = $wgContLang->convert( $text );
359 // A title may have been set in a conversion rule.
360 // Note that if a user tries to set a title in a conversion
361 // rule but content conversion was not done, then the parser
362 // won't pick it up. This is probably expected behavior.
363 if ( $wgContLang->getConvRuleTitle() ) {
364 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
365 } elseif ( !( $wgDisableLangConversion
366 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] ) ) ) {
367 $this->mOutput
->setTitleText( $wgContLang->convert( $title->getPrefixedText() ) );
370 $text = $this->mStripState
->unstripNoWiki( $text );
372 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
374 //!JF Move to its own function
376 $uniq_prefix = $this->mUniqPrefix
;
378 $elements = array_keys( $this->mTransparentTagHooks
);
379 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
381 foreach( $matches as $marker => $data ) {
382 list( $element, $content, $params, $tag ) = $data;
383 $tagName = strtolower( $element );
384 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
385 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
386 array( $content, $params, $this ) );
390 $this->mStripState
->general
->setPair( $marker, $output );
392 $text = $this->mStripState
->unstripGeneral( $text );
394 $text = Sanitizer
::normalizeCharReferences( $text );
396 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
397 $text = MWTidy
::tidy( $text );
399 # attempt to sanitize at least some nesting problems
400 # (bug #2702 and quite a few others)
402 # ''Something [http://www.cool.com cool''] -->
403 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
404 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
405 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
406 # fix up an anchor inside another anchor, only
407 # at least for a single single nested link (bug 3695)
408 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
409 '\\1\\2</a>\\3</a>\\1\\4</a>',
410 # fix div inside inline elements- doBlockLevels won't wrap a line which
411 # contains a div, so fix it up here; replace
412 # div with escaped text
413 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
414 '\\1\\3<div\\5>\\6</div>\\8\\9',
415 # remove empty italic or bold tag pairs, some
416 # introduced by rules above
417 '/<([bi])><\/\\1>/' => '',
420 $text = preg_replace(
421 array_keys( $tidyregs ),
422 array_values( $tidyregs ),
425 global $wgExpensiveParserFunctionLimit;
426 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
427 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
430 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
432 # Information on include size limits, for the benefit of users who try to skirt them
433 if ( $this->mOptions
->getEnableLimitReport() ) {
434 global $wgExpensiveParserFunctionLimit;
435 $max = $this->mOptions
->getMaxIncludeSize();
436 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
438 "NewPP limit report\n" .
439 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
440 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
441 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
443 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
444 $text .= "\n<!-- \n$limitReport-->\n";
446 $this->mOutput
->setText( $text );
448 $this->mRevisionId
= $oldRevisionId;
449 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
450 wfProfileOut( $fname );
451 wfProfileOut( __METHOD__
);
453 return $this->mOutput
;
457 * Recursive parser entry point that can be called from an extension tag
460 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
462 * @param $text String: text extension wants to have parsed
463 * @param PPFrame $frame: The frame to use for expanding any template variables
465 function recursiveTagParse( $text, $frame=false ) {
466 wfProfileIn( __METHOD__
);
467 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
468 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
469 $text = $this->internalParse( $text, false, $frame );
470 wfProfileOut( __METHOD__
);
475 * Expand templates and variables in the text, producing valid, static wikitext.
476 * Also removes comments.
478 function preprocess( $text, $title, $options, $revid = null ) {
479 wfProfileIn( __METHOD__
);
481 $this->setOutputType( self
::OT_PREPROCESS
);
482 $this->mOptions
= $options;
483 $this->setTitle( $title );
484 if( $revid !== null ) {
485 $this->mRevisionId
= $revid;
487 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
488 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
489 $text = $this->replaceVariables( $text );
490 $text = $this->mStripState
->unstripBoth( $text );
491 wfProfileOut( __METHOD__
);
496 * Get the wikitext of a page as though it was transcluded.
498 * Specifically <includeonly> etc. are parsed, redirects are followed, comments
499 * are removed, but templates arguments and parser functions are untouched.
501 * This is not called by the parser itself, see braceSubstitution for its transclusion.
503 public function getTransclusionText( $title ) {
504 list( $text, $title ) = $this->getTemplateDom( $title );
505 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
506 return $this->getPreprocessor()->newFrame()->expand( $text, $flags );
510 * Get a random string
515 function getRandomString() {
516 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
519 function &getTitle() { return $this->mTitle
; }
520 function getOptions() { return $this->mOptions
; }
521 function getRevisionId() { return $this->mRevisionId
; }
522 function getOutput() { return $this->mOutput
; }
523 function nextLinkID() { return $this->mLinkID++
; }
525 function getFunctionLang() {
526 global $wgLang, $wgContLang;
528 $target = $this->mOptions
->getTargetLanguage();
529 if ( $target !== null ) {
532 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
537 * Get a preprocessor object
539 function getPreprocessor() {
540 if ( !isset( $this->mPreprocessor
) ) {
541 $class = $this->mPreprocessorClass
;
542 $this->mPreprocessor
= new $class( $this );
544 return $this->mPreprocessor
;
548 * Replaces all occurrences of HTML-style comments and the given tags
549 * in the text with a random marker and returns the next text. The output
550 * parameter $matches will be an associative array filled with data in
552 * 'UNIQ-xxxxx' => array(
555 * array( 'param' => 'x' ),
556 * '<element param="x">tag content</element>' ) )
558 * @param $elements list of element names. Comments are always extracted.
559 * @param $text Source text string.
560 * @param $uniq_prefix
565 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
570 $taglist = implode( '|', $elements );
571 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
573 while ( $text != '' ) {
574 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
576 if( count( $p ) < 5 ) {
579 if( count( $p ) > 5 ) {
593 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
594 $stripped .= $marker;
596 if ( $close === '/>' ) {
597 // Empty element tag, <tag />
602 if( $element === '!--' ) {
605 $end = "/(<\\/$element\\s*>)/i";
607 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
609 if( count( $q ) < 3 ) {
610 # No end tag -- let it run out to the end of the text.
619 $matches[$marker] = array( $element,
621 Sanitizer
::decodeTagAttributes( $attributes ),
622 "<$element$attributes$close$content$tail" );
628 * Get a list of strippable XML-like elements
630 function getStripList() {
631 return $this->mStripList
;
635 * @deprecated use replaceVariables
637 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
642 * Restores pre, math, and other extensions removed by strip()
644 * always call unstripNoWiki() after this one
646 * @deprecated use $this->mStripState->unstrip()
648 function unstrip( $text, $state ) {
649 return $state->unstripGeneral( $text );
653 * Always call this after unstrip() to preserve the order
656 * @deprecated use $this->mStripState->unstrip()
658 function unstripNoWiki( $text, $state ) {
659 return $state->unstripNoWiki( $text );
663 * @deprecated use $this->mStripState->unstripBoth()
665 function unstripForHTML( $text ) {
666 return $this->mStripState
->unstripBoth( $text );
670 * Add an item to the strip state
671 * Returns the unique tag which must be inserted into the stripped text
672 * The tag will be replaced with the original text in unstrip()
676 function insertStripItem( $text ) {
677 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
678 $this->mMarkerIndex++
;
679 $this->mStripState
->general
->setPair( $rnd, $text );
684 * Interface with html tidy
685 * @deprecated Use MWTidy::tidy()
687 public static function tidy( $text ) {
688 wfDeprecated( __METHOD__
);
689 return MWTidy
::tidy( $text );
693 * parse the wiki syntax used to render tables
697 function doTableStuff ( $text ) {
698 wfProfileIn( __METHOD__
);
700 $lines = StringUtils
::explode( "\n", $text );
702 $td_history = array (); // Is currently a td tag open?
703 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
704 $tr_history = array (); // Is currently a tr tag open?
705 $tr_attributes = array (); // history of tr attributes
706 $has_opened_tr = array(); // Did this table open a <tr> element?
707 $indent_level = 0; // indent level of the table
709 foreach ( $lines as $outLine ) {
710 $line = trim( $outLine );
712 if( $line == '' ) { // empty line, go to next line
713 $out .= $outLine."\n";
716 $first_character = $line[0];
719 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
720 // First check if we are starting a new table
721 $indent_level = strlen( $matches[1] );
723 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
724 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
726 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
727 array_push( $td_history , false );
728 array_push( $last_tag_history , '' );
729 array_push( $tr_history , false );
730 array_push( $tr_attributes , '' );
731 array_push( $has_opened_tr , false );
732 } else if ( count ( $td_history ) == 0 ) {
733 // Don't do any of the following
734 $out .= $outLine."\n";
736 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
737 // We are ending a table
738 $line = '</table>' . substr ( $line , 2 );
739 $last_tag = array_pop ( $last_tag_history );
741 if ( !array_pop ( $has_opened_tr ) ) {
742 $line = "<tr><td></td></tr>{$line}";
745 if ( array_pop ( $tr_history ) ) {
746 $line = "</tr>{$line}";
749 if ( array_pop ( $td_history ) ) {
750 $line = "</{$last_tag}>{$line}";
752 array_pop ( $tr_attributes );
753 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
754 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
755 // Now we have a table row
756 $line = preg_replace( '#^\|-+#', '', $line );
758 // Whats after the tag is now only attributes
759 $attributes = $this->mStripState
->unstripBoth( $line );
760 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
761 array_pop( $tr_attributes );
762 array_push( $tr_attributes, $attributes );
765 $last_tag = array_pop ( $last_tag_history );
766 array_pop ( $has_opened_tr );
767 array_push ( $has_opened_tr , true );
769 if ( array_pop ( $tr_history ) ) {
773 if ( array_pop ( $td_history ) ) {
774 $line = "</{$last_tag}>{$line}";
778 array_push ( $tr_history , false );
779 array_push ( $td_history , false );
780 array_push ( $last_tag_history , '' );
782 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
783 // This might be cell elements, td, th or captions
784 if ( substr ( $line , 0 , 2 ) === '|+' ) {
785 $first_character = '+';
786 $line = substr ( $line , 1 );
789 $line = substr ( $line , 1 );
791 if ( $first_character === '!' ) {
792 $line = str_replace ( '!!' , '||' , $line );
795 // Split up multiple cells on the same line.
796 // FIXME : This can result in improper nesting of tags processed
797 // by earlier parser steps, but should avoid splitting up eg
798 // attribute values containing literal "||".
799 $cells = StringUtils
::explodeMarkup( '||' , $line );
803 // Loop through each table cell
804 foreach ( $cells as $cell )
807 if ( $first_character !== '+' )
809 $tr_after = array_pop ( $tr_attributes );
810 if ( !array_pop ( $tr_history ) ) {
811 $previous = "<tr{$tr_after}>\n";
813 array_push ( $tr_history , true );
814 array_push ( $tr_attributes , '' );
815 array_pop ( $has_opened_tr );
816 array_push ( $has_opened_tr , true );
819 $last_tag = array_pop ( $last_tag_history );
821 if ( array_pop ( $td_history ) ) {
822 $previous = "</{$last_tag}>{$previous}";
825 if ( $first_character === '|' ) {
827 } else if ( $first_character === '!' ) {
829 } else if ( $first_character === '+' ) {
830 $last_tag = 'caption';
835 array_push ( $last_tag_history , $last_tag );
837 // A cell could contain both parameters and data
838 $cell_data = explode ( '|' , $cell , 2 );
840 // Bug 553: Note that a '|' inside an invalid link should not
841 // be mistaken as delimiting cell parameters
842 if ( strpos( $cell_data[0], '[[' ) !== false ) {
843 $cell = "{$previous}<{$last_tag}>{$cell}";
844 } else if ( count ( $cell_data ) == 1 )
845 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
847 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
848 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
849 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
853 array_push ( $td_history , true );
856 $out .= $outLine . "\n";
859 // Closing open td, tr && table
860 while ( count ( $td_history ) > 0 )
862 if ( array_pop ( $td_history ) ) {
865 if ( array_pop ( $tr_history ) ) {
868 if ( !array_pop ( $has_opened_tr ) ) {
869 $out .= "<tr><td></td></tr>\n" ;
872 $out .= "</table>\n";
875 // Remove trailing line-ending (b/c)
876 if ( substr( $out, -1 ) === "\n" ) {
877 $out = substr( $out, 0, -1 );
880 // special case: don't return empty table
881 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
885 wfProfileOut( __METHOD__
);
891 * Helper function for parse() that transforms wiki markup into
892 * HTML. Only called for $mOutputType == self::OT_HTML.
896 function internalParse( $text, $isMain = true, $frame=false ) {
897 wfProfileIn( __METHOD__
);
901 # Hook to suspend the parser in this state
902 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
903 wfProfileOut( __METHOD__
);
907 // if $frame is provided, then use $frame for replacing any variables
909 // use frame depth to infer how include/noinclude tags should be handled
910 // depth=0 means this is the top-level document; otherwise it's an included document
914 $flag = Parser
::PTD_FOR_INCLUSION
;
915 $dom = $this->preprocessToDom( $text, $flag );
916 $text = $frame->expand( $dom );
918 // if $frame is not provided, then use old-style replaceVariables
920 $text = $this->replaceVariables( $text );
923 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
924 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
926 // Tables need to come after variable replacement for things to work
927 // properly; putting them before other transformations should keep
928 // exciting things like link expansions from showing up in surprising
930 $text = $this->doTableStuff( $text );
932 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
934 $text = $this->doDoubleUnderscore( $text );
936 $text = $this->doHeadings( $text );
937 if( $this->mOptions
->getUseDynamicDates() ) {
938 $df = DateFormatter
::getInstance();
939 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
941 $text = $this->doAllQuotes( $text );
942 $text = $this->replaceInternalLinks( $text );
943 $text = $this->replaceExternalLinks( $text );
945 # replaceInternalLinks may sometimes leave behind
946 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
947 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
949 $text = $this->doMagicLinks( $text );
950 $text = $this->formatHeadings( $text, $origText, $isMain );
952 wfProfileOut( __METHOD__
);
957 * Replace special strings like "ISBN xxx" and "RFC xxx" with
958 * magic external links.
963 function doMagicLinks( $text ) {
964 wfProfileIn( __METHOD__
);
965 $prots = $this->mUrlProtocols
;
966 $urlChar = self
::EXT_LINK_URL_CLASS
;
967 $text = preg_replace_callback(
969 (<a.*?</a>) | # m[1]: Skip link text
970 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
971 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
972 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
973 ISBN\s+(\b # m[5]: ISBN, capture number
974 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
975 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
976 [0-9Xx] # check digit
978 )!x', array( &$this, 'magicLinkCallback' ), $text );
979 wfProfileOut( __METHOD__
);
983 function magicLinkCallback( $m ) {
984 if ( isset( $m[1] ) && $m[1] !== '' ) {
987 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
990 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
992 return $this->makeFreeExternalLink( $m[0] );
993 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
996 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
999 $CssClass = 'mw-magiclink-rfc';
1001 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1003 $urlmsg = 'pubmedurl';
1004 $CssClass = 'mw-magiclink-pmid';
1007 throw new MWException( __METHOD__
.': unrecognised match type "' .
1008 substr($m[0], 0, 20 ) . '"' );
1010 $url = wfMsg( $urlmsg, $id);
1011 $sk = $this->mOptions
->getSkin();
1012 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1013 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1014 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1017 $num = strtr( $isbn, array(
1022 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1024 $titleObj->escapeLocalUrl() .
1025 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1032 * Make a free external link, given a user-supplied URL
1036 function makeFreeExternalLink( $url ) {
1038 wfProfileIn( __METHOD__
);
1040 $sk = $this->mOptions
->getSkin();
1043 # The characters '<' and '>' (which were escaped by
1044 # removeHTMLtags()) should not be included in
1045 # URLs, per RFC 2396.
1047 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1048 $trail = substr($url, $m2[0][1]) . $trail;
1049 $url = substr($url, 0, $m2[0][1]);
1052 # Move trailing punctuation to $trail
1054 # If there is no left bracket, then consider right brackets fair game too
1055 if ( strpos( $url, '(' ) === false ) {
1059 $numSepChars = strspn( strrev( $url ), $sep );
1060 if ( $numSepChars ) {
1061 $trail = substr( $url, -$numSepChars ) . $trail;
1062 $url = substr( $url, 0, -$numSepChars );
1065 $url = Sanitizer
::cleanUrl( $url );
1067 # Is this an external image?
1068 $text = $this->maybeMakeExternalImage( $url );
1069 if ( $text === false ) {
1070 # Not an image, make a link
1071 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1072 $this->getExternalLinkAttribs( $url ) );
1073 # Register it in the output object...
1074 # Replace unnecessary URL escape codes with their equivalent characters
1075 $pasteurized = self
::replaceUnusualEscapes( $url );
1076 $this->mOutput
->addExternalLink( $pasteurized );
1078 wfProfileOut( __METHOD__
);
1079 return $text . $trail;
1084 * Parse headers and return html
1088 function doHeadings( $text ) {
1089 wfProfileIn( __METHOD__
);
1090 for ( $i = 6; $i >= 1; --$i ) {
1091 $h = str_repeat( '=', $i );
1092 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1093 "<h$i>\\1</h$i>", $text );
1095 wfProfileOut( __METHOD__
);
1100 * Replace single quotes with HTML markup
1102 * @return string the altered text
1104 function doAllQuotes( $text ) {
1105 wfProfileIn( __METHOD__
);
1107 $lines = StringUtils
::explode( "\n", $text );
1108 foreach ( $lines as $line ) {
1109 $outtext .= $this->doQuotes( $line ) . "\n";
1111 $outtext = substr($outtext, 0,-1);
1112 wfProfileOut( __METHOD__
);
1117 * Helper function for doAllQuotes()
1119 public function doQuotes( $text ) {
1120 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1121 if ( count( $arr ) == 1 )
1125 # First, do some preliminary work. This may shift some apostrophes from
1126 # being mark-up to being text. It also counts the number of occurrences
1127 # of bold and italics mark-ups.
1131 foreach ( $arr as $r )
1133 if ( ( $i %
2 ) == 1 )
1135 # If there are ever four apostrophes, assume the first is supposed to
1136 # be text, and the remaining three constitute mark-up for bold text.
1137 if ( strlen( $arr[$i] ) == 4 )
1142 # If there are more than 5 apostrophes in a row, assume they're all
1143 # text except for the last 5.
1144 else if ( strlen( $arr[$i] ) > 5 )
1146 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1149 # Count the number of occurrences of bold and italics mark-ups.
1150 # We are not counting sequences of five apostrophes.
1151 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1152 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1153 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1158 # If there is an odd number of both bold and italics, it is likely
1159 # that one of the bold ones was meant to be an apostrophe followed
1160 # by italics. Which one we cannot know for certain, but it is more
1161 # likely to be one that has a single-letter word before it.
1162 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1165 $firstsingleletterword = -1;
1166 $firstmultiletterword = -1;
1168 foreach ( $arr as $r )
1170 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1172 $x1 = substr ($arr[$i-1], -1);
1173 $x2 = substr ($arr[$i-1], -2, 1);
1175 if ($firstspace == -1) $firstspace = $i;
1176 } else if ($x2 === ' ') {
1177 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1179 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1185 # If there is a single-letter word, use it!
1186 if ($firstsingleletterword > -1)
1188 $arr [ $firstsingleletterword ] = "''";
1189 $arr [ $firstsingleletterword-1 ] .= "'";
1191 # If not, but there's a multi-letter word, use that one.
1192 else if ($firstmultiletterword > -1)
1194 $arr [ $firstmultiletterword ] = "''";
1195 $arr [ $firstmultiletterword-1 ] .= "'";
1197 # ... otherwise use the first one that has neither.
1198 # (notice that it is possible for all three to be -1 if, for example,
1199 # there is only one pentuple-apostrophe in the line)
1200 else if ($firstspace > -1)
1202 $arr [ $firstspace ] = "''";
1203 $arr [ $firstspace-1 ] .= "'";
1207 # Now let's actually convert our apostrophic mush to HTML!
1212 foreach ($arr as $r)
1216 if ($state === 'both')
1223 if (strlen ($r) == 2)
1226 { $output .= '</i>'; $state = ''; }
1227 else if ($state === 'bi')
1228 { $output .= '</i>'; $state = 'b'; }
1229 else if ($state === 'ib')
1230 { $output .= '</b></i><b>'; $state = 'b'; }
1231 else if ($state === 'both')
1232 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1233 else # $state can be 'b' or ''
1234 { $output .= '<i>'; $state .= 'i'; }
1236 else if (strlen ($r) == 3)
1239 { $output .= '</b>'; $state = ''; }
1240 else if ($state === 'bi')
1241 { $output .= '</i></b><i>'; $state = 'i'; }
1242 else if ($state === 'ib')
1243 { $output .= '</b>'; $state = 'i'; }
1244 else if ($state === 'both')
1245 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1246 else # $state can be 'i' or ''
1247 { $output .= '<b>'; $state .= 'b'; }
1249 else if (strlen ($r) == 5)
1252 { $output .= '</b><i>'; $state = 'i'; }
1253 else if ($state === 'i')
1254 { $output .= '</i><b>'; $state = 'b'; }
1255 else if ($state === 'bi')
1256 { $output .= '</i></b>'; $state = ''; }
1257 else if ($state === 'ib')
1258 { $output .= '</b></i>'; $state = ''; }
1259 else if ($state === 'both')
1260 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1261 else # ($state == '')
1262 { $buffer = ''; $state = 'both'; }
1267 # Now close all remaining tags. Notice that the order is important.
1268 if ($state === 'b' ||
$state === 'ib')
1270 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1272 if ($state === 'bi')
1274 # There might be lonely ''''', so make sure we have a buffer
1275 if ($state === 'both' && $buffer)
1276 $output .= '<b><i>'.$buffer.'</i></b>';
1282 * Replace external links (REL)
1284 * Note: this is all very hackish and the order of execution matters a lot.
1285 * Make sure to run maintenance/parserTests.php if you change this code.
1289 function replaceExternalLinks( $text ) {
1291 wfProfileIn( __METHOD__
);
1293 $sk = $this->mOptions
->getSkin();
1295 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1296 $s = array_shift( $bits );
1299 while ( $i<count( $bits ) ) {
1301 $protocol = $bits[$i++
];
1302 $text = $bits[$i++
];
1303 $trail = $bits[$i++
];
1305 # The characters '<' and '>' (which were escaped by
1306 # removeHTMLtags()) should not be included in
1307 # URLs, per RFC 2396.
1309 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1310 $text = substr($url, $m2[0][1]) . ' ' . $text;
1311 $url = substr($url, 0, $m2[0][1]);
1314 # If the link text is an image URL, replace it with an <img> tag
1315 # This happened by accident in the original parser, but some people used it extensively
1316 $img = $this->maybeMakeExternalImage( $text );
1317 if ( $img !== false ) {
1323 # Set linktype for CSS - if URL==text, link is essentially free
1324 $linktype = ($text === $url) ?
'free' : 'text';
1326 # No link text, e.g. [http://domain.tld/some.link]
1327 if ( $text == '' ) {
1328 # Autonumber if allowed. See bug #5918
1329 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1330 $langObj = $this->getFunctionLang();
1331 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1332 $linktype = 'autonumber';
1334 # Otherwise just use the URL
1335 $text = htmlspecialchars( $url );
1339 # Have link text, e.g. [http://domain.tld/some.link text]s
1341 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1344 $text = $wgContLang->markNoConversion($text);
1346 $url = Sanitizer
::cleanUrl( $url );
1348 # Use the encoded URL
1349 # This means that users can paste URLs directly into the text
1350 # Funny characters like ö aren't valid in URLs anyway
1351 # This was changed in August 2004
1352 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1353 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1355 # Register link in the output object.
1356 # Replace unnecessary URL escape codes with the referenced character
1357 # This prevents spammers from hiding links from the filters
1358 $pasteurized = self
::replaceUnusualEscapes( $url );
1359 $this->mOutput
->addExternalLink( $pasteurized );
1362 wfProfileOut( __METHOD__
);
1367 * Get an associative array of additional HTML attributes appropriate for a
1368 * particular external link. This currently may include rel => nofollow
1369 * (depending on configuration, namespace, and the URL's domain) and/or a
1370 * target attribute (depending on configuration).
1372 * @param string $url Optional URL, to extract the domain from for rel =>
1373 * nofollow if appropriate
1374 * @return array Associative array of HTML attributes
1376 function getExternalLinkAttribs( $url = false ) {
1378 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1379 $ns = $this->mTitle
->getNamespace();
1380 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1381 $attribs['rel'] = 'nofollow';
1383 global $wgNoFollowDomainExceptions;
1384 if ( $wgNoFollowDomainExceptions ) {
1385 $bits = wfParseUrl( $url );
1386 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1387 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1388 if( substr( $bits['host'], -strlen( $domain ) )
1390 unset( $attribs['rel'] );
1397 if ( $this->mOptions
->getExternalLinkTarget() ) {
1398 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1405 * Replace unusual URL escape codes with their equivalent characters
1409 * @todo This can merge genuinely required bits in the path or query string,
1410 * breaking legit URLs. A proper fix would treat the various parts of
1411 * the URL differently; as a workaround, just use the output for
1412 * statistical records, not for actual linking/output.
1414 static function replaceUnusualEscapes( $url ) {
1415 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1416 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1420 * Callback function used in replaceUnusualEscapes().
1421 * Replaces unusual URL escape codes with their equivalent character
1425 private static function replaceUnusualEscapesCallback( $matches ) {
1426 $char = urldecode( $matches[0] );
1427 $ord = ord( $char );
1428 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1429 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1430 // No, shouldn't be escaped
1433 // Yes, leave it escaped
1439 * make an image if it's allowed, either through the global
1440 * option, through the exception, or through the on-wiki whitelist
1443 function maybeMakeExternalImage( $url ) {
1444 $sk = $this->mOptions
->getSkin();
1445 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1446 $imagesexception = !empty($imagesfrom);
1448 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1449 if( $imagesexception && is_array( $imagesfrom ) ) {
1450 $imagematch = false;
1451 foreach( $imagesfrom as $match ) {
1452 if( strpos( $url, $match ) === 0 ) {
1457 } elseif( $imagesexception ) {
1458 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1460 $imagematch = false;
1462 if ( $this->mOptions
->getAllowExternalImages()
1463 ||
( $imagesexception && $imagematch ) ) {
1464 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1466 $text = $sk->makeExternalImage( $url );
1469 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1470 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1471 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1472 foreach( $whitelist as $entry ) {
1473 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1474 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1476 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1477 # Image matches a whitelist entry
1478 $text = $sk->makeExternalImage( $url );
1487 * Process [[ ]] wikilinks
1488 * @return processed text
1492 function replaceInternalLinks( $s ) {
1493 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1498 * Process [[ ]] wikilinks (RIL)
1499 * @return LinkHolderArray
1503 function replaceInternalLinks2( &$s ) {
1506 wfProfileIn( __METHOD__
);
1508 wfProfileIn( __METHOD__
.'-setup' );
1509 static $tc = FALSE, $e1, $e1_img;
1510 # the % is needed to support urlencoded titles as well
1512 $tc = Title
::legalChars() . '#%';
1513 # Match a link having the form [[namespace:link|alternate]]trail
1514 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1515 # Match cases where there is no "]]", which might still be images
1516 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1519 $sk = $this->mOptions
->getSkin();
1520 $holders = new LinkHolderArray( $this );
1522 #split the entire text string on occurences of [[
1523 $a = StringUtils
::explode( '[[', ' ' . $s );
1524 #get the first element (all text up to first [[), and remove the space we added
1527 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1528 $s = substr( $s, 1 );
1530 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1532 if ( $useLinkPrefixExtension ) {
1533 # Match the end of a line for a word that's not followed by whitespace,
1534 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1535 $e2 = wfMsgForContent( 'linkprefix' );
1538 if( is_null( $this->mTitle
) ) {
1539 wfProfileOut( __METHOD__
.'-setup' );
1540 wfProfileOut( __METHOD__
);
1541 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1543 $nottalk = !$this->mTitle
->isTalkPage();
1545 if ( $useLinkPrefixExtension ) {
1547 if ( preg_match( $e2, $s, $m ) ) {
1548 $first_prefix = $m[2];
1550 $first_prefix = false;
1556 if($wgContLang->hasVariants()) {
1557 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1559 $selflink = array($this->mTitle
->getPrefixedText());
1561 $useSubpages = $this->areSubpagesAllowed();
1562 wfProfileOut( __METHOD__
.'-setup' );
1564 # Loop for each link
1565 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1566 # Check for excessive memory usage
1567 if ( $holders->isBig() ) {
1569 # Do the existence check, replace the link holders and clear the array
1570 $holders->replace( $s );
1574 if ( $useLinkPrefixExtension ) {
1575 wfProfileIn( __METHOD__
.'-prefixhandling' );
1576 if ( preg_match( $e2, $s, $m ) ) {
1584 $prefix = $first_prefix;
1585 $first_prefix = false;
1587 wfProfileOut( __METHOD__
.'-prefixhandling' );
1590 $might_be_img = false;
1592 wfProfileIn( __METHOD__
."-e1" );
1593 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1595 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1596 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1597 # the real problem is with the $e1 regex
1600 # Still some problems for cases where the ] is meant to be outside punctuation,
1601 # and no image is in sight. See bug 2095.
1604 substr( $m[3], 0, 1 ) === ']' &&
1605 strpos($text, '[') !== false
1608 $text .= ']'; # so that replaceExternalLinks($text) works later
1609 $m[3] = substr( $m[3], 1 );
1611 # fix up urlencoded title texts
1612 if( strpos( $m[1], '%' ) !== false ) {
1613 # Should anchors '#' also be rejected?
1614 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1617 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1618 $might_be_img = true;
1620 if ( strpos( $m[1], '%' ) !== false ) {
1621 $m[1] = urldecode($m[1]);
1624 } else { # Invalid form; output directly
1625 $s .= $prefix . '[[' . $line ;
1626 wfProfileOut( __METHOD__
."-e1" );
1629 wfProfileOut( __METHOD__
."-e1" );
1630 wfProfileIn( __METHOD__
."-misc" );
1632 # Don't allow internal links to pages containing
1633 # PROTO: where PROTO is a valid URL protocol; these
1634 # should be external links.
1635 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1636 $s .= $prefix . '[[' . $line ;
1637 wfProfileOut( __METHOD__
."-misc" );
1641 # Make subpage if necessary
1642 if ( $useSubpages ) {
1643 $link = $this->maybeDoSubpageLink( $m[1], $text );
1648 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1650 # Strip off leading ':'
1651 $link = substr( $link, 1 );
1654 wfProfileOut( __METHOD__
."-misc" );
1655 wfProfileIn( __METHOD__
."-title" );
1656 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1657 if ( $nt === null ) {
1658 $s .= $prefix . '[[' . $line;
1659 wfProfileOut( __METHOD__
."-title" );
1663 $ns = $nt->getNamespace();
1664 $iw = $nt->getInterWiki();
1665 wfProfileOut( __METHOD__
."-title" );
1667 if ( $might_be_img ) { # if this is actually an invalid link
1668 wfProfileIn( __METHOD__
."-might_be_img" );
1669 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1672 #look at the next 'line' to see if we can close it there
1674 $next_line = $a->current();
1675 if ( $next_line === false ||
$next_line === null ) {
1678 $m = explode( ']]', $next_line, 3 );
1679 if ( count( $m ) == 3 ) {
1680 # the first ]] closes the inner link, the second the image
1682 $text .= "[[{$m[0]}]]{$m[1]}";
1685 } elseif ( count( $m ) == 2 ) {
1686 #if there's exactly one ]] that's fine, we'll keep looking
1687 $text .= "[[{$m[0]}]]{$m[1]}";
1689 #if $next_line is invalid too, we need look no further
1690 $text .= '[[' . $next_line;
1695 # we couldn't find the end of this imageLink, so output it raw
1696 #but don't ignore what might be perfectly normal links in the text we've examined
1697 $holders->merge( $this->replaceInternalLinks2( $text ) );
1698 $s .= "{$prefix}[[$link|$text";
1699 # note: no $trail, because without an end, there *is* no trail
1700 wfProfileOut( __METHOD__
."-might_be_img" );
1703 } else { #it's not an image, so output it raw
1704 $s .= "{$prefix}[[$link|$text";
1705 # note: no $trail, because without an end, there *is* no trail
1706 wfProfileOut( __METHOD__
."-might_be_img" );
1709 wfProfileOut( __METHOD__
."-might_be_img" );
1712 $wasblank = ( $text == '' );
1713 if ( $wasblank ) $text = $link;
1715 # Link not escaped by : , create the various objects
1719 wfProfileIn( __METHOD__
."-interwiki" );
1720 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1721 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1722 $s = rtrim($s . $prefix);
1723 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1724 wfProfileOut( __METHOD__
."-interwiki" );
1727 wfProfileOut( __METHOD__
."-interwiki" );
1729 if ( $ns == NS_FILE
) {
1730 wfProfileIn( __METHOD__
."-image" );
1731 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1733 # if no parameters were passed, $text
1734 # becomes something like "File:Foo.png",
1735 # which we don't want to pass on to the
1739 # recursively parse links inside the image caption
1740 # actually, this will parse them in any other parameters, too,
1741 # but it might be hard to fix that, and it doesn't matter ATM
1742 $text = $this->replaceExternalLinks($text);
1743 $holders->merge( $this->replaceInternalLinks2( $text ) );
1745 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1746 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1748 $s .= $prefix . $trail;
1750 $this->mOutput
->addImage( $nt->getDBkey() );
1751 wfProfileOut( __METHOD__
."-image" );
1756 if ( $ns == NS_CATEGORY
) {
1757 wfProfileIn( __METHOD__
."-category" );
1758 $s = rtrim($s . "\n"); # bug 87
1761 $sortkey = $this->getDefaultSort();
1765 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1766 $sortkey = str_replace( "\n", '', $sortkey );
1767 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1768 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1771 * Strip the whitespace Category links produce, see bug 87
1772 * @todo We might want to use trim($tmp, "\n") here.
1774 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1776 wfProfileOut( __METHOD__
."-category" );
1781 # Self-link checking
1782 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1783 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1784 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1789 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1790 # FIXME: Should do batch file existence checks, see comment below
1791 if( $ns == NS_MEDIA
) {
1792 wfProfileIn( __METHOD__
."-media" );
1793 # Give extensions a chance to select the file revision for us
1794 $skip = $time = false;
1795 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1797 $link = $sk->link( $nt );
1799 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1801 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1802 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1803 $this->mOutput
->addImage( $nt->getDBkey() );
1804 wfProfileOut( __METHOD__
."-media" );
1808 wfProfileIn( __METHOD__
."-always_known" );
1809 # Some titles, such as valid special pages or files in foreign repos, should
1810 # be shown as bluelinks even though they're not included in the page table
1812 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1813 # batch file existence checks for NS_FILE and NS_MEDIA
1814 if( $iw == '' && $nt->isAlwaysKnown() ) {
1815 $this->mOutput
->addLink( $nt );
1816 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1818 # Links will be added to the output link list after checking
1819 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1821 wfProfileOut( __METHOD__
."-always_known" );
1823 wfProfileOut( __METHOD__
);
1828 * Make a link placeholder. The text returned can be later resolved to a real link with
1829 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1830 * parsing of interwiki links, and secondly to allow all existence checks and
1831 * article length checks (for stub links) to be bundled into a single query.
1835 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1836 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1840 * Render a forced-blue link inline; protect against double expansion of
1841 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1842 * Since this little disaster has to split off the trail text to avoid
1843 * breaking URLs in the following text without breaking trails on the
1844 * wiki links, it's been made into a horrible function.
1847 * @param string $text
1848 * @param string $query
1849 * @param string $trail
1850 * @param string $prefix
1851 * @return string HTML-wikitext mix oh yuck
1853 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1854 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1855 $sk = $this->mOptions
->getSkin();
1856 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1857 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1858 return $this->armorLinks( $link ) . $trail;
1862 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1863 * going to go through further parsing steps before inline URL expansion.
1865 * Not needed quite as much as it used to be since free links are a bit
1866 * more sensible these days. But bracketed links are still an issue.
1868 * @param string more-or-less HTML
1869 * @return string less-or-more HTML with NOPARSE bits
1871 function armorLinks( $text ) {
1872 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1873 "{$this->mUniqPrefix}NOPARSE$1", $text );
1877 * Return true if subpage links should be expanded on this page.
1880 function areSubpagesAllowed() {
1881 # Some namespaces don't allow subpages
1882 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1886 * Handle link to subpage if necessary
1887 * @param string $target the source of the link
1888 * @param string &$text the link text, modified as necessary
1889 * @return string the full name of the link
1892 function maybeDoSubpageLink($target, &$text) {
1893 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1897 * Used by doBlockLevels()
1900 /* private */ function closeParagraph() {
1902 if ( $this->mLastSection
!= '' ) {
1903 $result = '</' . $this->mLastSection
. ">\n";
1905 $this->mInPre
= false;
1906 $this->mLastSection
= '';
1909 # getCommon() returns the length of the longest common substring
1910 # of both arguments, starting at the beginning of both.
1912 /* private */ function getCommon( $st1, $st2 ) {
1913 $fl = strlen( $st1 );
1914 $shorter = strlen( $st2 );
1915 if ( $fl < $shorter ) { $shorter = $fl; }
1917 for ( $i = 0; $i < $shorter; ++
$i ) {
1918 if ( $st1{$i} != $st2{$i} ) { break; }
1922 # These next three functions open, continue, and close the list
1923 # element appropriate to the prefix character passed into them.
1925 /* private */ function openList( $char ) {
1926 $result = $this->closeParagraph();
1928 if ( '*' === $char ) { $result .= '<ul><li>'; }
1929 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1930 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1931 elseif ( ';' === $char ) {
1932 $result .= '<dl><dt>';
1933 $this->mDTopen
= true;
1935 else { $result = '<!-- ERR 1 -->'; }
1940 /* private */ function nextItem( $char ) {
1941 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1942 elseif ( ':' === $char ||
';' === $char ) {
1944 if ( $this->mDTopen
) { $close = '</dt>'; }
1945 if ( ';' === $char ) {
1946 $this->mDTopen
= true;
1947 return $close . '<dt>';
1949 $this->mDTopen
= false;
1950 return $close . '<dd>';
1953 return '<!-- ERR 2 -->';
1956 /* private */ function closeList( $char ) {
1957 if ( '*' === $char ) { $text = '</li></ul>'; }
1958 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1959 elseif ( ':' === $char ) {
1960 if ( $this->mDTopen
) {
1961 $this->mDTopen
= false;
1962 $text = '</dt></dl>';
1964 $text = '</dd></dl>';
1967 else { return '<!-- ERR 3 -->'; }
1973 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1975 * @param $linestart bool whether or not this is at the start of a line.
1977 * @return string the lists rendered as HTML
1979 function doBlockLevels( $text, $linestart ) {
1980 wfProfileIn( __METHOD__
);
1982 # Parsing through the text line by line. The main thing
1983 # happening here is handling of block-level elements p, pre,
1984 # and making lists from lines starting with * # : etc.
1986 $textLines = StringUtils
::explode( "\n", $text );
1988 $lastPrefix = $output = '';
1989 $this->mDTopen
= $inBlockElem = false;
1991 $paragraphStack = false;
1993 foreach ( $textLines as $oLine ) {
1995 if ( !$linestart ) {
2005 $lastPrefixLength = strlen( $lastPrefix );
2006 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2007 $preOpenMatch = preg_match('/<pre/i', $oLine );
2008 // If not in a <pre> element, scan for and figure out what prefixes are there.
2009 if ( !$this->mInPre
) {
2010 # Multiple prefixes may abut each other for nested lists.
2011 $prefixLength = strspn( $oLine, '*#:;' );
2012 $prefix = substr( $oLine, 0, $prefixLength );
2015 // ; and : are both from definition-lists, so they're equivalent
2016 // for the purposes of determining whether or not we need to open/close
2018 $prefix2 = str_replace( ';', ':', $prefix );
2019 $t = substr( $oLine, $prefixLength );
2020 $this->mInPre
= (bool)$preOpenMatch;
2022 # Don't interpret any other prefixes in preformatted text
2024 $prefix = $prefix2 = '';
2029 if( $prefixLength && $lastPrefix === $prefix2 ) {
2030 # Same as the last item, so no need to deal with nesting or opening stuff
2031 $output .= $this->nextItem( substr( $prefix, -1 ) );
2032 $paragraphStack = false;
2034 if ( substr( $prefix, -1 ) === ';') {
2035 # The one nasty exception: definition lists work like this:
2036 # ; title : definition text
2037 # So we check for : in the remainder text to split up the
2038 # title and definition, without b0rking links.
2040 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2042 $output .= $term . $this->nextItem( ':' );
2045 } elseif( $prefixLength ||
$lastPrefixLength ) {
2046 // We need to open or close prefixes, or both.
2048 # Either open or close a level...
2049 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2050 $paragraphStack = false;
2052 // Close all the prefixes which aren't shared.
2053 while( $commonPrefixLength < $lastPrefixLength ) {
2054 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2055 --$lastPrefixLength;
2058 // Continue the current prefix if appropriate.
2059 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2060 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2063 // Open prefixes where appropriate.
2064 while ( $prefixLength > $commonPrefixLength ) {
2065 $char = substr( $prefix, $commonPrefixLength, 1 );
2066 $output .= $this->openList( $char );
2068 if ( ';' === $char ) {
2069 # FIXME: This is dupe of code above
2070 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2072 $output .= $term . $this->nextItem( ':' );
2075 ++
$commonPrefixLength;
2077 $lastPrefix = $prefix2;
2080 // If we have no prefixes, go to paragraph mode.
2081 if( 0 == $prefixLength ) {
2082 wfProfileIn( __METHOD__
."-paragraph" );
2083 # No prefix (not in list)--go to paragraph mode
2084 // XXX: use a stack for nestable elements like span, table and div
2085 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2086 $closematch = preg_match(
2087 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2088 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2089 if ( $openmatch or $closematch ) {
2090 $paragraphStack = false;
2091 #Â TODO bug 5718: paragraph closed
2092 $output .= $this->closeParagraph();
2093 if ( $preOpenMatch and !$preCloseMatch ) {
2094 $this->mInPre
= true;
2096 if ( $closematch ) {
2097 $inBlockElem = false;
2099 $inBlockElem = true;
2101 } else if ( !$inBlockElem && !$this->mInPre
) {
2102 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2104 if ($this->mLastSection
!== 'pre') {
2105 $paragraphStack = false;
2106 $output .= $this->closeParagraph().'<pre>';
2107 $this->mLastSection
= 'pre';
2109 $t = substr( $t, 1 );
2112 if ( trim($t) == '' ) {
2113 if ( $paragraphStack ) {
2114 $output .= $paragraphStack.'<br />';
2115 $paragraphStack = false;
2116 $this->mLastSection
= 'p';
2118 if ($this->mLastSection
!== 'p' ) {
2119 $output .= $this->closeParagraph();
2120 $this->mLastSection
= '';
2121 $paragraphStack = '<p>';
2123 $paragraphStack = '</p><p>';
2127 if ( $paragraphStack ) {
2128 $output .= $paragraphStack;
2129 $paragraphStack = false;
2130 $this->mLastSection
= 'p';
2131 } else if ($this->mLastSection
!== 'p') {
2132 $output .= $this->closeParagraph().'<p>';
2133 $this->mLastSection
= 'p';
2138 wfProfileOut( __METHOD__
."-paragraph" );
2140 // somewhere above we forget to get out of pre block (bug 785)
2141 if($preCloseMatch && $this->mInPre
) {
2142 $this->mInPre
= false;
2144 if ($paragraphStack === false) {
2148 while ( $prefixLength ) {
2149 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2152 if ( $this->mLastSection
!= '' ) {
2153 $output .= '</' . $this->mLastSection
. '>';
2154 $this->mLastSection
= '';
2157 wfProfileOut( __METHOD__
);
2162 * Split up a string on ':', ignoring any occurences inside tags
2163 * to prevent illegal overlapping.
2164 * @param string $str the string to split
2165 * @param string &$before set to everything before the ':'
2166 * @param string &$after set to everything after the ':'
2167 * return string the position of the ':', or false if none found
2169 function findColonNoLinks($str, &$before, &$after) {
2170 wfProfileIn( __METHOD__
);
2172 $pos = strpos( $str, ':' );
2173 if( $pos === false ) {
2175 wfProfileOut( __METHOD__
);
2179 $lt = strpos( $str, '<' );
2180 if( $lt === false ||
$lt > $pos ) {
2181 // Easy; no tag nesting to worry about
2182 $before = substr( $str, 0, $pos );
2183 $after = substr( $str, $pos+
1 );
2184 wfProfileOut( __METHOD__
);
2188 // Ugly state machine to walk through avoiding tags.
2189 $state = self
::COLON_STATE_TEXT
;
2191 $len = strlen( $str );
2192 for( $i = 0; $i < $len; $i++
) {
2196 // (Using the number is a performance hack for common cases)
2197 case 0: // self::COLON_STATE_TEXT:
2200 // Could be either a <start> tag or an </end> tag
2201 $state = self
::COLON_STATE_TAGSTART
;
2206 $before = substr( $str, 0, $i );
2207 $after = substr( $str, $i +
1 );
2208 wfProfileOut( __METHOD__
);
2211 // Embedded in a tag; don't break it.
2214 // Skip ahead looking for something interesting
2215 $colon = strpos( $str, ':', $i );
2216 if( $colon === false ) {
2217 // Nothing else interesting
2218 wfProfileOut( __METHOD__
);
2221 $lt = strpos( $str, '<', $i );
2222 if( $stack === 0 ) {
2223 if( $lt === false ||
$colon < $lt ) {
2225 $before = substr( $str, 0, $colon );
2226 $after = substr( $str, $colon +
1 );
2227 wfProfileOut( __METHOD__
);
2231 if( $lt === false ) {
2232 // Nothing else interesting to find; abort!
2233 // We're nested, but there's no close tags left. Abort!
2236 // Skip ahead to next tag start
2238 $state = self
::COLON_STATE_TAGSTART
;
2241 case 1: // self::COLON_STATE_TAG:
2246 $state = self
::COLON_STATE_TEXT
;
2249 // Slash may be followed by >?
2250 $state = self
::COLON_STATE_TAGSLASH
;
2256 case 2: // self::COLON_STATE_TAGSTART:
2259 $state = self
::COLON_STATE_CLOSETAG
;
2262 $state = self
::COLON_STATE_COMMENT
;
2265 // Illegal early close? This shouldn't happen D:
2266 $state = self
::COLON_STATE_TEXT
;
2269 $state = self
::COLON_STATE_TAG
;
2272 case 3: // self::COLON_STATE_CLOSETAG:
2277 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2278 wfProfileOut( __METHOD__
);
2281 $state = self
::COLON_STATE_TEXT
;
2284 case self
::COLON_STATE_TAGSLASH
:
2286 // Yes, a self-closed tag <blah/>
2287 $state = self
::COLON_STATE_TEXT
;
2289 // Probably we're jumping the gun, and this is an attribute
2290 $state = self
::COLON_STATE_TAG
;
2293 case 5: // self::COLON_STATE_COMMENT:
2295 $state = self
::COLON_STATE_COMMENTDASH
;
2298 case self
::COLON_STATE_COMMENTDASH
:
2300 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2302 $state = self
::COLON_STATE_COMMENT
;
2305 case self
::COLON_STATE_COMMENTDASHDASH
:
2307 $state = self
::COLON_STATE_TEXT
;
2309 $state = self
::COLON_STATE_COMMENT
;
2313 throw new MWException( "State machine error in " . __METHOD__
);
2317 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2320 wfProfileOut( __METHOD__
);
2325 * Return value of a magic variable (like PAGENAME)
2329 function getVariableValue( $index, $frame=false ) {
2330 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2331 global $wgScriptPath, $wgStylePath;
2334 * Some of these require message or data lookups and can be
2335 * expensive to check many times.
2337 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2338 if ( isset( $this->mVarCache
[$index] ) ) {
2339 return $this->mVarCache
[$index];
2343 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2344 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2347 global $wgLocaltimezone;
2348 if ( isset( $wgLocaltimezone ) ) {
2349 $oldtz = date_default_timezone_get();
2350 date_default_timezone_set( $wgLocaltimezone );
2353 $localTimestamp = date( 'YmdHis', $ts );
2354 $localMonth = date( 'm', $ts );
2355 $localMonth1 = date( 'n', $ts );
2356 $localMonthName = date( 'n', $ts );
2357 $localDay = date( 'j', $ts );
2358 $localDay2 = date( 'd', $ts );
2359 $localDayOfWeek = date( 'w', $ts );
2360 $localWeek = date( 'W', $ts );
2361 $localYear = date( 'Y', $ts );
2362 $localHour = date( 'H', $ts );
2363 if ( isset( $wgLocaltimezone ) ) {
2364 date_default_timezone_set( $oldtz );
2368 case 'currentmonth':
2369 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2371 case 'currentmonth1':
2372 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2374 case 'currentmonthname':
2375 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2377 case 'currentmonthnamegen':
2378 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2380 case 'currentmonthabbrev':
2381 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2384 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2387 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2390 $value = $wgContLang->formatNum( $localMonth );
2393 $value = $wgContLang->formatNum( $localMonth1 );
2395 case 'localmonthname':
2396 $value = $wgContLang->getMonthName( $localMonthName );
2398 case 'localmonthnamegen':
2399 $value = $wgContLang->getMonthNameGen( $localMonthName );
2401 case 'localmonthabbrev':
2402 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2405 $value = $wgContLang->formatNum( $localDay );
2408 $value = $wgContLang->formatNum( $localDay2 );
2411 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2414 $value = $this->mTitle
->getPartialURL();
2416 case 'fullpagename':
2417 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2419 case 'fullpagenamee':
2420 $value = $this->mTitle
->getPrefixedURL();
2423 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2425 case 'subpagenamee':
2426 $value = $this->mTitle
->getSubpageUrlForm();
2428 case 'basepagename':
2429 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2431 case 'basepagenamee':
2432 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2434 case 'talkpagename':
2435 if( $this->mTitle
->canTalk() ) {
2436 $talkPage = $this->mTitle
->getTalkPage();
2437 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2442 case 'talkpagenamee':
2443 if( $this->mTitle
->canTalk() ) {
2444 $talkPage = $this->mTitle
->getTalkPage();
2445 $value = $talkPage->getPrefixedUrl();
2450 case 'subjectpagename':
2451 $subjPage = $this->mTitle
->getSubjectPage();
2452 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2454 case 'subjectpagenamee':
2455 $subjPage = $this->mTitle
->getSubjectPage();
2456 $value = $subjPage->getPrefixedUrl();
2459 // Let the edit saving system know we should parse the page
2460 // *after* a revision ID has been assigned.
2461 $this->mOutput
->setFlag( 'vary-revision' );
2462 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2463 $value = $this->mRevisionId
;
2466 // Let the edit saving system know we should parse the page
2467 // *after* a revision ID has been assigned. This is for null edits.
2468 $this->mOutput
->setFlag( 'vary-revision' );
2469 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2470 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2472 case 'revisionday2':
2473 // Let the edit saving system know we should parse the page
2474 // *after* a revision ID has been assigned. This is for null edits.
2475 $this->mOutput
->setFlag( 'vary-revision' );
2476 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2477 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2479 case 'revisionmonth':
2480 // Let the edit saving system know we should parse the page
2481 // *after* a revision ID has been assigned. This is for null edits.
2482 $this->mOutput
->setFlag( 'vary-revision' );
2483 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2484 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2486 case 'revisionyear':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput
->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2491 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2493 case 'revisiontimestamp':
2494 // Let the edit saving system know we should parse the page
2495 // *after* a revision ID has been assigned. This is for null edits.
2496 $this->mOutput
->setFlag( 'vary-revision' );
2497 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2498 $value = $this->getRevisionTimestamp();
2500 case 'revisionuser':
2501 // Let the edit saving system know we should parse the page
2502 // *after* a revision ID has been assigned. This is for null edits.
2503 $this->mOutput
->setFlag( 'vary-revision' );
2504 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2505 $value = $this->getRevisionUser();
2508 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2511 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2514 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2517 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2519 case 'subjectspace':
2520 $value = $this->mTitle
->getSubjectNsText();
2522 case 'subjectspacee':
2523 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2525 case 'currentdayname':
2526 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2529 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2532 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2535 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2538 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2539 // int to remove the padding
2540 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2543 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2545 case 'localdayname':
2546 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2549 $value = $wgContLang->formatNum( $localYear, true );
2552 $value = $wgContLang->time( $localTimestamp, false, false );
2555 $value = $wgContLang->formatNum( $localHour, true );
2558 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2559 // int to remove the padding
2560 $value = $wgContLang->formatNum( (int)$localWeek );
2563 $value = $wgContLang->formatNum( $localDayOfWeek );
2565 case 'numberofarticles':
2566 $value = $wgContLang->formatNum( SiteStats
::articles() );
2568 case 'numberoffiles':
2569 $value = $wgContLang->formatNum( SiteStats
::images() );
2571 case 'numberofusers':
2572 $value = $wgContLang->formatNum( SiteStats
::users() );
2574 case 'numberofactiveusers':
2575 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2577 case 'numberofpages':
2578 $value = $wgContLang->formatNum( SiteStats
::pages() );
2580 case 'numberofadmins':
2581 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2583 case 'numberofedits':
2584 $value = $wgContLang->formatNum( SiteStats
::edits() );
2586 case 'numberofviews':
2587 $value = $wgContLang->formatNum( SiteStats
::views() );
2589 case 'currenttimestamp':
2590 $value = wfTimestamp( TS_MW
, $ts );
2592 case 'localtimestamp':
2593 $value = $localTimestamp;
2595 case 'currentversion':
2596 $value = SpecialVersion
::getVersion();
2603 return $wgServerName;
2605 return $wgScriptPath;
2607 return $wgStylePath;
2608 case 'directionmark':
2609 return $wgContLang->getDirMark();
2610 case 'contentlanguage':
2611 global $wgContLanguageCode;
2612 return $wgContLanguageCode;
2615 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2622 $this->mVarCache
[$index] = $value;
2628 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2632 function initialiseVariables() {
2633 wfProfileIn( __METHOD__
);
2634 $variableIDs = MagicWord
::getVariableIDs();
2635 $substIDs = MagicWord
::getSubstIDs();
2637 $this->mVariables
= new MagicWordArray( $variableIDs );
2638 $this->mSubsts
= new MagicWordArray( $substIDs );
2639 wfProfileOut( __METHOD__
);
2643 * Preprocess some wikitext and return the document tree.
2644 * This is the ghost of replace_variables().
2646 * @param string $text The text to parse
2647 * @param integer flags Bitwise combination of:
2648 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2649 * included. Default is to assume a direct page view.
2651 * The generated DOM tree must depend only on the input text and the flags.
2652 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2654 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2655 * change in the DOM tree for a given text, must be passed through the section identifier
2656 * in the section edit link and thus back to extractSections().
2658 * The output of this function is currently only cached in process memory, but a persistent
2659 * cache may be implemented at a later date which takes further advantage of these strict
2660 * dependency requirements.
2664 function preprocessToDom ( $text, $flags = 0 ) {
2665 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2670 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2672 public static function splitWhitespace( $s ) {
2673 $ltrimmed = ltrim( $s );
2674 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2675 $trimmed = rtrim( $ltrimmed );
2676 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2678 $w2 = substr( $ltrimmed, -$diff );
2682 return array( $w1, $trimmed, $w2 );
2686 * Replace magic variables, templates, and template arguments
2687 * with the appropriate text. Templates are substituted recursively,
2688 * taking care to avoid infinite loops.
2690 * Note that the substitution depends on value of $mOutputType:
2691 * self::OT_WIKI: only {{subst:}} templates
2692 * self::OT_PREPROCESS: templates but not extension tags
2693 * self::OT_HTML: all templates and extension tags
2695 * @param string $tex The text to transform
2696 * @param PPFrame $frame Object describing the arguments passed to the template.
2697 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2698 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2699 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2702 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2703 # Is there any text? Also, Prevent too big inclusions!
2704 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2707 wfProfileIn( __METHOD__
);
2709 if ( $frame === false ) {
2710 $frame = $this->getPreprocessor()->newFrame();
2711 } elseif ( !( $frame instanceof PPFrame
) ) {
2712 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2713 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2716 $dom = $this->preprocessToDom( $text );
2717 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2718 $text = $frame->expand( $dom, $flags );
2720 wfProfileOut( __METHOD__
);
2724 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2725 static function createAssocArgs( $args ) {
2726 $assocArgs = array();
2728 foreach( $args as $arg ) {
2729 $eqpos = strpos( $arg, '=' );
2730 if ( $eqpos === false ) {
2731 $assocArgs[$index++
] = $arg;
2733 $name = trim( substr( $arg, 0, $eqpos ) );
2734 $value = trim( substr( $arg, $eqpos+
1 ) );
2735 if ( $value === false ) {
2738 if ( $name !== false ) {
2739 $assocArgs[$name] = $value;
2748 * Warn the user when a parser limitation is reached
2749 * Will warn at most once the user per limitation type
2751 * @param string $limitationType, should be one of:
2752 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2753 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2754 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2755 * @params int $current, $max When an explicit limit has been
2756 * exceeded, provide the values (optional)
2758 function limitationWarn( $limitationType, $current=null, $max=null) {
2759 //does no harm if $current and $max are present but are unnecessary for the message
2760 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2761 $this->mOutput
->addWarning( $warning );
2762 $this->addTrackingCategory( "$limitationType-category" );
2766 * Return the text of a template, after recursively
2767 * replacing any variables or templates within the template.
2769 * @param array $piece The parts of the template
2770 * $piece['title']: the title, i.e. the part before the |
2771 * $piece['parts']: the parameter array
2772 * $piece['lineStart']: whether the brace was at the start of a line
2773 * @param PPFrame The current frame, contains template arguments
2774 * @return string the text of the template
2777 function braceSubstitution( $piece, $frame ) {
2778 global $wgContLang, $wgNonincludableNamespaces;
2779 wfProfileIn( __METHOD__
);
2780 wfProfileIn( __METHOD__
.'-setup' );
2783 $found = false; # $text has been filled
2784 $nowiki = false; # wiki markup in $text should be escaped
2785 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2786 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2787 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2788 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2790 # Title object, where $text came from
2793 # $part1 is the bit before the first |, and must contain only title characters.
2794 # Various prefixes will be stripped from it later.
2795 $titleWithSpaces = $frame->expand( $piece['title'] );
2796 $part1 = trim( $titleWithSpaces );
2799 # Original title text preserved for various purposes
2800 $originalTitle = $part1;
2802 # $args is a list of argument nodes, starting from index 0, not including $part1
2803 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2804 wfProfileOut( __METHOD__
.'-setup' );
2807 wfProfileIn( __METHOD__
.'-modifiers' );
2810 $substMatch = $this->mSubsts
->matchStartAndRemove( $part1 );
2812 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2813 # Whether to include depends also on whether we are in the pre-save-transform
2815 # safesubst || (subst && PST) || (false && !PST) => transclude (skip the if)
2816 # (false && PST) || (subst && !PST) => return input (handled by if)
2817 if ( $substMatch != 'safesubst' && ($substMatch == 'subst' xor $this->ot
['wiki']) ) {
2818 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2825 if ( !$found && $args->getLength() == 0 ) {
2826 $id = $this->mVariables
->matchStartToEnd( $part1 );
2827 if ( $id !== false ) {
2828 $text = $this->getVariableValue( $id, $frame );
2829 if (MagicWord
::getCacheTTL($id)>-1)
2830 $this->mOutput
->mContainsOldMagic
= true;
2835 # MSG, MSGNW and RAW
2838 $mwMsgnw = MagicWord
::get( 'msgnw' );
2839 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2842 # Remove obsolete MSG:
2843 $mwMsg = MagicWord
::get( 'msg' );
2844 $mwMsg->matchStartAndRemove( $part1 );
2848 $mwRaw = MagicWord
::get( 'raw' );
2849 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2850 $forceRawInterwiki = true;
2853 wfProfileOut( __METHOD__
.'-modifiers' );
2857 wfProfileIn( __METHOD__
. '-pfunc' );
2859 $colonPos = strpos( $part1, ':' );
2860 if ( $colonPos !== false ) {
2861 # Case sensitive functions
2862 $function = substr( $part1, 0, $colonPos );
2863 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2864 $function = $this->mFunctionSynonyms
[1][$function];
2866 # Case insensitive functions
2867 $function = $wgContLang->lc( $function );
2868 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2869 $function = $this->mFunctionSynonyms
[0][$function];
2875 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2876 $initialArgs = array( &$this );
2877 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2878 if ( $flags & SFH_OBJECT_ARGS
) {
2879 # Add a frame parameter, and pass the arguments as an array
2880 $allArgs = $initialArgs;
2881 $allArgs[] = $frame;
2882 for ( $i = 0; $i < $args->getLength(); $i++
) {
2883 $funcArgs[] = $args->item( $i );
2885 $allArgs[] = $funcArgs;
2887 # Convert arguments to plain text
2888 for ( $i = 0; $i < $args->getLength(); $i++
) {
2889 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2891 $allArgs = array_merge( $initialArgs, $funcArgs );
2894 # Workaround for PHP bug 35229 and similar
2895 if ( !is_callable( $callback ) ) {
2896 wfProfileOut( __METHOD__
. '-pfunc' );
2897 wfProfileOut( __METHOD__
);
2898 throw new MWException( "Tag hook for $function is not callable\n" );
2900 $result = call_user_func_array( $callback, $allArgs );
2903 $preprocessFlags = 0;
2905 if ( is_array( $result ) ) {
2906 if ( isset( $result[0] ) ) {
2908 unset( $result[0] );
2911 // Extract flags into the local scope
2912 // This allows callers to set flags such as nowiki, found, etc.
2918 $text = $this->preprocessToDom( $text, $preprocessFlags );
2923 wfProfileOut( __METHOD__
. '-pfunc' );
2926 # Finish mangling title and then check for loops.
2927 # Set $title to a Title object and $titleText to the PDBK
2930 # Split the title into page and subpage
2932 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2933 if ($subpage !== '') {
2934 $ns = $this->mTitle
->getNamespace();
2936 $title = Title
::newFromText( $part1, $ns );
2938 $titleText = $title->getPrefixedText();
2939 # Check for language variants if the template is not found
2940 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2941 $wgContLang->findVariantLink( $part1, $title, true );
2943 # Do recursion depth check
2944 $limit = $this->mOptions
->getMaxTemplateDepth();
2945 if ( $frame->depth
>= $limit ) {
2947 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2952 # Load from database
2953 if ( !$found && $title ) {
2954 wfProfileIn( __METHOD__
. '-loadtpl' );
2955 if ( !$title->isExternal() ) {
2956 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2957 $text = SpecialPage
::capturePath( $title );
2958 if ( is_string( $text ) ) {
2961 $this->disableCache();
2963 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2964 $found = false; //access denied
2965 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2967 list( $text, $title ) = $this->getTemplateDom( $title );
2968 if ( $text !== false ) {
2974 # If the title is valid but undisplayable, make a link to it
2975 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2976 $text = "[[:$titleText]]";
2979 } elseif ( $title->isTrans() ) {
2980 // Interwiki transclusion
2981 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2982 $text = $this->interwikiTransclude( $title, 'render' );
2985 $text = $this->interwikiTransclude( $title, 'raw' );
2986 // Preprocess it like a template
2987 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2993 # Do infinite loop check
2994 # This has to be done after redirect resolution to avoid infinite loops via redirects
2995 if ( !$frame->loopCheck( $title ) ) {
2997 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2998 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3000 wfProfileOut( __METHOD__
. '-loadtpl' );
3003 # If we haven't found text to substitute by now, we're done
3004 # Recover the source wikitext and return it
3006 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3007 wfProfileOut( __METHOD__
);
3008 return array( 'object' => $text );
3011 # Expand DOM-style return values in a child frame
3012 if ( $isChildObj ) {
3013 # Clean up argument array
3014 $newFrame = $frame->newChild( $args, $title );
3017 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3018 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3019 # Expansion is eligible for the empty-frame cache
3020 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3021 $text = $this->mTplExpandCache
[$titleText];
3023 $text = $newFrame->expand( $text );
3024 $this->mTplExpandCache
[$titleText] = $text;
3027 # Uncached expansion
3028 $text = $newFrame->expand( $text );
3031 if ( $isLocalObj && $nowiki ) {
3032 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3033 $isLocalObj = false;
3036 # Replace raw HTML by a placeholder
3037 # Add a blank line preceding, to prevent it from mucking up
3038 # immediately preceding headings
3040 $text = "\n\n" . $this->insertStripItem( $text );
3042 # Escape nowiki-style return values
3043 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3044 $text = wfEscapeWikiText( $text );
3046 # Bug 529: if the template begins with a table or block-level
3047 # element, it should be treated as beginning a new line.
3048 # This behaviour is somewhat controversial.
3049 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3050 $text = "\n" . $text;
3053 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3054 # Error, oversize inclusion
3055 $text = "[[$originalTitle]]" .
3056 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3057 $this->limitationWarn( 'post-expand-template-inclusion' );
3060 if ( $isLocalObj ) {
3061 $ret = array( 'object' => $text );
3063 $ret = array( 'text' => $text );
3066 wfProfileOut( __METHOD__
);
3071 * Get the semi-parsed DOM representation of a template with a given title,
3072 * and its redirect destination title. Cached.
3074 function getTemplateDom( $title ) {
3075 $cacheTitle = $title;
3076 $titleText = $title->getPrefixedDBkey();
3078 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3079 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3080 $title = Title
::makeTitle( $ns, $dbk );
3081 $titleText = $title->getPrefixedDBkey();
3083 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3084 return array( $this->mTplDomCache
[$titleText], $title );
3087 // Cache miss, go to the database
3088 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3090 if ( $text === false ) {
3091 $this->mTplDomCache
[$titleText] = false;
3092 return array( false, $title );
3095 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3096 $this->mTplDomCache
[ $titleText ] = $dom;
3098 if (! $title->equals($cacheTitle)) {
3099 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3100 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3103 return array( $dom, $title );
3107 * Fetch the unparsed text of a template and register a reference to it.
3109 function fetchTemplateAndTitle( $title ) {
3110 $templateCb = $this->mOptions
->getTemplateCallback();
3111 $stuff = call_user_func( $templateCb, $title, $this );
3112 $text = $stuff['text'];
3113 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3114 if ( isset( $stuff['deps'] ) ) {
3115 foreach ( $stuff['deps'] as $dep ) {
3116 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3119 return array($text,$finalTitle);
3122 function fetchTemplate( $title ) {
3123 $rv = $this->fetchTemplateAndTitle($title);
3128 * Static function to get a template
3129 * Can be overridden via ParserOptions::setTemplateCallback().
3131 static function statelessFetchTemplate( $title, $parser=false ) {
3132 $text = $skip = false;
3133 $finalTitle = $title;
3136 // Loop to fetch the article, with up to 1 redirect
3137 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3138 # Give extensions a chance to select the revision instead
3139 $id = false; // Assume current
3140 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3146 'page_id' => $title->getArticleID(),
3150 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3151 $rev_id = $rev ?
$rev->getId() : 0;
3152 // If there is no current revision, there is no page
3153 if( $id === false && !$rev ) {
3154 $linkCache = LinkCache
::singleton();
3155 $linkCache->addBadLinkObj( $title );
3160 'page_id' => $title->getArticleID(),
3161 'rev_id' => $rev_id );
3164 $text = $rev->getText();
3165 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3167 $message = $wgContLang->lcfirst( $title->getText() );
3168 $text = wfMsgForContentNoTrans( $message );
3169 if( wfEmptyMsg( $message, $text ) ) {
3176 if ( $text === false ) {
3180 $finalTitle = $title;
3181 $title = Title
::newFromRedirect( $text );
3185 'finalTitle' => $finalTitle,
3190 * Transclude an interwiki link.
3192 function interwikiTransclude( $title, $action ) {
3193 global $wgEnableScaryTranscluding;
3195 if (!$wgEnableScaryTranscluding)
3196 return wfMsg('scarytranscludedisabled');
3198 $url = $title->getFullUrl( "action=$action" );
3200 if (strlen($url) > 255)
3201 return wfMsg('scarytranscludetoolong');
3202 return $this->fetchScaryTemplateMaybeFromCache($url);
3205 function fetchScaryTemplateMaybeFromCache($url) {
3206 global $wgTranscludeCacheExpiry;
3207 $dbr = wfGetDB(DB_SLAVE
);
3208 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3209 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3210 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3212 return $obj->tc_contents
;
3215 $text = Http
::get($url);
3217 return wfMsg('scarytranscludefailed', $url);
3219 $dbw = wfGetDB(DB_MASTER
);
3220 $dbw->replace('transcache', array('tc_url'), array(
3222 'tc_time' => $dbw->timestamp( time() ),
3223 'tc_contents' => $text));
3229 * Triple brace replacement -- used for template arguments
3232 function argSubstitution( $piece, $frame ) {
3233 wfProfileIn( __METHOD__
);
3236 $parts = $piece['parts'];
3237 $nameWithSpaces = $frame->expand( $piece['title'] );
3238 $argName = trim( $nameWithSpaces );
3240 $text = $frame->getArgument( $argName );
3241 if ( $text === false && $parts->getLength() > 0
3245 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3248 # No match in frame, use the supplied default
3249 $object = $parts->item( 0 )->getChildren();
3251 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3252 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3253 $this->limitationWarn( 'post-expand-template-argument' );
3256 if ( $text === false && $object === false ) {
3258 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3260 if ( $error !== false ) {
3263 if ( $object !== false ) {
3264 $ret = array( 'object' => $object );
3266 $ret = array( 'text' => $text );
3269 wfProfileOut( __METHOD__
);
3274 * Return the text to be used for a given extension tag.
3275 * This is the ghost of strip().
3277 * @param array $params Associative array of parameters:
3278 * name PPNode for the tag name
3279 * attr PPNode for unparsed text where tag attributes are thought to be
3280 * attributes Optional associative array of parsed attributes
3281 * inner Contents of extension element
3282 * noClose Original text did not have a close tag
3283 * @param PPFrame $frame
3285 function extensionSubstitution( $params, $frame ) {
3286 global $wgRawHtml, $wgContLang;
3288 $name = $frame->expand( $params['name'] );
3289 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3290 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3291 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3293 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3294 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3295 if ( $isFunctionTag ) {
3296 $markerType = 'none';
3298 $markerType = 'general';
3300 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3301 $name = strtolower( $name );
3302 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3303 if ( isset( $params['attributes'] ) ) {
3304 $attributes = $attributes +
$params['attributes'];
3307 if( isset( $this->mTagHooks
[$name] ) ) {
3308 # Workaround for PHP bug 35229 and similar
3309 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3310 throw new MWException( "Tag hook for $name is not callable\n" );
3312 $output = call_user_func_array( $this->mTagHooks
[$name],
3313 array( $content, $attributes, $this, $frame ) );
3314 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3315 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3316 if( !is_callable( $callback ) )
3317 throw new MWException( "Tag hook for $name is not callable\n" );
3319 $output = call_user_func_array( $callback,
3320 array( &$this, $frame, $content, $attributes ) );
3322 $output = '<span class="error">Invalid tag extension name: ' .
3323 htmlspecialchars( $name ) . '</span>';
3326 if ( is_array( $output ) ) {
3327 // Extract flags to local scope (to override $markerType)
3329 $output = $flags[0];
3334 if ( is_null( $attrText ) ) {
3337 if ( isset( $params['attributes'] ) ) {
3338 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3339 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3340 htmlspecialchars( $attrValue ) . '"';
3343 if ( $content === null ) {
3344 $output = "<$name$attrText/>";
3346 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3347 $output = "<$name$attrText>$content$close";
3351 if( $markerType === 'none' ) {
3353 } elseif ( $markerType === 'nowiki' ) {
3354 $this->mStripState
->nowiki
->setPair( $marker, $output );
3355 } elseif ( $markerType === 'general' ) {
3356 $this->mStripState
->general
->setPair( $marker, $output );
3358 throw new MWException( __METHOD__
.': invalid marker type' );
3364 * Increment an include size counter
3366 * @param string $type The type of expansion
3367 * @param integer $size The size of the text
3368 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3370 function incrementIncludeSize( $type, $size ) {
3371 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3374 $this->mIncludeSizes
[$type] +
= $size;
3380 * Increment the expensive function count
3382 * @return boolean False if the limit has been exceeded
3384 function incrementExpensiveFunctionCount() {
3385 global $wgExpensiveParserFunctionLimit;
3386 $this->mExpensiveFunctionCount++
;
3387 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3394 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3395 * Fills $this->mDoubleUnderscores, returns the modified text
3397 function doDoubleUnderscore( $text ) {
3398 wfProfileIn( __METHOD__
);
3400 // The position of __TOC__ needs to be recorded
3401 $mw = MagicWord
::get( 'toc' );
3402 if( $mw->match( $text ) ) {
3403 $this->mShowToc
= true;
3404 $this->mForceTocPosition
= true;
3406 // Set a placeholder. At the end we'll fill it in with the TOC.
3407 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3409 // Only keep the first one.
3410 $text = $mw->replace( '', $text );
3413 // Now match and remove the rest of them
3414 $mwa = MagicWord
::getDoubleUnderscoreArray();
3415 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3417 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3418 $this->mOutput
->mNoGallery
= true;
3420 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3421 $this->mShowToc
= false;
3423 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3424 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3425 $this->addTrackingCategory( 'hidden-category-category' );
3427 # (bug 8068) Allow control over whether robots index a page.
3429 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3430 # is not desirable, the last one on the page should win.
3431 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3432 $this->mOutput
->setIndexPolicy( 'noindex' );
3433 $this->addTrackingCategory( 'noindex-category' );
3435 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3436 $this->mOutput
->setIndexPolicy( 'index' );
3437 $this->addTrackingCategory( 'index-category' );
3440 wfProfileOut( __METHOD__
);
3445 * Add a tracking category, getting the title from a system message,
3446 * or print a debug message if the title is invalid.
3447 * @param $msg String message key
3448 * @return Bool whether the addition was successful
3450 protected function addTrackingCategory( $msg ){
3451 $cat = wfMsgForContent( $msg );
3453 # Allow tracking categories to be disabled by setting them to "-"
3454 if( $cat === '-' ) return false;
3456 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3457 if ( $containerCategory ) {
3458 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3461 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3467 * This function accomplishes several tasks:
3468 * 1) Auto-number headings if that option is enabled
3469 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3470 * 3) Add a Table of contents on the top for users who have enabled the option
3471 * 4) Auto-anchor headings
3473 * It loops through all headlines, collects the necessary data, then splits up the
3474 * string and re-inserts the newly formatted headlines.
3476 * @param string $text
3477 * @param string $origText Original, untouched wikitext
3478 * @param boolean $isMain
3481 function formatHeadings( $text, $origText, $isMain=true ) {
3482 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3484 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3485 $showEditLink = $this->mOptions
->getEditSection();
3487 // Do not call quickUserCan unless necessary
3488 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3492 # Inhibit editsection links if requested in the page
3493 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3497 # Get all headlines for numbering them and adding funky stuff like [edit]
3498 # links - this is for later, but we need the number of headlines right now
3500 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3502 # if there are fewer than 4 headlines in the article, do not show TOC
3503 # unless it's been explicitly enabled.
3504 $enoughToc = $this->mShowToc
&&
3505 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3507 # Allow user to stipulate that a page should have a "new section"
3508 # link added via __NEWSECTIONLINK__
3509 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3510 $this->mOutput
->setNewSection( true );
3513 # Allow user to remove the "new section"
3514 # link via __NONEWSECTIONLINK__
3515 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3516 $this->mOutput
->hideNewSection( true );
3519 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3520 # override above conditions and always show TOC above first header
3521 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3522 $this->mShowToc
= true;
3526 # We need this to perform operations on the HTML
3527 $sk = $this->mOptions
->getSkin();
3533 # Ugh .. the TOC should have neat indentation levels which can be
3534 # passed to the skin functions. These are determined here
3538 $sublevelCount = array();
3539 $levelCount = array();
3545 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3546 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3547 $oldType = $this->mOutputType
;
3548 $this->setOutputType( self
::OT_WIKI
);
3549 $frame = $this->getPreprocessor()->newFrame();
3550 $root = $this->preprocessToDom( $origText );
3551 $node = $root->getFirstChild();
3555 foreach( $matches[3] as $headline ) {
3556 $isTemplate = false;
3558 $sectionIndex = false;
3560 $markerMatches = array();
3561 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3562 $serial = $markerMatches[1];
3563 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3564 $isTemplate = ($titleText != $baseTitleText);
3565 $headline = preg_replace("/^$markerRegex/", "", $headline);
3569 $prevlevel = $level;
3570 $prevtoclevel = $toclevel;
3572 $level = $matches[1][$headlineCount];
3574 if ( $level > $prevlevel ) {
3575 # Increase TOC level
3577 $sublevelCount[$toclevel] = 0;
3578 if( $toclevel<$wgMaxTocLevel ) {
3579 $prevtoclevel = $toclevel;
3580 $toc .= $sk->tocIndent();
3584 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3585 # Decrease TOC level, find level to jump to
3587 for ($i = $toclevel; $i > 0; $i--) {
3588 if ( $levelCount[$i] == $level ) {
3589 # Found last matching level
3593 elseif ( $levelCount[$i] < $level ) {
3594 # Found first matching level below current level
3599 if( $i == 0 ) $toclevel = 1;
3600 if( $toclevel<$wgMaxTocLevel ) {
3601 if($prevtoclevel < $wgMaxTocLevel) {
3602 # Unindent only if the previous toc level was shown :p
3603 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3604 $prevtoclevel = $toclevel;
3606 $toc .= $sk->tocLineEnd();
3611 # No change in level, end TOC line
3612 if( $toclevel<$wgMaxTocLevel ) {
3613 $toc .= $sk->tocLineEnd();
3617 $levelCount[$toclevel] = $level;
3619 # count number of headlines for each level
3620 @$sublevelCount[$toclevel]++
;
3622 for( $i = 1; $i <= $toclevel; $i++
) {
3623 if( !empty( $sublevelCount[$i] ) ) {
3627 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3632 # The safe header is a version of the header text safe to use for links
3633 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3634 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3636 # Remove link placeholders by the link text.
3637 # <!--LINK number-->
3639 # link text with suffix
3640 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3642 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3643 $tocline = preg_replace(
3644 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3648 $tocline = trim( $tocline );
3650 # For the anchor, strip out HTML-y stuff period
3651 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3652 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3653 $safeHeadline = trim( $safeHeadline );
3655 # Save headline for section edit hint before it's escaped
3656 $headlineHint = $safeHeadline;
3658 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3659 # For reverse compatibility, provide an id that's
3660 # HTML4-compatible, like we used to.
3662 # It may be worth noting, academically, that it's possible for
3663 # the legacy anchor to conflict with a non-legacy headline
3664 # anchor on the page. In this case likely the "correct" thing
3665 # would be to either drop the legacy anchors or make sure
3666 # they're numbered first. However, this would require people
3667 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3668 # manually, so let's not bother worrying about it.
3669 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3670 array( 'noninitial', 'legacy' ) );
3671 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3673 if ( $legacyHeadline == $safeHeadline ) {
3674 # No reason to have both (in fact, we can't)
3675 $legacyHeadline = false;
3678 $legacyHeadline = false;
3679 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3683 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3684 # Does this apply to Unicode characters? Because we aren't
3685 # handling those here.
3686 $arrayKey = strtolower( $safeHeadline );
3687 if ( $legacyHeadline === false ) {
3688 $legacyArrayKey = false;
3690 $legacyArrayKey = strtolower( $legacyHeadline );
3693 # count how many in assoc. array so we can track dupes in anchors
3694 if ( isset( $refers[$arrayKey] ) ) {
3695 $refers[$arrayKey]++
;
3697 $refers[$arrayKey] = 1;
3699 if ( isset( $refers[$legacyArrayKey] ) ) {
3700 $refers[$legacyArrayKey]++
;
3702 $refers[$legacyArrayKey] = 1;
3705 # Don't number the heading if it is the only one (looks silly)
3706 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3707 # the two are different if the line contains a link
3708 $headline = $numbering . ' ' . $headline;
3711 # Create the anchor for linking from the TOC to the section
3712 $anchor = $safeHeadline;
3713 $legacyAnchor = $legacyHeadline;
3714 if ( $refers[$arrayKey] > 1 ) {
3715 $anchor .= '_' . $refers[$arrayKey];
3717 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3718 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3720 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3721 $toc .= $sk->tocLine($anchor, $tocline,
3722 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3725 # Add the section to the section tree
3726 # Find the DOM node for this header
3727 while ( $node && !$isTemplate ) {
3728 if ( $node->getName() === 'h' ) {
3729 $bits = $node->splitHeading();
3730 if ( $bits['i'] == $sectionIndex )
3733 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3734 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3735 $node = $node->getNextSibling();
3738 'toclevel' => $toclevel,
3741 'number' => $numbering,
3742 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3743 'fromtitle' => $titleText,
3744 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3745 'anchor' => $anchor,
3748 # give headline the correct <h#> tag
3749 if( $showEditLink && $sectionIndex !== false ) {
3751 # Put a T flag in the section identifier, to indicate to extractSections()
3752 # that sections inside <includeonly> should be counted.
3753 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3755 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3760 $head[$headlineCount] = $sk->makeHeadline( $level,
3761 $matches['attrib'][$headlineCount], $anchor, $headline,
3762 $editlink, $legacyAnchor );
3767 $this->setOutputType( $oldType );
3769 # Never ever show TOC if no headers
3770 if( $numVisible < 1 ) {
3775 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3776 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3778 $toc = $sk->tocList( $toc );
3779 $this->mOutput
->setTOCHTML( $toc );
3783 $this->mOutput
->setSections( $tocraw );
3786 # split up and insert constructed headlines
3788 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3791 foreach( $blocks as $block ) {
3792 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3793 # This is the [edit] link that appears for the top block of text when
3794 # section editing is enabled
3796 # Disabled because it broke block formatting
3797 # For example, a bullet point in the top line
3798 # $full .= $sk->editSectionLink(0);
3801 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3802 # Top anchor now in skin
3806 if( !empty( $head[$i] ) ) {
3811 if( $this->mForceTocPosition
) {
3812 return str_replace( '<!--MWTOC-->', $toc, $full );
3819 * Merge $tree2 into $tree1 by replacing the section with index
3820 * $section in $tree1 and its descendants with the sections in $tree2.
3821 * Note that in the returned section tree, only the 'index' and
3822 * 'byteoffset' fields are guaranteed to be correct.
3823 * @param $tree1 array Section tree from ParserOutput::getSectons()
3824 * @param $tree2 array Section tree
3825 * @param $section int Section index
3826 * @param $title Title Title both section trees come from
3827 * @param $len2 int Length of the original wikitext for $tree2
3828 * @return array Merged section tree
3830 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3833 $targetLevel = false;
3837 $numbering = array( 0 );
3838 $titletext = $title->getPrefixedDBkey();
3839 foreach ( $tree1 as $s ) {
3840 if ( $targetLevel !== false ) {
3841 if ( $s['level'] <= $targetLevel )
3842 // We've skipped enough
3843 $targetLevel = false;
3847 if ( $s['index'] != $section ||
3848 $s['fromtitle'] != $titletext ) {
3849 self
::incrementNumbering( $numbering,
3850 $s['toclevel'], $lastLevel );
3852 // Rewrite index, byteoffset and number
3853 if ( $s['fromtitle'] == $titletext ) {
3854 $s['index'] = $nextIndex++
;
3856 $s['byteoffset'] +
= $len2;
3858 $s['number'] = implode( '.', array_map(
3859 array( $wgContLang, 'formatnum' ),
3861 $lastLevel = $s['toclevel'];
3864 // We're at $section
3865 // Insert sections from $tree2 here
3866 foreach ( $tree2 as $s2 ) {
3867 // Rewrite the fields in $s2
3868 // before inserting it
3869 $s2['toclevel'] +
= $s['toclevel'] - 1;
3870 $s2['level'] +
= $s['level'] - 1;
3871 $s2['index'] = $nextIndex++
;
3872 $s2['byteoffset'] +
= $s['byteoffset'];
3874 self
::incrementNumbering( $numbering,
3875 $s2['toclevel'], $lastLevel );
3876 $s2['number'] = implode( '.', array_map(
3877 array( $wgContLang, 'formatnum' ),
3879 $lastLevel = $s2['toclevel'];
3882 // Skip all descendants of $section in $tree1
3883 $targetLevel = $s['level'];
3891 * Increment a section number. Helper function for mergeSectionTrees()
3892 * @param $number array Array representing a section number
3893 * @param $level int Current TOC level (depth)
3894 * @param $lastLevel int Level of previous TOC entry
3896 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3897 if ( $level > $lastLevel )
3898 $number[$level - 1] = 1;
3899 else if ( $level < $lastLevel ) {
3900 foreach ( $number as $key => $unused )
3901 if ( $key >= $level )
3902 unset( $number[$key] );
3903 $number[$level - 1]++
;
3905 $number[$level - 1]++
;
3909 * Transform wiki markup when saving a page by doing \r\n -> \n
3910 * conversion, substitting signatures, {{subst:}} templates, etc.
3912 * @param string $text the text to transform
3913 * @param Title &$title the Title object for the current article
3914 * @param User $user the User object describing the current user
3915 * @param ParserOptions $options parsing options
3916 * @param bool $clearState whether to clear the parser state first
3917 * @return string the altered wiki markup
3920 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3921 $this->mOptions
= $options;
3922 $this->setTitle( $title );
3923 $this->setOutputType( self
::OT_WIKI
);
3925 if ( $clearState ) {
3926 $this->clearState();
3932 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3933 $text = $this->pstPass2( $text, $user );
3934 $text = $this->mStripState
->unstripBoth( $text );
3939 * Pre-save transform helper function
3942 function pstPass2( $text, $user ) {
3943 global $wgContLang, $wgLocaltimezone;
3945 /* Note: This is the timestamp saved as hardcoded wikitext to
3946 * the database, we use $wgContLang here in order to give
3947 * everyone the same signature and use the default one rather
3948 * than the one selected in each user's preferences.
3950 * (see also bug 12815)
3952 $ts = $this->mOptions
->getTimestamp();
3953 if ( isset( $wgLocaltimezone ) ) {
3954 $tz = $wgLocaltimezone;
3956 $tz = date_default_timezone_get();
3959 $unixts = wfTimestamp( TS_UNIX
, $ts );
3960 $oldtz = date_default_timezone_get();
3961 date_default_timezone_set( $tz );
3962 $ts = date( 'YmdHis', $unixts );
3963 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3965 /* Allow translation of timezones trough wiki. date() can return
3966 * whatever crap the system uses, localised or not, so we cannot
3967 * ship premade translations.
3969 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3970 $value = wfMsgForContent( $key );
3971 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3973 date_default_timezone_set( $oldtz );
3975 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
3977 # Variable replacement
3978 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3979 $text = $this->replaceVariables( $text );
3982 $sigText = $this->getUserSig( $user );
3983 $text = strtr( $text, array(
3985 '~~~~' => "$sigText $d",
3989 # Context links: [[|name]] and [[name (context)|]]
3991 global $wgLegalTitleChars;
3992 $tc = "[$wgLegalTitleChars]";
3993 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3995 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3996 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3997 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3998 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4000 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4001 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4002 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4003 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4005 $t = $this->mTitle
->getText();
4007 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4008 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4009 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4010 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4012 # if there's no context, don't bother duplicating the title
4013 $text = preg_replace( $p2, '[[\\1]]', $text );
4016 # Trim trailing whitespace
4017 $text = rtrim( $text );
4023 * Fetch the user's signature text, if any, and normalize to
4024 * validated, ready-to-insert wikitext.
4025 * If you have pre-fetched the nickname or the fancySig option, you can
4026 * specify them here to save a database query.
4031 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4032 global $wgMaxSigChars;
4034 $username = $user->getName();
4036 // If not given, retrieve from the user object.
4037 if ( $nickname === false )
4038 $nickname = $user->getOption( 'nickname' );
4040 if ( is_null( $fancySig ) )
4041 $fancySig = $user->getBoolOption( 'fancysig' );
4043 $nickname = $nickname == null ?
$username : $nickname;
4045 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4046 $nickname = $username;
4047 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4048 } elseif( $fancySig !== false ) {
4049 # Sig. might contain markup; validate this
4050 if( $this->validateSig( $nickname ) !== false ) {
4051 # Validated; clean up (if needed) and return it
4052 return $this->cleanSig( $nickname, true );
4054 # Failed to validate; fall back to the default
4055 $nickname = $username;
4056 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4060 // Make sure nickname doesnt get a sig in a sig
4061 $nickname = $this->cleanSigInSig( $nickname );
4063 # If we're still here, make it a link to the user page
4064 $userText = wfEscapeWikiText( $username );
4065 $nickText = wfEscapeWikiText( $nickname );
4066 if ( $user->isAnon() ) {
4067 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4069 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4074 * Check that the user's signature contains no bad XML
4076 * @param string $text
4077 * @return mixed An expanded string, or false if invalid.
4079 function validateSig( $text ) {
4080 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4084 * Clean up signature text
4086 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4087 * 2) Substitute all transclusions
4089 * @param string $text
4090 * @param $parsing Whether we're cleaning (preferences save) or parsing
4091 * @return string Signature text
4093 function cleanSig( $text, $parsing = false ) {
4096 $this->clearState();
4097 $this->setTitle( $wgTitle );
4098 $this->mOptions
= new ParserOptions
;
4099 $this->setOutputType
= self
::OT_PREPROCESS
;
4102 # Option to disable this feature
4103 if ( !$this->mOptions
->getCleanSignatures() ) {
4107 # FIXME: regex doesn't respect extension tags or nowiki
4108 # => Move this logic to braceSubstitution()
4109 $substWord = MagicWord
::get( 'subst' );
4110 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4111 $substText = '{{' . $substWord->getSynonym( 0 );
4113 $text = preg_replace( $substRegex, $substText, $text );
4114 $text = $this->cleanSigInSig( $text );
4115 $dom = $this->preprocessToDom( $text );
4116 $frame = $this->getPreprocessor()->newFrame();
4117 $text = $frame->expand( $dom );
4120 $text = $this->mStripState
->unstripBoth( $text );
4127 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4128 * @param string $text
4129 * @return string Signature text with /~{3,5}/ removed
4131 function cleanSigInSig( $text ) {
4132 $text = preg_replace( '/~{3,5}/', '', $text );
4137 * Set up some variables which are usually set up in parse()
4138 * so that an external function can call some class members with confidence
4141 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4142 $this->setTitle( $title );
4143 $this->mOptions
= $options;
4144 $this->setOutputType( $outputType );
4145 if ( $clearState ) {
4146 $this->clearState();
4151 * Wrapper for preprocess()
4153 * @param string $text the text to preprocess
4154 * @param ParserOptions $options options
4158 function transformMsg( $text, $options ) {
4160 static $executing = false;
4162 # Guard against infinite recursion
4168 wfProfileIn(__METHOD__
);
4169 $text = $this->preprocess( $text, $wgTitle, $options );
4172 wfProfileOut(__METHOD__
);
4177 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4178 * The callback should have the following form:
4179 * function myParserHook( $text, $params, &$parser ) { ... }
4181 * Transform and return $text. Use $parser for any required context, e.g. use
4182 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4186 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4187 * @param mixed $callback The callback function (and object) to use for the tag
4189 * @return The old value of the mTagHooks array associated with the hook
4191 function setHook( $tag, $callback ) {
4192 $tag = strtolower( $tag );
4193 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4194 $this->mTagHooks
[$tag] = $callback;
4195 if( !in_array( $tag, $this->mStripList
) ) {
4196 $this->mStripList
[] = $tag;
4202 function setTransparentTagHook( $tag, $callback ) {
4203 $tag = strtolower( $tag );
4204 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4205 $this->mTransparentTagHooks
[$tag] = $callback;
4211 * Remove all tag hooks
4213 function clearTagHooks() {
4214 $this->mTagHooks
= array();
4215 $this->mStripList
= $this->mDefaultStripList
;
4219 * Create a function, e.g. {{sum:1|2|3}}
4220 * The callback function should have the form:
4221 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4223 * Or with SFH_OBJECT_ARGS:
4224 * function myParserFunction( $parser, $frame, $args ) { ... }
4226 * The callback may either return the text result of the function, or an array with the text
4227 * in element 0, and a number of flags in the other elements. The names of the flags are
4228 * specified in the keys. Valid flags are:
4229 * found The text returned is valid, stop processing the template. This
4231 * nowiki Wiki markup in the return value should be escaped
4232 * isHTML The returned text is HTML, armour it against wikitext transformation
4236 * @param string $id The magic word ID
4237 * @param mixed $callback The callback function (and object) to use
4238 * @param integer $flags a combination of the following flags:
4239 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4241 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4242 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4243 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4244 * the arguments, and to control the way they are expanded.
4246 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4247 * arguments, for instance:
4248 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4250 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4251 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4252 * working if/when this is changed.
4254 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4257 * Please read the documentation in includes/parser/Preprocessor.php for more information
4258 * about the methods available in PPFrame and PPNode.
4260 * @return The old callback function for this name, if any
4262 function setFunctionHook( $id, $callback, $flags = 0 ) {
4265 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4266 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4268 # Add to function cache
4269 $mw = MagicWord
::get( $id );
4271 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4273 $synonyms = $mw->getSynonyms();
4274 $sensitive = intval( $mw->isCaseSensitive() );
4276 foreach ( $synonyms as $syn ) {
4278 if ( !$sensitive ) {
4279 $syn = $wgContLang->lc( $syn );
4282 if ( !( $flags & SFH_NO_HASH
) ) {
4285 # Remove trailing colon
4286 if ( substr( $syn, -1, 1 ) === ':' ) {
4287 $syn = substr( $syn, 0, -1 );
4289 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4295 * Get all registered function hook identifiers
4299 function getFunctionHooks() {
4300 return array_keys( $this->mFunctionHooks
);
4304 * Create a tag function, e.g. <test>some stuff</test>.
4305 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4306 * Unlike parser functions, their content is not preprocessed.
4308 function setFunctionTagHook( $tag, $callback, $flags ) {
4309 $tag = strtolower( $tag );
4310 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4311 $this->mFunctionTagHooks
[$tag] : null;
4312 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4314 if( !in_array( $tag, $this->mStripList
) ) {
4315 $this->mStripList
[] = $tag;
4322 * FIXME: update documentation. makeLinkObj() is deprecated.
4323 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4324 * Placeholders created in Skin::makeLinkObj()
4325 * Returns an array of link CSS classes, indexed by PDBK.
4327 function replaceLinkHolders( &$text, $options = 0 ) {
4328 return $this->mLinkHolders
->replace( $text );
4332 * Replace <!--LINK--> link placeholders with plain text of links
4333 * (not HTML-formatted).
4334 * @param string $text
4337 function replaceLinkHoldersText( $text ) {
4338 return $this->mLinkHolders
->replaceText( $text );
4342 * Renders an image gallery from a text with one line per image.
4343 * text labels may be given by using |-style alternative text. E.g.
4344 * Image:one.jpg|The number "1"
4345 * Image:tree.jpg|A tree
4346 * given as text will return the HTML of a gallery with two images,
4347 * labeled 'The number "1"' and
4350 function renderImageGallery( $text, $params ) {
4351 $ig = new ImageGallery();
4352 $ig->setContextTitle( $this->mTitle
);
4353 $ig->setShowBytes( false );
4354 $ig->setShowFilename( false );
4355 $ig->setParser( $this );
4356 $ig->setHideBadImages();
4357 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4358 $ig->useSkin( $this->mOptions
->getSkin() );
4359 $ig->mRevisionId
= $this->mRevisionId
;
4361 if( isset( $params['caption'] ) ) {
4362 $caption = $params['caption'];
4363 $caption = htmlspecialchars( $caption );
4364 $caption = $this->replaceInternalLinks( $caption );
4365 $ig->setCaptionHtml( $caption );
4367 if( isset( $params['perrow'] ) ) {
4368 $ig->setPerRow( $params['perrow'] );
4370 if( isset( $params['widths'] ) ) {
4371 $ig->setWidths( $params['widths'] );
4373 if( isset( $params['heights'] ) ) {
4374 $ig->setHeights( $params['heights'] );
4377 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4379 $lines = StringUtils
::explode( "\n", $text );
4380 foreach ( $lines as $line ) {
4381 # match lines like these:
4382 # Image:someimage.jpg|This is some image
4384 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4386 if ( count( $matches ) == 0 ) {
4390 if ( strpos( $matches[0], '%' ) !== false )
4391 $matches[1] = urldecode( $matches[1] );
4392 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4394 if( is_null( $nt ) ) {
4395 # Bogus title. Ignore these so we don't bomb out later.
4398 if ( isset( $matches[3] ) ) {
4399 $label = $matches[3];
4404 $html = $this->recursiveTagParse( trim( $label ) );
4406 $ig->add( $nt, $html );
4408 # Only add real images (bug #5586)
4409 if ( $nt->getNamespace() == NS_FILE
) {
4410 $this->mOutput
->addImage( $nt->getDBkey() );
4413 return $ig->toHTML();
4416 function getImageParams( $handler ) {
4418 $handlerClass = get_class( $handler );
4422 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4423 // Initialise static lists
4424 static $internalParamNames = array(
4425 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4426 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4427 'bottom', 'text-bottom' ),
4428 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4429 'upright', 'border', 'link', 'alt' ),
4431 static $internalParamMap;
4432 if ( !$internalParamMap ) {
4433 $internalParamMap = array();
4434 foreach ( $internalParamNames as $type => $names ) {
4435 foreach ( $names as $name ) {
4436 $magicName = str_replace( '-', '_', "img_$name" );
4437 $internalParamMap[$magicName] = array( $type, $name );
4442 // Add handler params
4443 $paramMap = $internalParamMap;
4445 $handlerParamMap = $handler->getParamMap();
4446 foreach ( $handlerParamMap as $magic => $paramName ) {
4447 $paramMap[$magic] = array( 'handler', $paramName );
4450 $this->mImageParams
[$handlerClass] = $paramMap;
4451 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4453 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4457 * Parse image options text and use it to make an image
4458 * @param Title $title
4459 * @param string $options
4460 * @param LinkHolderArray $holders
4462 function makeImage( $title, $options, $holders = false ) {
4463 # Check if the options text is of the form "options|alt text"
4465 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4466 # * left no resizing, just left align. label is used for alt= only
4467 # * right same, but right aligned
4468 # * none same, but not aligned
4469 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4470 # * center center the image
4471 # * frame Keep original image size, no magnify-button.
4472 # * framed Same as "frame"
4473 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4474 # * upright reduce width for upright images, rounded to full __0 px
4475 # * border draw a 1px border around the image
4476 # * alt Text for HTML alt attribute (defaults to empty)
4477 # * link Set the target of the image link. Can be external, interwiki, or local
4478 # vertical-align values (no % or length right now):
4488 $parts = StringUtils
::explode( "|", $options );
4489 $sk = $this->mOptions
->getSkin();
4491 # Give extensions a chance to select the file revision for us
4492 $skip = $time = $descQuery = false;
4493 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4496 return $sk->link( $title );
4500 $imagename = $title->getDBkey();
4501 $file = wfFindFile( $title, array( 'time' => $time ) );
4503 $handler = $file ?
$file->getHandler() : false;
4505 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4507 # Process the input parameters
4509 $params = array( 'frame' => array(), 'handler' => array(),
4510 'horizAlign' => array(), 'vertAlign' => array() );
4511 foreach( $parts as $part ) {
4512 $part = trim( $part );
4513 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4515 if( isset( $paramMap[$magicName] ) ) {
4516 list( $type, $paramName ) = $paramMap[$magicName];
4518 // Special case; width and height come in one variable together
4519 if( $type === 'handler' && $paramName === 'width' ) {
4521 # (bug 13500) In both cases (width/height and width only),
4522 # permit trailing "px" for backward compatibility.
4523 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4524 $width = intval( $m[1] );
4525 $height = intval( $m[2] );
4526 if ( $handler->validateParam( 'width', $width ) ) {
4527 $params[$type]['width'] = $width;
4530 if ( $handler->validateParam( 'height', $height ) ) {
4531 $params[$type]['height'] = $height;
4534 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4535 $width = intval( $value );
4536 if ( $handler->validateParam( 'width', $width ) ) {
4537 $params[$type]['width'] = $width;
4540 } // else no validation -- bug 13436
4542 if ( $type === 'handler' ) {
4543 # Validate handler parameter
4544 $validated = $handler->validateParam( $paramName, $value );
4546 # Validate internal parameters
4547 switch( $paramName ) {
4550 // @todo Fixme: possibly check validity here for
4551 // manualthumb? downstream behavior seems odd with
4552 // missing manual thumbs.
4554 $value = $this->stripAltText( $value, $holders );
4557 $chars = self
::EXT_LINK_URL_CLASS
;
4558 $prots = $this->mUrlProtocols
;
4559 if ( $value === '' ) {
4560 $paramName = 'no-link';
4563 } elseif ( preg_match( "/^$prots/", $value ) ) {
4564 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4565 $paramName = 'link-url';
4566 $this->mOutput
->addExternalLink( $value );
4570 $linkTitle = Title
::newFromText( $value );
4572 $paramName = 'link-title';
4573 $value = $linkTitle;
4574 $this->mOutput
->addLink( $linkTitle );
4580 // Most other things appear to be empty or numeric...
4581 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4586 $params[$type][$paramName] = $value;
4590 if ( !$validated ) {
4595 # Process alignment parameters
4596 if ( $params['horizAlign'] ) {
4597 $params['frame']['align'] = key( $params['horizAlign'] );
4599 if ( $params['vertAlign'] ) {
4600 $params['frame']['valign'] = key( $params['vertAlign'] );
4603 $params['frame']['caption'] = $caption;
4605 # Will the image be presented in a frame, with the caption below?
4606 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4607 isset( $params['frame']['framed'] ) ||
4608 isset( $params['frame']['thumbnail'] ) ||
4609 isset( $params['frame']['manualthumb'] );
4611 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4612 # came to also set the caption, ordinary text after the image -- which
4613 # makes no sense, because that just repeats the text multiple times in
4614 # screen readers. It *also* came to set the title attribute.
4616 # Now that we have an alt attribute, we should not set the alt text to
4617 # equal the caption: that's worse than useless, it just repeats the
4618 # text. This is the framed/thumbnail case. If there's no caption, we
4619 # use the unnamed parameter for alt text as well, just for the time be-
4620 # ing, if the unnamed param is set and the alt param is not.
4622 # For the future, we need to figure out if we want to tweak this more,
4623 # e.g., introducing a title= parameter for the title; ignoring the un-
4624 # named parameter entirely for images without a caption; adding an ex-
4625 # plicit caption= parameter and preserving the old magic unnamed para-
4627 if ( $imageIsFramed ) { # Framed image
4628 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4629 # No caption or alt text, add the filename as the alt text so
4630 # that screen readers at least get some description of the image
4631 $params['frame']['alt'] = $title->getText();
4633 # Do not set $params['frame']['title'] because tooltips don't make sense
4635 } else { # Inline image
4636 if ( !isset( $params['frame']['alt'] ) ) {
4637 # No alt text, use the "caption" for the alt text
4638 if ( $caption !== '') {
4639 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4641 # No caption, fall back to using the filename for the
4643 $params['frame']['alt'] = $title->getText();
4646 # Use the "caption" for the tooltip text
4647 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4650 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4652 # Linker does the rest
4653 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4655 # Give the handler a chance to modify the parser object
4657 $handler->parserTransformHook( $this, $file );
4663 protected function stripAltText( $caption, $holders ) {
4664 # Strip bad stuff out of the title (tooltip). We can't just use
4665 # replaceLinkHoldersText() here, because if this function is called
4666 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4668 $tooltip = $holders->replaceText( $caption );
4670 $tooltip = $this->replaceLinkHoldersText( $caption );
4673 # make sure there are no placeholders in thumbnail attributes
4674 # that are later expanded to html- so expand them now and
4676 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4677 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4683 * Set a flag in the output object indicating that the content is dynamic and
4684 * shouldn't be cached.
4686 function disableCache() {
4687 wfDebug( "Parser output marked as uncacheable.\n" );
4688 $this->mOutput
->mCacheTime
= -1;
4692 * Callback from the Sanitizer for expanding items found in HTML attribute
4693 * values, so they can be safely tested and escaped.
4694 * @param string $text
4695 * @param PPFrame $frame
4699 function attributeStripCallback( &$text, $frame = false ) {
4700 $text = $this->replaceVariables( $text, $frame );
4701 $text = $this->mStripState
->unstripBoth( $text );
4710 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4711 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4712 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4718 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4723 * Break wikitext input into sections, and either pull or replace
4724 * some particular section's text.
4726 * External callers should use the getSection and replaceSection methods.
4728 * @param string $text Page wikitext
4729 * @param string $section A section identifier string of the form:
4730 * <flag1> - <flag2> - ... - <section number>
4732 * Currently the only recognised flag is "T", which means the target section number
4733 * was derived during a template inclusion parse, in other words this is a template
4734 * section edit link. If no flags are given, it was an ordinary section edit link.
4735 * This flag is required to avoid a section numbering mismatch when a section is
4736 * enclosed by <includeonly> (bug 6563).
4738 * The section number 0 pulls the text before the first heading; other numbers will
4739 * pull the given section along with its lower-level subsections. If the section is
4740 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4742 * @param string $mode One of "get" or "replace"
4743 * @param string $newText Replacement text for section data.
4744 * @return string for "get", the extracted section text.
4745 * for "replace", the whole page with the section replaced.
4747 private function extractSections( $text, $section, $mode, $newText='' ) {
4749 $this->clearState();
4750 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4751 $this->mOptions
= new ParserOptions
;
4752 $this->setOutputType( self
::OT_WIKI
);
4754 $frame = $this->getPreprocessor()->newFrame();
4756 // Process section extraction flags
4758 $sectionParts = explode( '-', $section );
4759 $sectionIndex = array_pop( $sectionParts );
4760 foreach ( $sectionParts as $part ) {
4761 if ( $part === 'T' ) {
4762 $flags |
= self
::PTD_FOR_INCLUSION
;
4765 // Preprocess the text
4766 $root = $this->preprocessToDom( $text, $flags );
4768 // <h> nodes indicate section breaks
4769 // They can only occur at the top level, so we can find them by iterating the root's children
4770 $node = $root->getFirstChild();
4772 // Find the target section
4773 if ( $sectionIndex == 0 ) {
4774 // Section zero doesn't nest, level=big
4775 $targetLevel = 1000;
4778 if ( $node->getName() === 'h' ) {
4779 $bits = $node->splitHeading();
4780 if ( $bits['i'] == $sectionIndex ) {
4781 $targetLevel = $bits['level'];
4785 if ( $mode === 'replace' ) {
4786 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4788 $node = $node->getNextSibling();
4794 if ( $mode === 'get' ) {
4801 // Find the end of the section, including nested sections
4803 if ( $node->getName() === 'h' ) {
4804 $bits = $node->splitHeading();
4805 $curLevel = $bits['level'];
4806 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4810 if ( $mode === 'get' ) {
4811 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4813 $node = $node->getNextSibling();
4816 // Write out the remainder (in replace mode only)
4817 if ( $mode === 'replace' ) {
4818 // Output the replacement text
4819 // Add two newlines on -- trailing whitespace in $newText is conventionally
4820 // stripped by the editor, so we need both newlines to restore the paragraph gap
4821 // Only add trailing whitespace if there is newText
4822 if($newText != "") {
4823 $outText .= $newText . "\n\n";
4827 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4828 $node = $node->getNextSibling();
4832 if ( is_string( $outText ) ) {
4833 // Re-insert stripped tags
4834 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4841 * This function returns the text of a section, specified by a number ($section).
4842 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4843 * the first section before any such heading (section 0).
4845 * If a section contains subsections, these are also returned.
4847 * @param string $text text to look in
4848 * @param string $section section identifier
4849 * @param string $deftext default to return if section is not found
4850 * @return string text of the requested section
4852 public function getSection( $text, $section, $deftext='' ) {
4853 return $this->extractSections( $text, $section, "get", $deftext );
4856 public function replaceSection( $oldtext, $section, $text ) {
4857 return $this->extractSections( $oldtext, $section, "replace", $text );
4861 * Get the timestamp associated with the current revision, adjusted for
4862 * the default server-local timestamp
4864 function getRevisionTimestamp() {
4865 if ( is_null( $this->mRevisionTimestamp
) ) {
4866 wfProfileIn( __METHOD__
);
4868 $dbr = wfGetDB( DB_SLAVE
);
4869 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4870 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4872 // Normalize timestamp to internal MW format for timezone processing.
4873 // This has the added side-effect of replacing a null value with
4874 // the current time, which gives us more sensible behavior for
4876 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4878 // The cryptic '' timezone parameter tells to use the site-default
4879 // timezone offset instead of the user settings.
4881 // Since this value will be saved into the parser cache, served
4882 // to other users, and potentially even used inside links and such,
4883 // it needs to be consistent for all visitors.
4884 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4886 wfProfileOut( __METHOD__
);
4888 return $this->mRevisionTimestamp
;
4892 * Get the name of the user that edited the last revision
4894 function getRevisionUser() {
4895 // if this template is subst: the revision id will be blank,
4896 // so just use the current user's name
4897 if( $this->mRevisionId
) {
4898 $revision = Revision
::newFromId( $this->mRevisionId
);
4899 $revuser = $revision->getUserText();
4902 $revuser = $wgUser->getName();
4908 * Mutator for $mDefaultSort
4910 * @param $sort New value
4912 public function setDefaultSort( $sort ) {
4913 $this->mDefaultSort
= $sort;
4917 * Accessor for $mDefaultSort
4918 * Will use the title/prefixed title if none is set
4922 public function getDefaultSort() {
4923 global $wgCategoryPrefixedDefaultSortkey;
4924 if( $this->mDefaultSort
!== false ) {
4925 return $this->mDefaultSort
;
4926 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4927 !$wgCategoryPrefixedDefaultSortkey) {
4928 return $this->mTitle
->getText();
4930 return $this->mTitle
->getPrefixedText();
4935 * Accessor for $mDefaultSort
4936 * Unlike getDefaultSort(), will return false if none is set
4938 * @return string or false
4940 public function getCustomDefaultSort() {
4941 return $this->mDefaultSort
;
4945 * Try to guess the section anchor name based on a wikitext fragment
4946 * presumably extracted from a heading, for example "Header" from
4949 public function guessSectionNameFromWikiText( $text ) {
4950 # Strip out wikitext links(they break the anchor)
4951 $text = $this->stripSectionName( $text );
4952 $headline = Sanitizer
::decodeCharReferences( $text );
4954 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4955 $headline = trim( $headline );
4956 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4957 $replacearray = array(
4962 array_keys( $replacearray ),
4963 array_values( $replacearray ),
4968 * Strips a text string of wikitext for use in a section anchor
4970 * Accepts a text string and then removes all wikitext from the
4971 * string and leaves only the resultant text (i.e. the result of
4972 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4973 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4974 * to create valid section anchors by mimicing the output of the
4975 * parser when headings are parsed.
4977 * @param $text string Text string to be stripped of wikitext
4978 * for use in a Section anchor
4979 * @return Filtered text string
4981 public function stripSectionName( $text ) {
4982 # Strip internal link markup
4983 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4984 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4986 # Strip external link markup (FIXME: Not Tolerant to blank link text
4987 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4988 # on how many empty links there are on the page - need to figure that out.
4989 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4991 # Parse wikitext quotes (italics & bold)
4992 $text = $this->doQuotes($text);
4995 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4999 function srvus( $text ) {
5000 return $this->testSrvus( $text, $this->mOutputType
);
5004 * strip/replaceVariables/unstrip for preprocessor regression testing
5006 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5007 $this->clearState();
5008 if ( ! ( $title instanceof Title
) ) {
5009 $title = Title
::newFromText( $title );
5011 $this->mTitle
= $title;
5012 $this->mOptions
= $options;
5013 $this->setOutputType( $outputType );
5014 $text = $this->replaceVariables( $text );
5015 $text = $this->mStripState
->unstripBoth( $text );
5016 $text = Sanitizer
::removeHTMLtags( $text );
5020 function testPst( $text, $title, $options ) {
5022 if ( ! ( $title instanceof Title
) ) {
5023 $title = Title
::newFromText( $title );
5025 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5028 function testPreprocess( $text, $title, $options ) {
5029 if ( ! ( $title instanceof Title
) ) {
5030 $title = Title
::newFromText( $title );
5032 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5035 function markerSkipCallback( $s, $callback ) {
5038 while ( $i < strlen( $s ) ) {
5039 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5040 if ( $markerStart === false ) {
5041 $out .= call_user_func( $callback, substr( $s, $i ) );
5044 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5045 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5046 if ( $markerEnd === false ) {
5047 $out .= substr( $s, $markerStart );
5050 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5051 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5059 function serialiseHalfParsedText( $text ) {
5061 $data['text'] = $text;
5063 // First, find all strip markers, and store their
5064 // data in an array.
5065 $stripState = new StripState
;
5067 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5068 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5069 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5071 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5072 $replaceArray = $stripState->general
;
5073 $stripText = $this->mStripState
->general
->data
[$marker];
5074 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5075 $replaceArray = $stripState->nowiki
;
5076 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5078 throw new MWException( "Hanging strip marker: '$marker'." );
5081 $replaceArray->setPair( $marker, $stripText );
5084 $data['stripstate'] = $stripState;
5086 // Now, find all of our links, and store THEIR
5087 // data in an array! :)
5088 $links = array( 'internal' => array(), 'interwiki' => array() );
5092 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5093 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5096 if (empty( $links['internal'][$ns] )) {
5097 $links['internal'][$ns] = array();
5100 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5101 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5102 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5108 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5109 $data = substr( $text, $start_pos );
5110 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5111 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5112 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5115 $data['linkholder'] = $links;
5120 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5122 $intPrefix = $this->getRandomString();
5124 // First, extract the strip state.
5125 $stripState = $data['stripstate'];
5126 $this->mStripState
->general
->merge( $stripState->general
);
5127 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5129 // Now, extract the text, and renumber links
5130 $text = $data['text'];
5131 $links = $data['linkholder'];
5134 foreach( $links['internal'] as $ns => $nsLinks ) {
5135 foreach( $nsLinks as $key => $entry ) {
5136 $newKey = $intPrefix . '-' . $key;
5137 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5139 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5144 foreach( $links['interwiki'] as $key => $entry ) {
5145 $newKey = "$intPrefix-$key";
5146 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5148 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5151 // Should be good to go.
5157 * @todo document, briefly.
5161 var $general, $nowiki;
5163 function __construct() {
5164 $this->general
= new ReplacementArray
;
5165 $this->nowiki
= new ReplacementArray
;
5168 function unstripGeneral( $text ) {
5169 wfProfileIn( __METHOD__
);
5172 $text = $this->general
->replace( $text );
5173 } while ( $text !== $oldText );
5174 wfProfileOut( __METHOD__
);
5178 function unstripNoWiki( $text ) {
5179 wfProfileIn( __METHOD__
);
5182 $text = $this->nowiki
->replace( $text );
5183 } while ( $text !== $oldText );
5184 wfProfileOut( __METHOD__
);
5188 function unstripBoth( $text ) {
5189 wfProfileIn( __METHOD__
);
5192 $text = $this->general
->replace( $text );
5193 $text = $this->nowiki
->replace( $text );
5194 } while ( $text !== $oldText );
5195 wfProfileOut( __METHOD__
);
5201 * @todo document, briefly.
5204 class OnlyIncludeReplacer
{
5207 function replace( $matches ) {
5208 if ( substr( $matches[1], -1 ) === "\n" ) {
5209 $this->output
.= substr( $matches[1], 0, -1 );
5211 $this->output
.= $matches[1];