3 * Parser with old preprocessor
8 * Update this version number when the ParserOutput format
9 * changes in an incompatible way, so the parser cache
10 * can automatically discard old data.
12 const VERSION
= '1.6.4';
14 # Flags for Parser::setFunctionHook
15 # Also available as global constants from Defines.php
16 const SFH_NO_HASH
= 1;
18 # Constants needed for external link processing
19 # Everything except bracket, space, or control characters
20 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
21 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)\\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/S';
23 // State constants for the definition list colon extraction
24 const COLON_STATE_TEXT
= 0;
25 const COLON_STATE_TAG
= 1;
26 const COLON_STATE_TAGSTART
= 2;
27 const COLON_STATE_CLOSETAG
= 3;
28 const COLON_STATE_TAGSLASH
= 4;
29 const COLON_STATE_COMMENT
= 5;
30 const COLON_STATE_COMMENTDASH
= 6;
31 const COLON_STATE_COMMENTDASHDASH
= 7;
33 // Allowed values for $this->mOutputType
34 // Parameter to startExternalParse().
37 const OT_PREPROCESS
= 3;
44 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
45 $mImageParams, $mImageParamsMagicArray, $mExtLinkBracketedRegex;
47 # Cleared with clearState():
48 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
49 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
50 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
51 var $mIncludeSizes, $mDefaultSort;
52 var $mTemplates, // cache of already loaded templates, avoids
53 // multiple SQL queries for the same string
54 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
55 // in this path. Used for loop detection.
58 # These are variables reset at least once per parse regardless of $clearState
59 var $mOptions, // ParserOptions object
60 $mTitle, // Title context, used for self-link rendering and similar things
61 $mOutputType, // Output type, one of the OT_xxx constants
62 $ot, // Shortcut alias, see setOutputType()
63 $mRevisionId, // ID to display in {{REVISIONID}} tags
64 $mRevisionTimestamp, // The timestamp of the specified revision ID
65 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
74 function __construct( $conf = array() ) {
75 $this->mTagHooks
= array();
76 $this->mTransparentTagHooks
= array();
77 $this->mFunctionHooks
= array();
78 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
79 $this->mFirstCall
= true;
80 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
81 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
85 * Do various kinds of initialisation on the first call of the parser
87 function firstCallInit() {
88 if ( !$this->mFirstCall
) {
91 $this->mFirstCall
= false;
93 wfProfileIn( __METHOD__
);
94 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
96 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
98 # Syntax for arguments (see self::setFunctionHook):
99 # "name for lookup in localized magic words array",
101 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
102 # instead of {{#int:...}})
103 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
104 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
105 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
106 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
107 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
108 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
109 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
110 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
111 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
112 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
113 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
114 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
115 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
116 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
117 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
118 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
119 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
120 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
121 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
122 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
123 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
124 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
125 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
126 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
127 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
128 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
129 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
131 if ( $wgAllowDisplayTitle ) {
132 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
134 if ( $wgAllowSlowParserFunctions ) {
135 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
138 $this->initialiseVariables();
140 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
141 wfProfileOut( __METHOD__
);
149 function clearState() {
150 wfProfileIn( __METHOD__
);
151 if ( $this->mFirstCall
) {
152 $this->firstCallInit();
154 $this->mOutput
= new ParserOutput
;
155 $this->mAutonumber
= 0;
156 $this->mLastSection
= '';
157 $this->mDTopen
= false;
158 $this->mIncludeCount
= array();
159 $this->mStripState
= new StripState
;
160 $this->mArgStack
= array();
161 $this->mInPre
= false;
162 $this->mInterwikiLinkHolders
= array(
166 $this->mLinkHolders
= array(
167 'namespaces' => array(),
169 'queries' => array(),
173 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
176 * Prefix for temporary replacement strings for the multipass parser.
177 * \x07 should never appear in input as it's disallowed in XML.
178 * Using it at the front also gives us a little extra robustness
179 * since it shouldn't match when butted up against identifier-like
182 $this->mUniqPrefix
= "\x07UNIQ" . self
::getRandomString();
184 # Clear these on every parse, bug 4549
185 $this->mTemplates
= array();
186 $this->mTemplatePath
= array();
188 $this->mShowToc
= true;
189 $this->mForceTocPosition
= false;
190 $this->mIncludeSizes
= array(
195 $this->mDefaultSort
= false;
197 wfRunHooks( 'ParserClearState', array( &$this ) );
198 wfProfileOut( __METHOD__
);
201 function setOutputType( $ot ) {
202 $this->mOutputType
= $ot;
205 'html' => $ot == self
::OT_HTML
,
206 'wiki' => $ot == self
::OT_WIKI
,
207 'msg' => $ot == self
::OT_MSG
,
208 'pre' => $ot == self
::OT_PREPROCESS
,
213 * Accessor for mUniqPrefix.
217 function uniqPrefix() {
218 return $this->mUniqPrefix
;
222 * Convert wikitext to HTML
223 * Do not call this function recursively.
225 * @param string $text Text we want to parse
226 * @param Title &$title A title object
227 * @param array $options
228 * @param boolean $linestart
229 * @param boolean $clearState
230 * @param int $revid number to pass in {{REVISIONID}}
231 * @return ParserOutput a ParserOutput
233 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
235 * First pass--just handle <nowiki> sections, pass the rest off
236 * to internalParse() which does all the real work.
239 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
240 $fname = 'Parser::parse-' . wfGetCaller();
241 wfProfileIn( __METHOD__
);
242 wfProfileIn( $fname );
248 $this->mOptions
= $options;
249 $this->mTitle
=& $title;
250 $oldRevisionId = $this->mRevisionId
;
251 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
252 if( $revid !== null ) {
253 $this->mRevisionId
= $revid;
254 $this->mRevisionTimestamp
= null;
256 $this->setOutputType( self
::OT_HTML
);
257 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
258 $text = $this->strip( $text, $this->mStripState
);
259 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
260 $text = $this->internalParse( $text );
261 $text = $this->mStripState
->unstripGeneral( $text );
263 # Clean up special characters, only run once, next-to-last before doBlockLevels
265 # french spaces, last one Guillemet-left
266 # only if there is something before the space
267 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
268 # french spaces, Guillemet-right
269 '/(\\302\\253) /' => '\\1 ',
271 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
274 $text = $this->doBlockLevels( $text, $linestart );
276 $this->replaceLinkHolders( $text );
278 # the position of the parserConvert() call should not be changed. it
279 # assumes that the links are all replaced and the only thing left
280 # is the <nowiki> mark.
281 # Side-effects: this calls $this->mOutput->setTitleText()
282 $text = $wgContLang->parserConvert( $text, $this );
284 $text = $this->mStripState
->unstripNoWiki( $text );
286 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
288 //!JF Move to its own function
290 $uniq_prefix = $this->mUniqPrefix
;
292 $elements = array_keys( $this->mTransparentTagHooks
);
293 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
295 foreach( $matches as $marker => $data ) {
296 list( $element, $content, $params, $tag ) = $data;
297 $tagName = strtolower( $element );
298 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
299 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
300 array( $content, $params, $this ) );
304 $this->mStripState
->general
->setPair( $marker, $output );
306 $text = $this->mStripState
->unstripGeneral( $text );
308 $text = Sanitizer
::normalizeCharReferences( $text );
310 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
311 $text = self
::tidy($text);
313 # attempt to sanitize at least some nesting problems
314 # (bug #2702 and quite a few others)
316 # ''Something [http://www.cool.com cool''] -->
317 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
318 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
319 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
320 # fix up an anchor inside another anchor, only
321 # at least for a single single nested link (bug 3695)
322 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
323 '\\1\\2</a>\\3</a>\\1\\4</a>',
324 # fix div inside inline elements- doBlockLevels won't wrap a line which
325 # contains a div, so fix it up here; replace
326 # div with escaped text
327 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
328 '\\1\\3<div\\5>\\6</div>\\8\\9',
329 # remove empty italic or bold tag pairs, some
330 # introduced by rules above
331 '/<([bi])><\/\\1>/' => '',
334 $text = preg_replace(
335 array_keys( $tidyregs ),
336 array_values( $tidyregs ),
340 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
342 # Information on include size limits, for the benefit of users who try to skirt them
343 if ( $this->mOptions
->getEnableLimitReport() ) {
344 $max = $this->mOptions
->getMaxIncludeSize();
346 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']}/$max bytes\n" .
347 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
348 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
349 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
350 $text .= "<!-- \n$limitReport-->\n";
352 $this->mOutput
->setText( $text );
353 $this->mRevisionId
= $oldRevisionId;
354 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
355 wfProfileOut( $fname );
356 wfProfileOut( __METHOD__
);
358 return $this->mOutput
;
362 * Recursive parser entry point that can be called from an extension tag
365 function recursiveTagParse( $text ) {
366 wfProfileIn( __METHOD__
);
367 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
368 $text = $this->strip( $text, $this->mStripState
);
369 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
370 $text = $this->internalParse( $text );
371 wfProfileOut( __METHOD__
);
376 * Expand templates and variables in the text, producing valid, static wikitext.
377 * Also removes comments.
379 function preprocess( $text, $title, $options, $revid = null ) {
380 wfProfileIn( __METHOD__
);
382 $this->setOutputType( self
::OT_PREPROCESS
);
383 $this->mOptions
= $options;
384 $this->mTitle
= $title;
385 if( $revid !== null ) {
386 $this->mRevisionId
= $revid;
388 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
389 $text = $this->strip( $text, $this->mStripState
);
390 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
391 if ( $this->mOptions
->getRemoveComments() ) {
392 $text = Sanitizer
::removeHTMLcomments( $text );
394 $text = $this->replaceVariables( $text );
395 $text = $this->mStripState
->unstripBoth( $text );
396 wfProfileOut( __METHOD__
);
401 * Get a random string
406 function getRandomString() {
407 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
410 function &getTitle() { return $this->mTitle
; }
411 function getOptions() { return $this->mOptions
; }
413 function getFunctionLang() {
414 global $wgLang, $wgContLang;
415 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
419 * Replaces all occurrences of HTML-style comments and the given tags
420 * in the text with a random marker and returns teh next text. The output
421 * parameter $matches will be an associative array filled with data in
423 * 'UNIQ-xxxxx' => array(
426 * array( 'param' => 'x' ),
427 * '<element param="x">tag content</element>' ) )
429 * @param $elements list of element names. Comments are always extracted.
430 * @param $text Source text string.
431 * @param $uniq_prefix
436 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
441 $taglist = implode( '|', $elements );
442 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
444 while ( '' != $text ) {
445 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
447 if( count( $p ) < 5 ) {
450 if( count( $p ) > 5 ) {
464 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
465 $stripped .= $marker;
467 if ( $close === '/>' ) {
468 // Empty element tag, <tag />
473 if( $element == '!--' ) {
476 $end = "/(<\\/$element\\s*>)/i";
478 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
480 if( count( $q ) < 3 ) {
481 # No end tag -- let it run out to the end of the text.
490 $matches[$marker] = array( $element,
492 Sanitizer
::decodeTagAttributes( $attributes ),
493 "<$element$attributes$close$content$tail" );
499 * Strips and renders nowiki, pre, math, hiero
500 * If $render is set, performs necessary rendering operations on plugins
501 * Returns the text, and fills an array with data needed in unstrip()
503 * @param StripState $state
505 * @param bool $stripcomments when set, HTML comments <!-- like this -->
506 * will be stripped in addition to other tags. This is important
507 * for section editing, where these comments cause confusion when
508 * counting the sections in the wikisource
510 * @param array dontstrip contains tags which should not be stripped;
511 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
515 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
517 wfProfileIn( __METHOD__
);
518 $render = ($this->mOutputType
== self
::OT_HTML
);
520 $uniq_prefix = $this->mUniqPrefix
;
521 $commentState = new ReplacementArray
;
522 $nowikiItems = array();
523 $generalItems = array();
525 $elements = array_merge(
526 array( 'nowiki', 'gallery' ),
527 array_keys( $this->mTagHooks
) );
530 $elements[] = 'html';
532 if( $this->mOptions
->getUseTeX() ) {
533 $elements[] = 'math';
536 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
537 foreach ( $elements AS $k => $v ) {
538 if ( !in_array ( $v , $dontstrip ) ) continue;
539 unset ( $elements[$k] );
543 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
545 foreach( $matches as $marker => $data ) {
546 list( $element, $content, $params, $tag ) = $data;
548 $tagName = strtolower( $element );
549 wfProfileIn( __METHOD__
."-render-$tagName" );
553 if( substr( $tag, -3 ) == '-->' ) {
556 // Unclosed comment in input.
557 // Close it so later stripping can remove it
566 // Shouldn't happen otherwise. :)
568 $output = Xml
::escapeTagsOnly( $content );
571 $output = $wgContLang->armourMath(
572 MathRenderer
::renderMath( $content, $params ) );
575 $output = $this->renderImageGallery( $content, $params );
578 if( isset( $this->mTagHooks
[$tagName] ) ) {
579 $output = call_user_func_array( $this->mTagHooks
[$tagName],
580 array( $content, $params, $this ) );
582 throw new MWException( "Invalid call hook $element" );
585 wfProfileOut( __METHOD__
."-render-$tagName" );
587 // Just stripping tags; keep the source
591 // Unstrip the output, to support recursive strip() calls
592 $output = $state->unstripBoth( $output );
594 if( !$stripcomments && $element == '!--' ) {
595 $commentState->setPair( $marker, $output );
596 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
597 $nowikiItems[$marker] = $output;
599 $generalItems[$marker] = $output;
602 # Add the new items to the state
603 # We do this after the loop instead of during it to avoid slowing
604 # down the recursive unstrip
605 $state->nowiki
->mergeArray( $nowikiItems );
606 $state->general
->mergeArray( $generalItems );
608 # Unstrip comments unless explicitly told otherwise.
609 # (The comments are always stripped prior to this point, so as to
610 # not invoke any extension tags / parser hooks contained within
612 if ( !$stripcomments ) {
613 // Put them all back and forget them
614 $text = $commentState->replace( $text );
617 wfProfileOut( __METHOD__
);
622 * Restores pre, math, and other extensions removed by strip()
624 * always call unstripNoWiki() after this one
626 * @deprecated use $this->mStripState->unstrip()
628 function unstrip( $text, $state ) {
629 return $state->unstripGeneral( $text );
633 * Always call this after unstrip() to preserve the order
636 * @deprecated use $this->mStripState->unstrip()
638 function unstripNoWiki( $text, $state ) {
639 return $state->unstripNoWiki( $text );
643 * @deprecated use $this->mStripState->unstripBoth()
645 function unstripForHTML( $text ) {
646 return $this->mStripState
->unstripBoth( $text );
650 * Add an item to the strip state
651 * Returns the unique tag which must be inserted into the stripped text
652 * The tag will be replaced with the original text in unstrip()
656 function insertStripItem( $text, &$state ) {
657 $rnd = $this->mUniqPrefix
. '-item' . self
::getRandomString();
658 $state->general
->setPair( $rnd, $text );
663 * Interface with html tidy, used if $wgUseTidy = true.
664 * If tidy isn't able to correct the markup, the original will be
665 * returned in all its glory with a warning comment appended.
667 * Either the external tidy program or the in-process tidy extension
668 * will be used depending on availability. Override the default
669 * $wgTidyInternal setting to disable the internal if it's not working.
671 * @param string $text Hideous HTML input
672 * @return string Corrected HTML output
676 function tidy( $text ) {
677 global $wgTidyInternal;
678 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
679 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
680 '<head><title>test</title></head><body>'.$text.'</body></html>';
681 if( $wgTidyInternal ) {
682 $correctedtext = self
::internalTidy( $wrappedtext );
684 $correctedtext = self
::externalTidy( $wrappedtext );
686 if( is_null( $correctedtext ) ) {
687 wfDebug( "Tidy error detected!\n" );
688 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
690 return $correctedtext;
694 * Spawn an external HTML tidy process and get corrected markup back from it.
699 function externalTidy( $text ) {
700 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
701 $fname = 'Parser::externalTidy';
702 wfProfileIn( $fname );
707 $descriptorspec = array(
708 0 => array('pipe', 'r'),
709 1 => array('pipe', 'w'),
710 2 => array('file', wfGetNull(), 'a')
713 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
714 if (is_resource($process)) {
715 // Theoretically, this style of communication could cause a deadlock
716 // here. If the stdout buffer fills up, then writes to stdin could
717 // block. This doesn't appear to happen with tidy, because tidy only
718 // writes to stdout after it's finished reading from stdin. Search
719 // for tidyParseStdin and tidySaveStdout in console/tidy.c
720 fwrite($pipes[0], $text);
722 while (!feof($pipes[1])) {
723 $cleansource .= fgets($pipes[1], 1024);
726 proc_close($process);
729 wfProfileOut( $fname );
731 if( $cleansource == '' && $text != '') {
732 // Some kind of error happened, so we couldn't get the corrected text.
733 // Just give up; we'll use the source text and append a warning.
741 * Use the HTML tidy PECL extension to use the tidy library in-process,
742 * saving the overhead of spawning a new process.
744 * 'pear install tidy' should be able to compile the extension module.
749 function internalTidy( $text ) {
750 global $wgTidyConf, $IP;
751 $fname = 'Parser::internalTidy';
752 wfProfileIn( $fname );
755 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
756 $tidy->cleanRepair();
757 if( $tidy->getStatus() == 2 ) {
758 // 2 is magic number for fatal error
759 // http://www.php.net/manual/en/function.tidy-get-status.php
762 $cleansource = tidy_get_output( $tidy );
764 wfProfileOut( $fname );
769 * parse the wiki syntax used to render tables
773 function doTableStuff ( $text ) {
774 $fname = 'Parser::doTableStuff';
775 wfProfileIn( $fname );
777 $lines = explode ( "\n" , $text );
778 $td_history = array (); // Is currently a td tag open?
779 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
780 $tr_history = array (); // Is currently a tr tag open?
781 $tr_attributes = array (); // history of tr attributes
782 $has_opened_tr = array(); // Did this table open a <tr> element?
783 $indent_level = 0; // indent level of the table
784 foreach ( $lines as $key => $line )
786 $line = trim ( $line );
788 if( $line == '' ) { // empty line, go to next line
791 $first_character = $line{0};
794 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
795 // First check if we are starting a new table
796 $indent_level = strlen( $matches[1] );
798 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
799 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
801 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
802 array_push ( $td_history , false );
803 array_push ( $last_tag_history , '' );
804 array_push ( $tr_history , false );
805 array_push ( $tr_attributes , '' );
806 array_push ( $has_opened_tr , false );
807 } else if ( count ( $td_history ) == 0 ) {
808 // Don't do any of the following
810 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
811 // We are ending a table
812 $line = '</table>' . substr ( $line , 2 );
813 $last_tag = array_pop ( $last_tag_history );
815 if ( !array_pop ( $has_opened_tr ) ) {
816 $line = "<tr><td></td></tr>{$line}";
819 if ( array_pop ( $tr_history ) ) {
820 $line = "</tr>{$line}";
823 if ( array_pop ( $td_history ) ) {
824 $line = "</{$last_tag}>{$line}";
826 array_pop ( $tr_attributes );
827 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
828 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
829 // Now we have a table row
830 $line = preg_replace( '#^\|-+#', '', $line );
832 // Whats after the tag is now only attributes
833 $attributes = $this->mStripState
->unstripBoth( $line );
834 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
835 array_pop ( $tr_attributes );
836 array_push ( $tr_attributes , $attributes );
839 $last_tag = array_pop ( $last_tag_history );
840 array_pop ( $has_opened_tr );
841 array_push ( $has_opened_tr , true );
843 if ( array_pop ( $tr_history ) ) {
847 if ( array_pop ( $td_history ) ) {
848 $line = "</{$last_tag}>{$line}";
851 $lines[$key] = $line;
852 array_push ( $tr_history , false );
853 array_push ( $td_history , false );
854 array_push ( $last_tag_history , '' );
856 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
857 // This might be cell elements, td, th or captions
858 if ( substr ( $line , 0 , 2 ) == '|+' ) {
859 $first_character = '+';
860 $line = substr ( $line , 1 );
863 $line = substr ( $line , 1 );
865 if ( $first_character == '!' ) {
866 $line = str_replace ( '!!' , '||' , $line );
869 // Split up multiple cells on the same line.
870 // FIXME : This can result in improper nesting of tags processed
871 // by earlier parser steps, but should avoid splitting up eg
872 // attribute values containing literal "||".
873 $cells = StringUtils
::explodeMarkup( '||' , $line );
877 // Loop through each table cell
878 foreach ( $cells as $cell )
881 if ( $first_character != '+' )
883 $tr_after = array_pop ( $tr_attributes );
884 if ( !array_pop ( $tr_history ) ) {
885 $previous = "<tr{$tr_after}>\n";
887 array_push ( $tr_history , true );
888 array_push ( $tr_attributes , '' );
889 array_pop ( $has_opened_tr );
890 array_push ( $has_opened_tr , true );
893 $last_tag = array_pop ( $last_tag_history );
895 if ( array_pop ( $td_history ) ) {
896 $previous = "</{$last_tag}>{$previous}";
899 if ( $first_character == '|' ) {
901 } else if ( $first_character == '!' ) {
903 } else if ( $first_character == '+' ) {
904 $last_tag = 'caption';
909 array_push ( $last_tag_history , $last_tag );
911 // A cell could contain both parameters and data
912 $cell_data = explode ( '|' , $cell , 2 );
914 // Bug 553: Note that a '|' inside an invalid link should not
915 // be mistaken as delimiting cell parameters
916 if ( strpos( $cell_data[0], '[[' ) !== false ) {
917 $cell = "{$previous}<{$last_tag}>{$cell}";
918 } else if ( count ( $cell_data ) == 1 )
919 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
921 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
922 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
923 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
926 $lines[$key] .= $cell;
927 array_push ( $td_history , true );
932 // Closing open td, tr && table
933 while ( count ( $td_history ) > 0 )
935 if ( array_pop ( $td_history ) ) {
938 if ( array_pop ( $tr_history ) ) {
941 if ( !array_pop ( $has_opened_tr ) ) {
942 $lines[] = "<tr><td></td></tr>" ;
945 $lines[] = '</table>' ;
948 $output = implode ( "\n" , $lines ) ;
950 // special case: don't return empty table
951 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
955 wfProfileOut( $fname );
961 * Helper function for parse() that transforms wiki markup into
962 * HTML. Only called for $mOutputType == OT_HTML.
966 function internalParse( $text ) {
969 $fname = 'Parser::internalParse';
970 wfProfileIn( $fname );
972 # Hook to suspend the parser in this state
973 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
974 wfProfileOut( $fname );
978 # Remove <noinclude> tags and <includeonly> sections
979 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
980 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
981 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
983 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
985 $text = $this->replaceVariables( $text, $args );
986 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
988 // Tables need to come after variable replacement for things to work
989 // properly; putting them before other transformations should keep
990 // exciting things like link expansions from showing up in surprising
992 $text = $this->doTableStuff( $text );
994 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
996 $text = $this->stripToc( $text );
997 $this->stripNoGallery( $text );
998 $text = $this->doHeadings( $text );
999 if($this->mOptions
->getUseDynamicDates()) {
1000 $df =& DateFormatter
::getInstance();
1001 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1003 $text = $this->doAllQuotes( $text );
1004 $text = $this->replaceInternalLinks( $text );
1005 $text = $this->replaceExternalLinks( $text );
1007 # replaceInternalLinks may sometimes leave behind
1008 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1009 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1011 $text = $this->doMagicLinks( $text );
1012 $text = $this->formatHeadings( $text, $isMain );
1014 wfProfileOut( $fname );
1019 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1020 * magic external links.
1024 function &doMagicLinks( &$text ) {
1025 wfProfileIn( __METHOD__
);
1026 $text = preg_replace_callback(
1028 <a.*?</a> | # Skip link text
1029 <.*?> | # Skip stuff inside HTML elements
1030 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1031 ISBN\s+(\b # ISBN, capture number as m[2]
1032 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1033 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1034 [0-9Xx] # check digit
1036 )!x', array( &$this, 'magicLinkCallback' ), $text );
1037 wfProfileOut( __METHOD__
);
1041 function magicLinkCallback( $m ) {
1042 if ( substr( $m[0], 0, 1 ) == '<' ) {
1045 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1047 $num = strtr( $isbn, array(
1052 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1053 $text = '<a href="' .
1054 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1055 "\" class=\"internal\">ISBN $isbn</a>";
1057 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1061 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1063 $urlmsg = 'pubmedurl';
1066 throw new MWException( __METHOD__
.': unrecognised match type "' .
1067 substr($m[0], 0, 20 ) . '"' );
1070 $url = wfMsg( $urlmsg, $id);
1071 $sk = $this->mOptions
->getSkin();
1072 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1073 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1079 * Parse headers and return html
1083 function doHeadings( $text ) {
1084 $fname = 'Parser::doHeadings';
1085 wfProfileIn( $fname );
1086 for ( $i = 6; $i >= 1; --$i ) {
1087 $h = str_repeat( '=', $i );
1088 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1089 "<h{$i}>\\1</h{$i}>\\2", $text );
1091 wfProfileOut( $fname );
1096 * Replace single quotes with HTML markup
1098 * @return string the altered text
1100 function doAllQuotes( $text ) {
1101 $fname = 'Parser::doAllQuotes';
1102 wfProfileIn( $fname );
1104 $lines = explode( "\n", $text );
1105 foreach ( $lines as $line ) {
1106 $outtext .= $this->doQuotes ( $line ) . "\n";
1108 $outtext = substr($outtext, 0,-1);
1109 wfProfileOut( $fname );
1114 * Helper function for doAllQuotes()
1116 public function doQuotes( $text ) {
1117 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1118 if ( count( $arr ) == 1 )
1122 # First, do some preliminary work. This may shift some apostrophes from
1123 # being mark-up to being text. It also counts the number of occurrences
1124 # of bold and italics mark-ups.
1128 foreach ( $arr as $r )
1130 if ( ( $i %
2 ) == 1 )
1132 # If there are ever four apostrophes, assume the first is supposed to
1133 # be text, and the remaining three constitute mark-up for bold text.
1134 if ( strlen( $arr[$i] ) == 4 )
1139 # If there are more than 5 apostrophes in a row, assume they're all
1140 # text except for the last 5.
1141 else if ( strlen( $arr[$i] ) > 5 )
1143 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1146 # Count the number of occurrences of bold and italics mark-ups.
1147 # We are not counting sequences of five apostrophes.
1148 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1149 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1150 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1155 # If there is an odd number of both bold and italics, it is likely
1156 # that one of the bold ones was meant to be an apostrophe followed
1157 # by italics. Which one we cannot know for certain, but it is more
1158 # likely to be one that has a single-letter word before it.
1159 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1162 $firstsingleletterword = -1;
1163 $firstmultiletterword = -1;
1165 foreach ( $arr as $r )
1167 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1169 $x1 = substr ($arr[$i-1], -1);
1170 $x2 = substr ($arr[$i-1], -2, 1);
1172 if ($firstspace == -1) $firstspace = $i;
1173 } else if ($x2 == ' ') {
1174 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1176 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1182 # If there is a single-letter word, use it!
1183 if ($firstsingleletterword > -1)
1185 $arr [ $firstsingleletterword ] = "''";
1186 $arr [ $firstsingleletterword-1 ] .= "'";
1188 # If not, but there's a multi-letter word, use that one.
1189 else if ($firstmultiletterword > -1)
1191 $arr [ $firstmultiletterword ] = "''";
1192 $arr [ $firstmultiletterword-1 ] .= "'";
1194 # ... otherwise use the first one that has neither.
1195 # (notice that it is possible for all three to be -1 if, for example,
1196 # there is only one pentuple-apostrophe in the line)
1197 else if ($firstspace > -1)
1199 $arr [ $firstspace ] = "''";
1200 $arr [ $firstspace-1 ] .= "'";
1204 # Now let's actually convert our apostrophic mush to HTML!
1209 foreach ($arr as $r)
1213 if ($state == 'both')
1220 if (strlen ($r) == 2)
1223 { $output .= '</i>'; $state = ''; }
1224 else if ($state == 'bi')
1225 { $output .= '</i>'; $state = 'b'; }
1226 else if ($state == 'ib')
1227 { $output .= '</b></i><b>'; $state = 'b'; }
1228 else if ($state == 'both')
1229 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1230 else # $state can be 'b' or ''
1231 { $output .= '<i>'; $state .= 'i'; }
1233 else if (strlen ($r) == 3)
1236 { $output .= '</b>'; $state = ''; }
1237 else if ($state == 'bi')
1238 { $output .= '</i></b><i>'; $state = 'i'; }
1239 else if ($state == 'ib')
1240 { $output .= '</b>'; $state = 'i'; }
1241 else if ($state == 'both')
1242 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1243 else # $state can be 'i' or ''
1244 { $output .= '<b>'; $state .= 'b'; }
1246 else if (strlen ($r) == 5)
1249 { $output .= '</b><i>'; $state = 'i'; }
1250 else if ($state == 'i')
1251 { $output .= '</i><b>'; $state = 'b'; }
1252 else if ($state == 'bi')
1253 { $output .= '</i></b>'; $state = ''; }
1254 else if ($state == 'ib')
1255 { $output .= '</b></i>'; $state = ''; }
1256 else if ($state == 'both')
1257 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1258 else # ($state == '')
1259 { $buffer = ''; $state = 'both'; }
1264 # Now close all remaining tags. Notice that the order is important.
1265 if ($state == 'b' ||
$state == 'ib')
1267 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1271 # There might be lonely ''''', so make sure we have a buffer
1272 if ($state == 'both' && $buffer)
1273 $output .= '<b><i>'.$buffer.'</i></b>';
1279 * Replace external links
1281 * Note: this is all very hackish and the order of execution matters a lot.
1282 * Make sure to run maintenance/parserTests.php if you change this code.
1286 function replaceExternalLinks( $text ) {
1288 $fname = 'Parser::replaceExternalLinks';
1289 wfProfileIn( $fname );
1291 $sk = $this->mOptions
->getSkin();
1293 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1295 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1298 while ( $i<count( $bits ) ) {
1300 $protocol = $bits[$i++
];
1301 $text = $bits[$i++
];
1302 $trail = $bits[$i++
];
1304 # The characters '<' and '>' (which were escaped by
1305 # removeHTMLtags()) should not be included in
1306 # URLs, per RFC 2396.
1308 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1309 $text = substr($url, $m2[0][1]) . ' ' . $text;
1310 $url = substr($url, 0, $m2[0][1]);
1313 # If the link text is an image URL, replace it with an <img> tag
1314 # This happened by accident in the original parser, but some people used it extensively
1315 $img = $this->maybeMakeExternalImage( $text );
1316 if ( $img !== false ) {
1322 # Set linktype for CSS - if URL==text, link is essentially free
1323 $linktype = ($text == $url) ?
'free' : 'text';
1325 # No link text, e.g. [http://domain.tld/some.link]
1326 if ( $text == '' ) {
1327 # Autonumber if allowed. See bug #5918
1328 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1329 $text = '[' . ++
$this->mAutonumber
. ']';
1330 $linktype = 'autonumber';
1332 # Otherwise just use the URL
1333 $text = htmlspecialchars( $url );
1337 # Have link text, e.g. [http://domain.tld/some.link text]s
1339 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1342 $text = $wgContLang->markNoConversion($text);
1344 $url = Sanitizer
::cleanUrl( $url );
1346 # Process the trail (i.e. everything after this link up until start of the next link),
1347 # replacing any non-bracketed links
1348 $trail = $this->replaceFreeExternalLinks( $trail );
1350 # Use the encoded URL
1351 # This means that users can paste URLs directly into the text
1352 # Funny characters like ö aren't valid in URLs anyway
1353 # This was changed in August 2004
1354 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1356 # Register link in the output object.
1357 # Replace unnecessary URL escape codes with the referenced character
1358 # This prevents spammers from hiding links from the filters
1359 $pasteurized = self
::replaceUnusualEscapes( $url );
1360 $this->mOutput
->addExternalLink( $pasteurized );
1363 wfProfileOut( $fname );
1368 * Replace anything that looks like a URL with a link
1371 function replaceFreeExternalLinks( $text ) {
1373 $fname = 'Parser::replaceFreeExternalLinks';
1374 wfProfileIn( $fname );
1376 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1377 $s = array_shift( $bits );
1380 $sk = $this->mOptions
->getSkin();
1382 while ( $i < count( $bits ) ){
1383 $protocol = $bits[$i++
];
1384 $remainder = $bits[$i++
];
1387 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1388 # Found some characters after the protocol that look promising
1389 $url = $protocol . $m[1];
1392 # special case: handle urls as url args:
1393 # http://www.example.com/foo?=http://www.example.com/bar
1394 if(strlen($trail) == 0 &&
1396 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1397 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1400 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1405 # The characters '<' and '>' (which were escaped by
1406 # removeHTMLtags()) should not be included in
1407 # URLs, per RFC 2396.
1409 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1410 $trail = substr($url, $m2[0][1]) . $trail;
1411 $url = substr($url, 0, $m2[0][1]);
1414 # Move trailing punctuation to $trail
1416 # If there is no left bracket, then consider right brackets fair game too
1417 if ( strpos( $url, '(' ) === false ) {
1421 $numSepChars = strspn( strrev( $url ), $sep );
1422 if ( $numSepChars ) {
1423 $trail = substr( $url, -$numSepChars ) . $trail;
1424 $url = substr( $url, 0, -$numSepChars );
1427 $url = Sanitizer
::cleanUrl( $url );
1429 # Is this an external image?
1430 $text = $this->maybeMakeExternalImage( $url );
1431 if ( $text === false ) {
1432 # Not an image, make a link
1433 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1434 # Register it in the output object...
1435 # Replace unnecessary URL escape codes with their equivalent characters
1436 $pasteurized = self
::replaceUnusualEscapes( $url );
1437 $this->mOutput
->addExternalLink( $pasteurized );
1439 $s .= $text . $trail;
1441 $s .= $protocol . $remainder;
1444 wfProfileOut( $fname );
1449 * Replace unusual URL escape codes with their equivalent characters
1453 * @todo This can merge genuinely required bits in the path or query string,
1454 * breaking legit URLs. A proper fix would treat the various parts of
1455 * the URL differently; as a workaround, just use the output for
1456 * statistical records, not for actual linking/output.
1458 static function replaceUnusualEscapes( $url ) {
1459 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1460 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1464 * Callback function used in replaceUnusualEscapes().
1465 * Replaces unusual URL escape codes with their equivalent character
1469 private static function replaceUnusualEscapesCallback( $matches ) {
1470 $char = urldecode( $matches[0] );
1471 $ord = ord( $char );
1472 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1473 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1474 // No, shouldn't be escaped
1477 // Yes, leave it escaped
1483 * make an image if it's allowed, either through the global
1484 * option or through the exception
1487 function maybeMakeExternalImage( $url ) {
1488 $sk = $this->mOptions
->getSkin();
1489 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1490 $imagesexception = !empty($imagesfrom);
1492 if ( $this->mOptions
->getAllowExternalImages()
1493 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1494 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1496 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1503 * Process [[ ]] wikilinks
1507 function replaceInternalLinks( $s ) {
1509 static $fname = 'Parser::replaceInternalLinks' ;
1511 wfProfileIn( $fname );
1513 wfProfileIn( $fname.'-setup' );
1515 # the % is needed to support urlencoded titles as well
1516 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1518 $sk = $this->mOptions
->getSkin();
1520 #split the entire text string on occurences of [[
1521 $a = explode( '[[', ' ' . $s );
1522 #get the first element (all text up to first [[), and remove the space we added
1523 $s = array_shift( $a );
1524 $s = substr( $s, 1 );
1526 # Match a link having the form [[namespace:link|alternate]]trail
1528 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1529 # Match cases where there is no "]]", which might still be images
1530 static $e1_img = FALSE;
1531 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1532 # Match the end of a line for a word that's not followed by whitespace,
1533 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1534 $e2 = wfMsgForContent( 'linkprefix' );
1536 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1537 if( is_null( $this->mTitle
) ) {
1538 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1540 $nottalk = !$this->mTitle
->isTalkPage();
1542 if ( $useLinkPrefixExtension ) {
1544 if ( preg_match( $e2, $s, $m ) ) {
1545 $first_prefix = $m[2];
1547 $first_prefix = false;
1553 if($wgContLang->hasVariants()) {
1554 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1556 $selflink = array($this->mTitle
->getPrefixedText());
1558 $useSubpages = $this->areSubpagesAllowed();
1559 wfProfileOut( $fname.'-setup' );
1561 # Loop for each link
1562 for ($k = 0; isset( $a[$k] ); $k++
) {
1564 if ( $useLinkPrefixExtension ) {
1565 wfProfileIn( $fname.'-prefixhandling' );
1566 if ( preg_match( $e2, $s, $m ) ) {
1574 $prefix = $first_prefix;
1575 $first_prefix = false;
1577 wfProfileOut( $fname.'-prefixhandling' );
1580 $might_be_img = false;
1582 wfProfileIn( "$fname-e1" );
1583 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1585 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1586 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1587 # the real problem is with the $e1 regex
1590 # Still some problems for cases where the ] is meant to be outside punctuation,
1591 # and no image is in sight. See bug 2095.
1594 substr( $m[3], 0, 1 ) === ']' &&
1595 strpos($text, '[') !== false
1598 $text .= ']'; # so that replaceExternalLinks($text) works later
1599 $m[3] = substr( $m[3], 1 );
1601 # fix up urlencoded title texts
1602 if( strpos( $m[1], '%' ) !== false ) {
1603 # Should anchors '#' also be rejected?
1604 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1607 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1608 $might_be_img = true;
1610 if ( strpos( $m[1], '%' ) !== false ) {
1611 $m[1] = urldecode($m[1]);
1614 } else { # Invalid form; output directly
1615 $s .= $prefix . '[[' . $line ;
1616 wfProfileOut( "$fname-e1" );
1619 wfProfileOut( "$fname-e1" );
1620 wfProfileIn( "$fname-misc" );
1622 # Don't allow internal links to pages containing
1623 # PROTO: where PROTO is a valid URL protocol; these
1624 # should be external links.
1625 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1626 $s .= $prefix . '[[' . $line ;
1630 # Make subpage if necessary
1631 if( $useSubpages ) {
1632 $link = $this->maybeDoSubpageLink( $m[1], $text );
1637 $noforce = (substr($m[1], 0, 1) != ':');
1639 # Strip off leading ':'
1640 $link = substr($link, 1);
1643 wfProfileOut( "$fname-misc" );
1644 wfProfileIn( "$fname-title" );
1645 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1647 $s .= $prefix . '[[' . $line;
1648 wfProfileOut( "$fname-title" );
1652 $ns = $nt->getNamespace();
1653 $iw = $nt->getInterWiki();
1654 wfProfileOut( "$fname-title" );
1656 if ($might_be_img) { # if this is actually an invalid link
1657 wfProfileIn( "$fname-might_be_img" );
1658 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1660 while (isset ($a[$k+
1]) ) {
1661 #look at the next 'line' to see if we can close it there
1662 $spliced = array_splice( $a, $k +
1, 1 );
1663 $next_line = array_shift( $spliced );
1664 $m = explode( ']]', $next_line, 3 );
1665 if ( count( $m ) == 3 ) {
1666 # the first ]] closes the inner link, the second the image
1668 $text .= "[[{$m[0]}]]{$m[1]}";
1671 } elseif ( count( $m ) == 2 ) {
1672 #if there's exactly one ]] that's fine, we'll keep looking
1673 $text .= "[[{$m[0]}]]{$m[1]}";
1675 #if $next_line is invalid too, we need look no further
1676 $text .= '[[' . $next_line;
1681 # we couldn't find the end of this imageLink, so output it raw
1682 #but don't ignore what might be perfectly normal links in the text we've examined
1683 $text = $this->replaceInternalLinks($text);
1684 $s .= "{$prefix}[[$link|$text";
1685 # note: no $trail, because without an end, there *is* no trail
1686 wfProfileOut( "$fname-might_be_img" );
1689 } else { #it's not an image, so output it raw
1690 $s .= "{$prefix}[[$link|$text";
1691 # note: no $trail, because without an end, there *is* no trail
1692 wfProfileOut( "$fname-might_be_img" );
1695 wfProfileOut( "$fname-might_be_img" );
1698 $wasblank = ( '' == $text );
1699 if( $wasblank ) $text = $link;
1701 # Link not escaped by : , create the various objects
1705 wfProfileIn( "$fname-interwiki" );
1706 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1707 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1708 $s = rtrim($s . $prefix);
1709 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1710 wfProfileOut( "$fname-interwiki" );
1713 wfProfileOut( "$fname-interwiki" );
1715 if ( $ns == NS_IMAGE
) {
1716 wfProfileIn( "$fname-image" );
1717 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1718 # recursively parse links inside the image caption
1719 # actually, this will parse them in any other parameters, too,
1720 # but it might be hard to fix that, and it doesn't matter ATM
1721 $text = $this->replaceExternalLinks($text);
1722 $text = $this->replaceInternalLinks($text);
1724 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1725 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1726 $this->mOutput
->addImage( $nt->getDBkey() );
1728 wfProfileOut( "$fname-image" );
1731 # We still need to record the image's presence on the page
1732 $this->mOutput
->addImage( $nt->getDBkey() );
1734 wfProfileOut( "$fname-image" );
1738 if ( $ns == NS_CATEGORY
) {
1739 wfProfileIn( "$fname-category" );
1740 $s = rtrim($s . "\n"); # bug 87
1743 $sortkey = $this->getDefaultSort();
1747 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1748 $sortkey = str_replace( "\n", '', $sortkey );
1749 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1750 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1753 * Strip the whitespace Category links produce, see bug 87
1754 * @todo We might want to use trim($tmp, "\n") here.
1756 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1758 wfProfileOut( "$fname-category" );
1763 # Self-link checking
1764 if( $nt->getFragment() === '' ) {
1765 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1766 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1771 # Special and Media are pseudo-namespaces; no pages actually exist in them
1772 if( $ns == NS_MEDIA
) {
1773 $link = $sk->makeMediaLinkObj( $nt, $text );
1774 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1775 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1776 $this->mOutput
->addImage( $nt->getDBkey() );
1778 } elseif( $ns == NS_SPECIAL
) {
1779 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1780 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1782 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1785 } elseif( $ns == NS_IMAGE
) {
1786 $img = wfFindFile( $nt );
1788 // Force a blue link if the file exists; may be a remote
1789 // upload on the shared repository, and we want to see its
1790 // auto-generated page.
1791 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1792 $this->mOutput
->addLink( $nt );
1796 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1798 wfProfileOut( $fname );
1803 * Make a link placeholder. The text returned can be later resolved to a real link with
1804 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1805 * parsing of interwiki links, and secondly to allow all existence checks and
1806 * article length checks (for stub links) to be bundled into a single query.
1809 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1810 wfProfileIn( __METHOD__
);
1811 if ( ! is_object($nt) ) {
1813 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1815 # Separate the link trail from the rest of the link
1816 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1818 if ( $nt->isExternal() ) {
1819 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1820 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1821 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1823 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1824 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1825 $this->mLinkHolders
['queries'][] = $query;
1826 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1827 $this->mLinkHolders
['titles'][] = $nt;
1829 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1832 wfProfileOut( __METHOD__
);
1837 * Render a forced-blue link inline; protect against double expansion of
1838 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1839 * Since this little disaster has to split off the trail text to avoid
1840 * breaking URLs in the following text without breaking trails on the
1841 * wiki links, it's been made into a horrible function.
1844 * @param string $text
1845 * @param string $query
1846 * @param string $trail
1847 * @param string $prefix
1848 * @return string HTML-wikitext mix oh yuck
1850 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1851 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1852 $sk = $this->mOptions
->getSkin();
1853 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1854 return $this->armorLinks( $link ) . $trail;
1858 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1859 * going to go through further parsing steps before inline URL expansion.
1861 * In particular this is important when using action=render, which causes
1862 * full URLs to be included.
1864 * Oh man I hate our multi-layer parser!
1866 * @param string more-or-less HTML
1867 * @return string less-or-more HTML with NOPARSE bits
1869 function armorLinks( $text ) {
1870 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1871 "{$this->mUniqPrefix}NOPARSE$1", $text );
1875 * Return true if subpage links should be expanded on this page.
1878 function areSubpagesAllowed() {
1879 # Some namespaces don't allow subpages
1880 global $wgNamespacesWithSubpages;
1881 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1885 * Handle link to subpage if necessary
1886 * @param string $target the source of the link
1887 * @param string &$text the link text, modified as necessary
1888 * @return string the full name of the link
1891 function maybeDoSubpageLink($target, &$text) {
1894 # :Foobar -- override special treatment of prefix (images, language links)
1895 # /Foobar -- convert to CurrentPage/Foobar
1896 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1897 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1898 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1900 $fname = 'Parser::maybeDoSubpageLink';
1901 wfProfileIn( $fname );
1902 $ret = $target; # default return value is no change
1904 # Some namespaces don't allow subpages,
1905 # so only perform processing if subpages are allowed
1906 if( $this->areSubpagesAllowed() ) {
1907 $hash = strpos( $target, '#' );
1908 if( $hash !== false ) {
1909 $suffix = substr( $target, $hash );
1910 $target = substr( $target, 0, $hash );
1915 $target = trim( $target );
1916 # Look at the first character
1917 if( $target != '' && $target{0} == '/' ) {
1918 # / at end means we don't want the slash to be shown
1920 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1921 if( $trailingSlashes ) {
1922 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1924 $noslash = substr( $target, 1 );
1927 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1928 if( '' === $text ) {
1929 $text = $target . $suffix;
1930 } # this might be changed for ugliness reasons
1932 # check for .. subpage backlinks
1934 $nodotdot = $target;
1935 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1937 $nodotdot = substr( $nodotdot, 3 );
1939 if($dotdotcount > 0) {
1940 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1941 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1942 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1943 # / at the end means don't show full path
1944 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1945 $nodotdot = substr( $nodotdot, 0, -1 );
1946 if( '' === $text ) {
1947 $text = $nodotdot . $suffix;
1950 $nodotdot = trim( $nodotdot );
1951 if( $nodotdot != '' ) {
1952 $ret .= '/' . $nodotdot;
1960 wfProfileOut( $fname );
1965 * Used by doBlockLevels()
1968 /* private */ function closeParagraph() {
1970 if ( '' != $this->mLastSection
) {
1971 $result = '</' . $this->mLastSection
. ">\n";
1973 $this->mInPre
= false;
1974 $this->mLastSection
= '';
1977 # getCommon() returns the length of the longest common substring
1978 # of both arguments, starting at the beginning of both.
1980 /* private */ function getCommon( $st1, $st2 ) {
1981 $fl = strlen( $st1 );
1982 $shorter = strlen( $st2 );
1983 if ( $fl < $shorter ) { $shorter = $fl; }
1985 for ( $i = 0; $i < $shorter; ++
$i ) {
1986 if ( $st1{$i} != $st2{$i} ) { break; }
1990 # These next three functions open, continue, and close the list
1991 # element appropriate to the prefix character passed into them.
1993 /* private */ function openList( $char ) {
1994 $result = $this->closeParagraph();
1996 if ( '*' == $char ) { $result .= '<ul><li>'; }
1997 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1998 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1999 else if ( ';' == $char ) {
2000 $result .= '<dl><dt>';
2001 $this->mDTopen
= true;
2003 else { $result = '<!-- ERR 1 -->'; }
2008 /* private */ function nextItem( $char ) {
2009 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2010 else if ( ':' == $char ||
';' == $char ) {
2012 if ( $this->mDTopen
) { $close = '</dt>'; }
2013 if ( ';' == $char ) {
2014 $this->mDTopen
= true;
2015 return $close . '<dt>';
2017 $this->mDTopen
= false;
2018 return $close . '<dd>';
2021 return '<!-- ERR 2 -->';
2024 /* private */ function closeList( $char ) {
2025 if ( '*' == $char ) { $text = '</li></ul>'; }
2026 else if ( '#' == $char ) { $text = '</li></ol>'; }
2027 else if ( ':' == $char ) {
2028 if ( $this->mDTopen
) {
2029 $this->mDTopen
= false;
2030 $text = '</dt></dl>';
2032 $text = '</dd></dl>';
2035 else { return '<!-- ERR 3 -->'; }
2041 * Make lists from lines starting with ':', '*', '#', etc.
2044 * @return string the lists rendered as HTML
2046 function doBlockLevels( $text, $linestart ) {
2047 $fname = 'Parser::doBlockLevels';
2048 wfProfileIn( $fname );
2050 # Parsing through the text line by line. The main thing
2051 # happening here is handling of block-level elements p, pre,
2052 # and making lists from lines starting with * # : etc.
2054 $textLines = explode( "\n", $text );
2056 $lastPrefix = $output = '';
2057 $this->mDTopen
= $inBlockElem = false;
2059 $paragraphStack = false;
2061 if ( !$linestart ) {
2062 $output .= array_shift( $textLines );
2064 foreach ( $textLines as $oLine ) {
2065 $lastPrefixLength = strlen( $lastPrefix );
2066 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2067 $preOpenMatch = preg_match('/<pre/i', $oLine );
2068 if ( !$this->mInPre
) {
2069 # Multiple prefixes may abut each other for nested lists.
2070 $prefixLength = strspn( $oLine, '*#:;' );
2071 $pref = substr( $oLine, 0, $prefixLength );
2074 $pref2 = str_replace( ';', ':', $pref );
2075 $t = substr( $oLine, $prefixLength );
2076 $this->mInPre
= !empty($preOpenMatch);
2078 # Don't interpret any other prefixes in preformatted text
2080 $pref = $pref2 = '';
2085 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2086 # Same as the last item, so no need to deal with nesting or opening stuff
2087 $output .= $this->nextItem( substr( $pref, -1 ) );
2088 $paragraphStack = false;
2090 if ( substr( $pref, -1 ) == ';') {
2091 # The one nasty exception: definition lists work like this:
2092 # ; title : definition text
2093 # So we check for : in the remainder text to split up the
2094 # title and definition, without b0rking links.
2096 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2098 $output .= $term . $this->nextItem( ':' );
2101 } elseif( $prefixLength ||
$lastPrefixLength ) {
2102 # Either open or close a level...
2103 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2104 $paragraphStack = false;
2106 while( $commonPrefixLength < $lastPrefixLength ) {
2107 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2108 --$lastPrefixLength;
2110 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2111 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2113 while ( $prefixLength > $commonPrefixLength ) {
2114 $char = substr( $pref, $commonPrefixLength, 1 );
2115 $output .= $this->openList( $char );
2117 if ( ';' == $char ) {
2118 # FIXME: This is dupe of code above
2119 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2121 $output .= $term . $this->nextItem( ':' );
2124 ++
$commonPrefixLength;
2126 $lastPrefix = $pref2;
2128 if( 0 == $prefixLength ) {
2129 wfProfileIn( "$fname-paragraph" );
2130 # No prefix (not in list)--go to paragraph mode
2131 // XXX: use a stack for nestable elements like span, table and div
2132 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2133 $closematch = preg_match(
2134 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2135 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2136 if ( $openmatch or $closematch ) {
2137 $paragraphStack = false;
2138 #Â TODO bug 5718: paragraph closed
2139 $output .= $this->closeParagraph();
2140 if ( $preOpenMatch and !$preCloseMatch ) {
2141 $this->mInPre
= true;
2143 if ( $closematch ) {
2144 $inBlockElem = false;
2146 $inBlockElem = true;
2148 } else if ( !$inBlockElem && !$this->mInPre
) {
2149 if ( '' != $t and ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2151 if ($this->mLastSection
!= 'pre') {
2152 $paragraphStack = false;
2153 $output .= $this->closeParagraph().'<pre>';
2154 $this->mLastSection
= 'pre';
2156 $t = substr( $t, 1 );
2159 if ( '' == trim($t) ) {
2160 if ( $paragraphStack ) {
2161 $output .= $paragraphStack.'<br />';
2162 $paragraphStack = false;
2163 $this->mLastSection
= 'p';
2165 if ($this->mLastSection
!= 'p' ) {
2166 $output .= $this->closeParagraph();
2167 $this->mLastSection
= '';
2168 $paragraphStack = '<p>';
2170 $paragraphStack = '</p><p>';
2174 if ( $paragraphStack ) {
2175 $output .= $paragraphStack;
2176 $paragraphStack = false;
2177 $this->mLastSection
= 'p';
2178 } else if ($this->mLastSection
!= 'p') {
2179 $output .= $this->closeParagraph().'<p>';
2180 $this->mLastSection
= 'p';
2185 wfProfileOut( "$fname-paragraph" );
2187 // somewhere above we forget to get out of pre block (bug 785)
2188 if($preCloseMatch && $this->mInPre
) {
2189 $this->mInPre
= false;
2191 if ($paragraphStack === false) {
2195 while ( $prefixLength ) {
2196 $output .= $this->closeList( $pref2{$prefixLength-1} );
2199 if ( '' != $this->mLastSection
) {
2200 $output .= '</' . $this->mLastSection
. '>';
2201 $this->mLastSection
= '';
2204 wfProfileOut( $fname );
2209 * Split up a string on ':', ignoring any occurences inside tags
2210 * to prevent illegal overlapping.
2211 * @param string $str the string to split
2212 * @param string &$before set to everything before the ':'
2213 * @param string &$after set to everything after the ':'
2214 * return string the position of the ':', or false if none found
2216 function findColonNoLinks($str, &$before, &$after) {
2217 $fname = 'Parser::findColonNoLinks';
2218 wfProfileIn( $fname );
2220 $pos = strpos( $str, ':' );
2221 if( $pos === false ) {
2223 wfProfileOut( $fname );
2227 $lt = strpos( $str, '<' );
2228 if( $lt === false ||
$lt > $pos ) {
2229 // Easy; no tag nesting to worry about
2230 $before = substr( $str, 0, $pos );
2231 $after = substr( $str, $pos+
1 );
2232 wfProfileOut( $fname );
2236 // Ugly state machine to walk through avoiding tags.
2237 $state = self
::COLON_STATE_TEXT
;
2239 $len = strlen( $str );
2240 for( $i = 0; $i < $len; $i++
) {
2244 // (Using the number is a performance hack for common cases)
2245 case 0: // self::COLON_STATE_TEXT:
2248 // Could be either a <start> tag or an </end> tag
2249 $state = self
::COLON_STATE_TAGSTART
;
2254 $before = substr( $str, 0, $i );
2255 $after = substr( $str, $i +
1 );
2256 wfProfileOut( $fname );
2259 // Embedded in a tag; don't break it.
2262 // Skip ahead looking for something interesting
2263 $colon = strpos( $str, ':', $i );
2264 if( $colon === false ) {
2265 // Nothing else interesting
2266 wfProfileOut( $fname );
2269 $lt = strpos( $str, '<', $i );
2270 if( $stack === 0 ) {
2271 if( $lt === false ||
$colon < $lt ) {
2273 $before = substr( $str, 0, $colon );
2274 $after = substr( $str, $colon +
1 );
2275 wfProfileOut( $fname );
2279 if( $lt === false ) {
2280 // Nothing else interesting to find; abort!
2281 // We're nested, but there's no close tags left. Abort!
2284 // Skip ahead to next tag start
2286 $state = self
::COLON_STATE_TAGSTART
;
2289 case 1: // self::COLON_STATE_TAG:
2294 $state = self
::COLON_STATE_TEXT
;
2297 // Slash may be followed by >?
2298 $state = self
::COLON_STATE_TAGSLASH
;
2304 case 2: // self::COLON_STATE_TAGSTART:
2307 $state = self
::COLON_STATE_CLOSETAG
;
2310 $state = self
::COLON_STATE_COMMENT
;
2313 // Illegal early close? This shouldn't happen D:
2314 $state = self
::COLON_STATE_TEXT
;
2317 $state = self
::COLON_STATE_TAG
;
2320 case 3: // self::COLON_STATE_CLOSETAG:
2325 wfDebug( "Invalid input in $fname; too many close tags\n" );
2326 wfProfileOut( $fname );
2329 $state = self
::COLON_STATE_TEXT
;
2332 case self
::COLON_STATE_TAGSLASH
:
2334 // Yes, a self-closed tag <blah/>
2335 $state = self
::COLON_STATE_TEXT
;
2337 // Probably we're jumping the gun, and this is an attribute
2338 $state = self
::COLON_STATE_TAG
;
2341 case 5: // self::COLON_STATE_COMMENT:
2343 $state = self
::COLON_STATE_COMMENTDASH
;
2346 case self
::COLON_STATE_COMMENTDASH
:
2348 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2350 $state = self
::COLON_STATE_COMMENT
;
2353 case self
::COLON_STATE_COMMENTDASHDASH
:
2355 $state = self
::COLON_STATE_TEXT
;
2357 $state = self
::COLON_STATE_COMMENT
;
2361 throw new MWException( "State machine error in $fname" );
2365 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2368 wfProfileOut( $fname );
2373 * Return value of a magic variable (like PAGENAME)
2377 function getVariableValue( $index ) {
2378 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2381 * Some of these require message or data lookups and can be
2382 * expensive to check many times.
2384 static $varCache = array();
2385 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2386 if ( isset( $varCache[$index] ) ) {
2387 return $varCache[$index];
2392 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2395 global $wgLocaltimezone;
2396 if ( isset( $wgLocaltimezone ) ) {
2397 $oldtz = getenv( 'TZ' );
2398 putenv( 'TZ='.$wgLocaltimezone );
2401 wfSuppressWarnings(); // E_STRICT system time bitching
2402 $localTimestamp = date( 'YmdHis', $ts );
2403 $localMonth = date( 'm', $ts );
2404 $localMonthName = date( 'n', $ts );
2405 $localDay = date( 'j', $ts );
2406 $localDay2 = date( 'd', $ts );
2407 $localDayOfWeek = date( 'w', $ts );
2408 $localWeek = date( 'W', $ts );
2409 $localYear = date( 'Y', $ts );
2410 $localHour = date( 'H', $ts );
2411 if ( isset( $wgLocaltimezone ) ) {
2412 putenv( 'TZ='.$oldtz );
2414 wfRestoreWarnings();
2417 case 'currentmonth':
2418 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2419 case 'currentmonthname':
2420 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2421 case 'currentmonthnamegen':
2422 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2423 case 'currentmonthabbrev':
2424 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2426 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2428 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2430 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2431 case 'localmonthname':
2432 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2433 case 'localmonthnamegen':
2434 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2435 case 'localmonthabbrev':
2436 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2438 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2440 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2442 return wfEscapeWikiText( $this->mTitle
->getText() );
2444 return $this->mTitle
->getPartialURL();
2445 case 'fullpagename':
2446 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2447 case 'fullpagenamee':
2448 return $this->mTitle
->getPrefixedURL();
2450 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2451 case 'subpagenamee':
2452 return $this->mTitle
->getSubpageUrlForm();
2453 case 'basepagename':
2454 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2455 case 'basepagenamee':
2456 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2457 case 'talkpagename':
2458 if( $this->mTitle
->canTalk() ) {
2459 $talkPage = $this->mTitle
->getTalkPage();
2460 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2464 case 'talkpagenamee':
2465 if( $this->mTitle
->canTalk() ) {
2466 $talkPage = $this->mTitle
->getTalkPage();
2467 return $talkPage->getPrefixedUrl();
2471 case 'subjectpagename':
2472 $subjPage = $this->mTitle
->getSubjectPage();
2473 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2474 case 'subjectpagenamee':
2475 $subjPage = $this->mTitle
->getSubjectPage();
2476 return $subjPage->getPrefixedUrl();
2478 return $this->mRevisionId
;
2480 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2481 case 'revisionday2':
2482 return substr( $this->getRevisionTimestamp(), 6, 2 );
2483 case 'revisionmonth':
2484 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2485 case 'revisionyear':
2486 return substr( $this->getRevisionTimestamp(), 0, 4 );
2487 case 'revisiontimestamp':
2488 return $this->getRevisionTimestamp();
2490 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2492 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2494 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2496 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2497 case 'subjectspace':
2498 return $this->mTitle
->getSubjectNsText();
2499 case 'subjectspacee':
2500 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2501 case 'currentdayname':
2502 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2504 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2506 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2508 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2510 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2511 // int to remove the padding
2512 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2514 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2515 case 'localdayname':
2516 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2518 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2520 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2522 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2524 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2525 // int to remove the padding
2526 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2528 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2529 case 'numberofarticles':
2530 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2531 case 'numberoffiles':
2532 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2533 case 'numberofusers':
2534 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2535 case 'numberofpages':
2536 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2537 case 'numberofadmins':
2538 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2539 case 'numberofedits':
2540 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2541 case 'currenttimestamp':
2542 return $varCache[$index] = wfTimestampNow();
2543 case 'localtimestamp':
2544 return $varCache[$index] = $localTimestamp;
2545 case 'currentversion':
2546 return $varCache[$index] = SpecialVersion
::getVersion();
2552 return $wgServerName;
2554 return $wgScriptPath;
2555 case 'directionmark':
2556 return $wgContLang->getDirMark();
2557 case 'contentlanguage':
2558 global $wgContLanguageCode;
2559 return $wgContLanguageCode;
2562 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2570 * initialise the magic variables (like CURRENTMONTHNAME)
2574 function initialiseVariables() {
2575 $fname = 'Parser::initialiseVariables';
2576 wfProfileIn( $fname );
2577 $variableIDs = MagicWord
::getVariableIDs();
2579 $this->mVariables
= array();
2580 foreach ( $variableIDs as $id ) {
2581 $mw =& MagicWord
::get( $id );
2582 $mw->addToArray( $this->mVariables
, $id );
2584 wfProfileOut( $fname );
2588 * parse any parentheses in format ((title|part|part))
2589 * and call callbacks to get a replacement text for any found piece
2591 * @param string $text The text to parse
2592 * @param array $callbacks rules in form:
2593 * '{' => array( # opening parentheses
2594 * 'end' => '}', # closing parentheses
2595 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2596 * 3 => callback # replacement callback to call if {{{..}}} is found
2599 * 'min' => 2, # Minimum parenthesis count in cb
2600 * 'max' => 3, # Maximum parenthesis count in cb
2603 function replace_callback ($text, $callbacks) {
2604 wfProfileIn( __METHOD__
);
2605 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2606 $lastOpeningBrace = -1; # last not closed parentheses
2608 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2611 while ( $i < strlen( $text ) ) {
2612 # Find next opening brace, closing brace or pipe
2613 if ( $lastOpeningBrace == -1 ) {
2614 $currentClosing = '';
2615 $search = $validOpeningBraces;
2617 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2618 $search = $validOpeningBraces . '|' . $currentClosing;
2621 $i +
= strcspn( $text, $search, $i );
2622 if ( $i < strlen( $text ) ) {
2623 if ( $text[$i] == '|' ) {
2625 } elseif ( $text[$i] == $currentClosing ) {
2627 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2629 $rule = $callbacks[$text[$i]];
2631 # Some versions of PHP have a strcspn which stops on null characters
2632 # Ignore and continue
2641 if ( $found == 'open' ) {
2642 # found opening brace, let's add it to parentheses stack
2643 $piece = array('brace' => $text[$i],
2644 'braceEnd' => $rule['end'],
2648 # count opening brace characters
2649 $piece['count'] = strspn( $text, $piece['brace'], $i );
2650 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2651 $i +
= $piece['count'];
2653 # we need to add to stack only if opening brace count is enough for one of the rules
2654 if ( $piece['count'] >= $rule['min'] ) {
2655 $lastOpeningBrace ++
;
2656 $openingBraceStack[$lastOpeningBrace] = $piece;
2658 } elseif ( $found == 'close' ) {
2659 # lets check if it is enough characters for closing brace
2660 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2661 $count = strspn( $text, $text[$i], $i, $maxCount );
2663 # check for maximum matching characters (if there are 5 closing
2664 # characters, we will probably need only 3 - depending on the rules)
2666 $matchingCallback = null;
2667 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2668 if ( $count > $cbType['max'] ) {
2669 # The specified maximum exists in the callback array, unless the caller
2671 $matchingCount = $cbType['max'];
2673 # Count is less than the maximum
2674 # Skip any gaps in the callback array to find the true largest match
2675 # Need to use array_key_exists not isset because the callback can be null
2676 $matchingCount = $count;
2677 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2682 if ($matchingCount <= 0) {
2686 $matchingCallback = $cbType['cb'][$matchingCount];
2688 # let's set a title or last part (if '|' was found)
2689 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2690 $openingBraceStack[$lastOpeningBrace]['title'] =
2691 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2692 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2694 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2695 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2696 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2699 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2700 $pieceEnd = $i +
$matchingCount;
2702 if( is_callable( $matchingCallback ) ) {
2704 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2705 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2706 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2707 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2709 # finally we can call a user callback and replace piece of text
2710 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2711 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2712 $i = $pieceStart +
strlen($replaceWith);
2714 # null value for callback means that parentheses should be parsed, but not replaced
2715 $i +
= $matchingCount;
2718 # reset last opening parentheses, but keep it in case there are unused characters
2719 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2720 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2721 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2724 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2725 $openingBraceStack[$lastOpeningBrace--] = null;
2727 if ($matchingCount < $piece['count']) {
2728 $piece['count'] -= $matchingCount;
2729 $piece['startAt'] -= $matchingCount;
2730 $piece['partStart'] = $piece['startAt'];
2731 # do we still qualify for any callback with remaining count?
2732 $currentCbList = $callbacks[$piece['brace']]['cb'];
2733 while ( $piece['count'] ) {
2734 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2735 $lastOpeningBrace++
;
2736 $openingBraceStack[$lastOpeningBrace] = $piece;
2742 } elseif ( $found == 'pipe' ) {
2743 # lets set a title if it is a first separator, or next part otherwise
2744 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2745 $openingBraceStack[$lastOpeningBrace]['title'] =
2746 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2747 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2748 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2750 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2751 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2752 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2754 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2758 wfProfileOut( __METHOD__
);
2763 * Replace magic variables, templates, and template arguments
2764 * with the appropriate text. Templates are substituted recursively,
2765 * taking care to avoid infinite loops.
2767 * Note that the substitution depends on value of $mOutputType:
2768 * self::OT_WIKI: only {{subst:}} templates
2769 * self::OT_MSG: only magic variables
2770 * self::OT_HTML: all templates and magic variables
2772 * @param string $tex The text to transform
2773 * @param array $args Key-value pairs representing template parameters to substitute
2774 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2777 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2778 # Prevent too big inclusions
2779 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2783 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2784 wfProfileIn( $fname );
2786 # This function is called recursively. To keep track of arguments we need a stack:
2787 array_push( $this->mArgStack
, $args );
2789 $braceCallbacks = array();
2791 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2793 if ( $this->mOutputType
!= self
::OT_MSG
) {
2794 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2796 if ( $braceCallbacks ) {
2800 'cb' => $braceCallbacks,
2801 'min' => $argsOnly ?
3 : 2,
2802 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2806 'cb' => array(2=>null),
2811 $text = $this->replace_callback ($text, $callbacks);
2813 array_pop( $this->mArgStack
);
2815 wfProfileOut( $fname );
2820 * Replace magic variables
2823 function variableSubstitution( $matches ) {
2825 $fname = 'Parser::variableSubstitution';
2826 $varname = $wgContLang->lc($matches[1]);
2827 wfProfileIn( $fname );
2829 if ( $this->mOutputType
== self
::OT_WIKI
) {
2830 # Do only magic variables prefixed by SUBST
2831 $mwSubst =& MagicWord
::get( 'subst' );
2832 if (!$mwSubst->matchStartAndRemove( $varname ))
2834 # Note that if we don't substitute the variable below,
2835 # we don't remove the {{subst:}} magic word, in case
2836 # it is a template rather than a magic variable.
2838 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2839 $id = $this->mVariables
[$varname];
2840 # Now check if we did really match, case sensitive or not
2841 $mw =& MagicWord
::get( $id );
2842 if ($mw->match($matches[1])) {
2843 $text = $this->getVariableValue( $id );
2844 if (MagicWord
::getCacheTTL($id)>-1)
2845 $this->mOutput
->mContainsOldMagic
= true;
2847 $text = $matches[0];
2850 $text = $matches[0];
2852 wfProfileOut( $fname );
2857 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2858 static function createAssocArgs( $args ) {
2859 $assocArgs = array();
2861 foreach( $args as $arg ) {
2862 $eqpos = strpos( $arg, '=' );
2863 if ( $eqpos === false ) {
2864 $assocArgs[$index++
] = $arg;
2866 $name = trim( substr( $arg, 0, $eqpos ) );
2867 $value = trim( substr( $arg, $eqpos+
1 ) );
2868 if ( $value === false ) {
2871 if ( $name !== false ) {
2872 $assocArgs[$name] = $value;
2881 * Return the text of a template, after recursively
2882 * replacing any variables or templates within the template.
2884 * @param array $piece The parts of the template
2885 * $piece['text']: matched text
2886 * $piece['title']: the title, i.e. the part before the |
2887 * $piece['parts']: the parameter array
2888 * @return string the text of the template
2891 function braceSubstitution( $piece ) {
2892 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2893 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2894 wfProfileIn( $fname );
2895 wfProfileIn( __METHOD__
.'-setup' );
2898 $found = false; # $text has been filled
2899 $nowiki = false; # wiki markup in $text should be escaped
2900 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2901 $noargs = false; # Don't replace triple-brace arguments in $text
2902 $replaceHeadings = false; # Make the edit section links go to the template not the article
2903 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2904 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2905 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2907 # Title object, where $text came from
2913 # $part1 is the bit before the first |, and must contain only title characters
2914 # $args is a list of arguments, starting from index 0, not including $part1
2916 $titleText = $part1 = $piece['title'];
2917 # If the third subpattern matched anything, it will start with |
2919 if (null == $piece['parts']) {
2920 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2921 if ($replaceWith != $piece['text']) {
2922 $text = $replaceWith;
2929 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2930 wfProfileOut( __METHOD__
.'-setup' );
2933 wfProfileIn( __METHOD__
.'-modifiers' );
2935 $mwSubst =& MagicWord
::get( 'subst' );
2936 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2937 # One of two possibilities is true:
2938 # 1) Found SUBST but not in the PST phase
2939 # 2) Didn't find SUBST and in the PST phase
2940 # In either case, return without further processing
2941 $text = $piece['text'];
2948 # MSG, MSGNW and RAW
2951 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2952 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2955 # Remove obsolete MSG:
2956 $mwMsg =& MagicWord
::get( 'msg' );
2957 $mwMsg->matchStartAndRemove( $part1 );
2961 $mwRaw =& MagicWord
::get( 'raw' );
2962 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2963 $forceRawInterwiki = true;
2966 wfProfileOut( __METHOD__
.'-modifiers' );
2968 //save path level before recursing into functions & templates.
2969 $lastPathLevel = $this->mTemplatePath
;
2973 wfProfileIn( __METHOD__
. '-pfunc' );
2975 $colonPos = strpos( $part1, ':' );
2976 if ( $colonPos !== false ) {
2977 # Case sensitive functions
2978 $function = substr( $part1, 0, $colonPos );
2979 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2980 $function = $this->mFunctionSynonyms
[1][$function];
2982 # Case insensitive functions
2983 $function = strtolower( $function );
2984 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2985 $function = $this->mFunctionSynonyms
[0][$function];
2991 $funcArgs = array_map( 'trim', $args );
2992 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2993 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2996 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3000 if ( is_array( $result ) ) {
3001 if ( isset( $result[0] ) ) {
3002 $text = $linestart . $result[0];
3003 unset( $result[0] );
3006 // Extract flags into the local scope
3007 // This allows callers to set flags such as nowiki, noparse, found, etc.
3010 $text = $linestart . $result;
3014 wfProfileOut( __METHOD__
. '-pfunc' );
3017 # Template table test
3019 # Did we encounter this template already? If yes, it is in the cache
3020 # and we need to check for loops.
3021 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3024 # Infinite loop test
3025 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3029 $text = $linestart .
3030 "[[$part1]]<!-- WARNING: template loop detected -->";
3031 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3033 # set $text to cached message.
3034 $text = $linestart . $this->mTemplates
[$piece['title']];
3035 #treat title for cached page the same as others
3038 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3039 if ($subpage !== '') {
3040 $ns = $this->mTitle
->getNamespace();
3042 $title = Title
::newFromText( $part1, $ns );
3043 //used by include size checking
3044 $titleText = $title->getPrefixedText();
3045 //used by edit section links
3046 $replaceHeadings = true;
3051 # Load from database
3053 wfProfileIn( __METHOD__
. '-loadtpl' );
3055 # declaring $subpage directly in the function call
3056 # does not work correctly with references and breaks
3057 # {{/subpage}}-style inclusions
3059 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3060 if ($subpage !== '') {
3061 $ns = $this->mTitle
->getNamespace();
3063 $title = Title
::newFromText( $part1, $ns );
3066 if ( !is_null( $title ) ) {
3067 $titleText = $title->getPrefixedText();
3068 # Check for language variants if the template is not found
3069 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3070 $wgContLang->findVariantLink($part1, $title);
3073 if ( !$title->isExternal() ) {
3074 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3075 $text = SpecialPage
::capturePath( $title );
3076 if ( is_string( $text ) ) {
3081 $this->disableCache();
3083 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3084 $found = false; //access denied
3085 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3087 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3088 if ( $articleContent !== false ) {
3090 $text = $articleContent;
3091 $replaceHeadings = true;
3095 # If the title is valid but undisplayable, make a link to it
3096 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3097 $text = "[[:$titleText]]";
3100 } elseif ( $title->isTrans() ) {
3101 // Interwiki transclusion
3102 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3103 $text = $this->interwikiTransclude( $title, 'render' );
3107 $text = $this->interwikiTransclude( $title, 'raw' );
3108 $replaceHeadings = true;
3113 # Template cache array insertion
3114 # Use the original $piece['title'] not the mangled $part1, so that
3115 # modifiers such as RAW: produce separate cache entries
3118 // A special page; don't store it in the template cache.
3120 $this->mTemplates
[$piece['title']] = $text;
3122 $text = $linestart . $text;
3125 wfProfileOut( __METHOD__
. '-loadtpl' );
3128 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3129 # Error, oversize inclusion
3130 $text = $linestart .
3131 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3136 # Recursive parsing, escaping and link table handling
3137 # Only for HTML output
3138 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3139 $text = wfEscapeWikiText( $text );
3140 } elseif ( !$this->ot
['msg'] && $found ) {
3142 $assocArgs = array();
3144 # Clean up argument array
3145 $assocArgs = self
::createAssocArgs($args);
3146 # Add a new element to the templace recursion path
3147 $this->mTemplatePath
[$part1] = 1;
3151 # If there are any <onlyinclude> tags, only include them
3152 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3153 $replacer = new OnlyIncludeReplacer
;
3154 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3155 array( &$replacer, 'replace' ), $text );
3156 $text = $replacer->output
;
3158 # Remove <noinclude> sections and <includeonly> tags
3159 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3160 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3162 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3163 # Strip <nowiki>, <pre>, etc.
3164 $text = $this->strip( $text, $this->mStripState
);
3165 if ( $this->ot
['html'] ) {
3166 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3167 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3168 $text = Sanitizer
::removeHTMLcomments( $text );
3171 $text = $this->replaceVariables( $text, $assocArgs );
3173 # If the template begins with a table or block-level
3174 # element, it should be treated as beginning a new line.
3175 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3176 $text = "\n" . $text;
3178 } elseif ( !$noargs ) {
3179 # $noparse and !$noargs
3180 # Just replace the arguments, not any double-brace items
3181 # This is used for rendered interwiki transclusion
3182 $text = $this->replaceVariables( $text, $assocArgs, true );
3185 # Prune lower levels off the recursion check path
3186 $this->mTemplatePath
= $lastPathLevel;
3188 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3189 # Error, oversize inclusion
3190 $text = $linestart .
3191 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3197 wfProfileOut( $fname );
3198 return $piece['text'];
3200 wfProfileIn( __METHOD__
. '-placeholders' );
3202 # Replace raw HTML by a placeholder
3203 # Add a blank line preceding, to prevent it from mucking up
3204 # immediately preceding headings
3205 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3207 # replace ==section headers==
3208 # XXX this needs to go away once we have a better parser.
3209 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3210 if( !is_null( $title ) )
3211 $encodedname = base64_encode($title->getPrefixedDBkey());
3213 $encodedname = base64_encode("");
3214 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3215 PREG_SPLIT_DELIM_CAPTURE
);
3217 $nsec = $headingOffset;
3219 for( $i = 0; $i < count($m); $i +
= 2 ) {
3221 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3223 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3228 preg_match('/^(={1,6})(.*?)(={1,6}\s*?)$/m', $hl, $m2);
3229 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3230 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3236 wfProfileOut( __METHOD__
. '-placeholders' );
3239 # Prune lower levels off the recursion check path
3240 $this->mTemplatePath
= $lastPathLevel;
3243 wfProfileOut( $fname );
3244 return $piece['text'];
3246 wfProfileOut( $fname );
3252 * Fetch the unparsed text of a template and register a reference to it.
3254 function fetchTemplateAndTitle( $title ) {
3255 $templateCb = $this->mOptions
->getTemplateCallback();
3256 $stuff = call_user_func( $templateCb, $title );
3257 $text = $stuff['text'];
3258 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3259 if ( isset( $stuff['deps'] ) ) {
3260 foreach ( $stuff['deps'] as $dep ) {
3261 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3264 return array($text,$finalTitle);
3267 function fetchTemplate( $title ) {
3268 $rv = $this->fetchTemplateAndtitle($title);
3273 * Static function to get a template
3274 * Can be overridden via ParserOptions::setTemplateCallback().
3276 * Returns an associative array:
3277 * text The unparsed template text
3278 * finalTitle (Optional) The title after following redirects
3279 * deps (Optional) An array of associative array dependencies:
3280 * title: The dependency title, to be registered in templatelinks
3281 * page_id: The page_id of the title
3282 * rev_id: The revision ID loaded
3284 static function statelessFetchTemplate( $title ) {
3285 $text = $skip = false;
3286 $finalTitle = $title;
3289 // Loop to fetch the article, with up to 1 redirect
3290 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3291 # Give extensions a chance to select the revision instead
3292 $id = false; // Assume current
3293 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3299 'page_id' => $title->getArticleID(),
3303 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3304 $rev_id = $rev ?
$rev->getId() : 0;
3308 'page_id' => $title->getArticleID(),
3309 'rev_id' => $rev_id );
3312 $text = $rev->getText();
3313 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3315 $message = $wgLang->lcfirst( $title->getText() );
3316 $text = wfMsgForContentNoTrans( $message );
3317 if( wfEmptyMsg( $message, $text ) ) {
3324 if ( $text === false ) {
3328 $finalTitle = $title;
3329 $title = Title
::newFromRedirect( $text );
3333 'finalTitle' => $finalTitle,
3338 * Transclude an interwiki link.
3340 function interwikiTransclude( $title, $action ) {
3341 global $wgEnableScaryTranscluding;
3343 if (!$wgEnableScaryTranscluding)
3344 return wfMsg('scarytranscludedisabled');
3346 $url = $title->getFullUrl( "action=$action" );
3348 if (strlen($url) > 255)
3349 return wfMsg('scarytranscludetoolong');
3350 return $this->fetchScaryTemplateMaybeFromCache($url);
3353 function fetchScaryTemplateMaybeFromCache($url) {
3354 global $wgTranscludeCacheExpiry;
3355 $dbr = wfGetDB(DB_SLAVE
);
3356 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3357 array('tc_url' => $url));
3359 $time = $obj->tc_time
;
3360 $text = $obj->tc_contents
;
3361 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3366 $text = Http
::get($url);
3368 return wfMsg('scarytranscludefailed', $url);
3370 $dbw = wfGetDB(DB_MASTER
);
3371 $dbw->replace('transcache', array('tc_url'), array(
3373 'tc_time' => time(),
3374 'tc_contents' => $text));
3380 * Triple brace replacement -- used for template arguments
3383 function argSubstitution( $matches ) {
3384 $arg = trim( $matches['title'] );
3385 $text = $matches['text'];
3386 $inputArgs = end( $this->mArgStack
);
3388 if ( array_key_exists( $arg, $inputArgs ) ) {
3389 $text = $inputArgs[$arg];
3390 } else if (($this->mOutputType
== self
::OT_HTML ||
$this->mOutputType
== self
::OT_PREPROCESS
) &&
3391 null != $matches['parts'] && count($matches['parts']) > 0) {
3392 $text = $matches['parts'][0];
3394 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3395 $text = $matches['text'] .
3396 '<!-- WARNING: argument omitted, expansion size too large -->';
3403 * Increment an include size counter
3405 * @param string $type The type of expansion
3406 * @param integer $size The size of the text
3407 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3409 function incrementIncludeSize( $type, $size ) {
3410 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3413 $this->mIncludeSizes
[$type] +
= $size;
3419 * Detect __NOGALLERY__ magic word and set a placeholder
3421 function stripNoGallery( &$text ) {
3422 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3424 $mw = MagicWord
::get( 'nogallery' );
3425 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3429 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3430 * placeholder that will then be replaced by the real TOC in
3431 * ->formatHeadings, this works because at this points real
3432 * comments will have already been discarded by the sanitizer.
3434 * Any additional __TOC__ magic words left over will be discarded
3435 * as there can only be one TOC on the page.
3437 function stripToc( $text ) {
3438 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3440 $mw = MagicWord
::get( 'notoc' );
3441 if( $mw->matchAndRemove( $text ) ) {
3442 $this->mShowToc
= false;
3445 $mw = MagicWord
::get( 'toc' );
3446 if( $mw->match( $text ) ) {
3447 $this->mShowToc
= true;
3448 $this->mForceTocPosition
= true;
3450 // Set a placeholder. At the end we'll fill it in with the TOC.
3451 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3453 // Only keep the first one.
3454 $text = $mw->replace( '', $text );
3460 * This function accomplishes several tasks:
3461 * 1) Auto-number headings if that option is enabled
3462 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3463 * 3) Add a Table of contents on the top for users who have enabled the option
3464 * 4) Auto-anchor headings
3466 * It loops through all headlines, collects the necessary data, then splits up the
3467 * string and re-inserts the newly formatted headlines.
3469 * @param string $text
3470 * @param boolean $isMain
3473 function formatHeadings( $text, $isMain=true ) {
3474 global $wgMaxTocLevel, $wgContLang;
3476 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3477 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3480 $showEditLink = $this->mOptions
->getEditSection();
3483 # Inhibit editsection links if requested in the page
3484 $esw =& MagicWord
::get( 'noeditsection' );
3485 if( $esw->matchAndRemove( $text ) ) {
3489 # Get all headlines for numbering them and adding funky stuff like [edit]
3490 # links - this is for later, but we need the number of headlines right now
3492 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3494 # if there are fewer than 4 headlines in the article, do not show TOC
3495 # unless it's been explicitly enabled.
3496 $enoughToc = $this->mShowToc
&&
3497 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3499 # Allow user to stipulate that a page should have a "new section"
3500 # link added via __NEWSECTIONLINK__
3501 $mw =& MagicWord
::get( 'newsectionlink' );
3502 if( $mw->matchAndRemove( $text ) )
3503 $this->mOutput
->setNewSection( true );
3505 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3506 # override above conditions and always show TOC above first header
3507 $mw =& MagicWord
::get( 'forcetoc' );
3508 if ($mw->matchAndRemove( $text ) ) {
3509 $this->mShowToc
= true;
3513 # We need this to perform operations on the HTML
3514 $sk = $this->mOptions
->getSkin();
3518 $sectionCount = 0; # headlineCount excluding template sections
3521 # Ugh .. the TOC should have neat indentation levels which can be
3522 # passed to the skin functions. These are determined here
3526 $sublevelCount = array();
3527 $levelCount = array();
3535 foreach( $matches[3] as $headline ) {
3537 $templatetitle = '';
3538 $templatesection = 0;
3541 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3543 $templatetitle = base64_decode($mat[1]);
3544 $templatesection = 1 +
(int)base64_decode($mat[2]);
3545 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3549 $prevlevel = $level;
3550 $prevtoclevel = $toclevel;
3552 $level = $matches[1][$headlineCount];
3554 if( $doNumberHeadings ||
$enoughToc ) {
3556 if ( $level > $prevlevel ) {
3557 # Increase TOC level
3559 $sublevelCount[$toclevel] = 0;
3560 if( $toclevel<$wgMaxTocLevel ) {
3561 $prevtoclevel = $toclevel;
3562 $toc .= $sk->tocIndent();
3566 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3567 # Decrease TOC level, find level to jump to
3569 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3570 # Can only go down to level 1
3573 for ($i = $toclevel; $i > 0; $i--) {
3574 if ( $levelCount[$i] == $level ) {
3575 # Found last matching level
3579 elseif ( $levelCount[$i] < $level ) {
3580 # Found first matching level below current level
3586 if( $toclevel<$wgMaxTocLevel ) {
3587 if($prevtoclevel < $wgMaxTocLevel) {
3588 # Unindent only if the previous toc level was shown :p
3589 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3591 $toc .= $sk->tocLineEnd();
3596 # No change in level, end TOC line
3597 if( $toclevel<$wgMaxTocLevel ) {
3598 $toc .= $sk->tocLineEnd();
3602 $levelCount[$toclevel] = $level;
3604 # count number of headlines for each level
3605 @$sublevelCount[$toclevel]++
;
3607 for( $i = 1; $i <= $toclevel; $i++
) {
3608 if( !empty( $sublevelCount[$i] ) ) {
3612 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3618 # The canonized header is a version of the header text safe to use for links
3619 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3620 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3622 # Remove link placeholders by the link text.
3623 # <!--LINK number-->
3625 # link text with suffix
3626 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3627 "\$this->mLinkHolders['texts'][\$1]",
3628 $canonized_headline );
3629 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3630 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3631 $canonized_headline );
3633 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3634 $tocline = preg_replace(
3635 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3639 $tocline = trim( $tocline );
3641 # For the anchor, strip out HTML-y stuff period
3642 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3643 $canonized_headline = trim( $canonized_headline );
3645 # Save headline for section edit hint before it's escaped
3646 $headline_hint = $canonized_headline;
3647 $canonized_headline = Sanitizer
::escapeId( $canonized_headline );
3648 $refers[$headlineCount] = $canonized_headline;
3650 # count how many in assoc. array so we can track dupes in anchors
3651 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3652 $refcount[$headlineCount]=$refers[$canonized_headline];
3654 # Don't number the heading if it is the only one (looks silly)
3655 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3656 # the two are different if the line contains a link
3657 $headline=$numbering . ' ' . $headline;
3660 # Create the anchor for linking from the TOC to the section
3661 $anchor = $canonized_headline;
3662 if($refcount[$headlineCount] > 1 ) {
3663 $anchor .= '_' . $refcount[$headlineCount];
3665 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3666 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3667 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3669 # give headline the correct <h#> tag
3670 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3672 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3674 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3678 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3685 $this->mOutput
->setSections( $tocraw );
3687 # Never ever show TOC if no headers
3688 if( $numVisible < 1 ) {
3693 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3694 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3696 $toc = $sk->tocList( $toc );
3699 # split up and insert constructed headlines
3701 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3704 foreach( $blocks as $block ) {
3705 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3706 # This is the [edit] link that appears for the top block of text when
3707 # section editing is enabled
3709 # Disabled because it broke block formatting
3710 # For example, a bullet point in the top line
3711 # $full .= $sk->editSectionLink(0);
3714 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3715 # Top anchor now in skin
3719 if( !empty( $head[$i] ) ) {
3724 if( $this->mForceTocPosition
) {
3725 return str_replace( '<!--MWTOC-->', $toc, $full );
3732 * Transform wiki markup when saving a page by doing \r\n -> \n
3733 * conversion, substitting signatures, {{subst:}} templates, etc.
3735 * @param string $text the text to transform
3736 * @param Title &$title the Title object for the current article
3737 * @param User &$user the User object describing the current user
3738 * @param ParserOptions $options parsing options
3739 * @param bool $clearState whether to clear the parser state first
3740 * @return string the altered wiki markup
3743 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3744 $this->mOptions
= $options;
3745 $this->mTitle
=& $title;
3746 $this->setOutputType( self
::OT_WIKI
);
3748 if ( $clearState ) {
3749 $this->clearState();
3752 $stripState = new StripState
;
3756 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3757 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3758 $text = $this->pstPass2( $text, $stripState, $user );
3759 $text = $stripState->unstripBoth( $text );
3764 * Pre-save transform helper function
3767 function pstPass2( $text, &$stripState, $user ) {
3768 global $wgContLang, $wgLocaltimezone;
3770 /* Note: This is the timestamp saved as hardcoded wikitext to
3771 * the database, we use $wgContLang here in order to give
3772 * everyone the same signature and use the default one rather
3773 * than the one selected in each user's preferences.
3775 if ( isset( $wgLocaltimezone ) ) {
3776 $oldtz = getenv( 'TZ' );
3777 putenv( 'TZ='.$wgLocaltimezone );
3779 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3780 ' (' . date( 'T' ) . ')';
3781 if ( isset( $wgLocaltimezone ) ) {
3782 putenv( 'TZ='.$oldtz );
3785 # Variable replacement
3786 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3787 $text = $this->replaceVariables( $text );
3789 # Strip out <nowiki> etc. added via replaceVariables
3790 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3793 $sigText = $this->getUserSig( $user );
3794 $text = strtr( $text, array(
3796 '~~~~' => "$sigText $d",
3800 # Context links: [[|name]] and [[name (context)|]]
3802 global $wgLegalTitleChars;
3803 $tc = "[$wgLegalTitleChars]";
3804 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3806 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3807 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3808 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3810 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3811 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3812 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3814 $t = $this->mTitle
->getText();
3816 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3817 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3818 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3819 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3821 # if there's no context, don't bother duplicating the title
3822 $text = preg_replace( $p2, '[[\\1]]', $text );
3825 # Trim trailing whitespace
3826 $text = rtrim( $text );
3832 * Fetch the user's signature text, if any, and normalize to
3833 * validated, ready-to-insert wikitext.
3839 function getUserSig( &$user ) {
3840 global $wgMaxSigChars;
3842 $username = $user->getName();
3843 $nickname = $user->getOption( 'nickname' );
3844 $nickname = $nickname === '' ?
$username : $nickname;
3846 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3847 $nickname = $username;
3848 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3849 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3850 # Sig. might contain markup; validate this
3851 if( $this->validateSig( $nickname ) !== false ) {
3852 # Validated; clean up (if needed) and return it
3853 return $this->cleanSig( $nickname, true );
3855 # Failed to validate; fall back to the default
3856 $nickname = $username;
3857 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3861 // Make sure nickname doesnt get a sig in a sig
3862 $nickname = $this->cleanSigInSig( $nickname );
3864 # If we're still here, make it a link to the user page
3865 $userText = wfEscapeWikiText( $username );
3866 $nickText = wfEscapeWikiText( $nickname );
3867 if ( $user->isAnon() ) {
3868 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3870 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3875 * Check that the user's signature contains no bad XML
3877 * @param string $text
3878 * @return mixed An expanded string, or false if invalid.
3880 function validateSig( $text ) {
3881 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3885 * Clean up signature text
3887 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3888 * 2) Substitute all transclusions
3890 * @param string $text
3891 * @param $parsing Whether we're cleaning (preferences save) or parsing
3892 * @return string Signature text
3894 function cleanSig( $text, $parsing = false ) {
3896 $this->startExternalParse( $this->mTitle
, new ParserOptions(), $parsing ? self
::OT_WIKI
: self
::OT_MSG
);
3898 $substWord = MagicWord
::get( 'subst' );
3899 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3900 $substText = '{{' . $substWord->getSynonym( 0 );
3902 $text = preg_replace( $substRegex, $substText, $text );
3903 $text = $this->cleanSigInSig( $text );
3904 $text = $this->replaceVariables( $text );
3906 $this->clearState();
3911 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3912 * @param string $text
3913 * @return string Signature text with /~{3,5}/ removed
3915 function cleanSigInSig( $text ) {
3916 $text = preg_replace( '/~{3,5}/', '', $text );
3921 * Set up some variables which are usually set up in parse()
3922 * so that an external function can call some class members with confidence
3925 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3926 $this->mTitle
=& $title;
3927 $this->mOptions
= $options;
3928 $this->setOutputType( $outputType );
3929 if ( $clearState ) {
3930 $this->clearState();
3935 * Transform a MediaWiki message by replacing magic variables.
3937 * @param string $text the text to transform
3938 * @param ParserOptions $options options
3939 * @return string the text with variables substituted
3942 function transformMsg( $text, $options ) {
3944 static $executing = false;
3946 $fname = "Parser::transformMsg";
3948 # Guard against infinite recursion
3954 wfProfileIn($fname);
3956 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3957 $this->mTitle
= $wgTitle;
3959 $this->mTitle
= Title
::newFromText('msg');
3961 $this->mOptions
= $options;
3962 $this->setOutputType( self
::OT_MSG
);
3963 $this->clearState();
3964 $text = $this->replaceVariables( $text );
3967 wfProfileOut($fname);
3972 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3973 * The callback should have the following form:
3974 * function myParserHook( $text, $params, &$parser ) { ... }
3976 * Transform and return $text. Use $parser for any required context, e.g. use
3977 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3981 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3982 * @param mixed $callback The callback function (and object) to use for the tag
3984 * @return The old value of the mTagHooks array associated with the hook
3986 function setHook( $tag, $callback ) {
3987 $tag = strtolower( $tag );
3988 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3989 $this->mTagHooks
[$tag] = $callback;
3994 function setTransparentTagHook( $tag, $callback ) {
3995 $tag = strtolower( $tag );
3996 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3997 $this->mTransparentTagHooks
[$tag] = $callback;
4003 * Create a function, e.g. {{sum:1|2|3}}
4004 * The callback function should have the form:
4005 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4007 * The callback may either return the text result of the function, or an array with the text
4008 * in element 0, and a number of flags in the other elements. The names of the flags are
4009 * specified in the keys. Valid flags are:
4010 * found The text returned is valid, stop processing the template. This
4012 * nowiki Wiki markup in the return value should be escaped
4013 * noparse Unsafe HTML tags should not be stripped, etc.
4014 * noargs Don't replace triple-brace arguments in the return value
4015 * isHTML The returned text is HTML, armour it against wikitext transformation
4019 * @param string $id The magic word ID
4020 * @param mixed $callback The callback function (and object) to use
4021 * @param integer $flags a combination of the following flags:
4022 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4024 * @return The old callback function for this name, if any
4026 function setFunctionHook( $id, $callback, $flags = 0 ) {
4027 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4028 $this->mFunctionHooks
[$id] = $callback;
4030 # Add to function cache
4031 $mw = MagicWord
::get( $id );
4033 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4035 $synonyms = $mw->getSynonyms();
4036 $sensitive = intval( $mw->isCaseSensitive() );
4038 foreach ( $synonyms as $syn ) {
4040 if ( !$sensitive ) {
4041 $syn = strtolower( $syn );
4044 if ( !( $flags & SFH_NO_HASH
) ) {
4047 # Remove trailing colon
4048 if ( substr( $syn, -1, 1 ) == ':' ) {
4049 $syn = substr( $syn, 0, -1 );
4051 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4057 * Get all registered function hook identifiers
4061 function getFunctionHooks() {
4062 return array_keys( $this->mFunctionHooks
);
4066 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4067 * Placeholders created in Skin::makeLinkObj()
4068 * Returns an array of links found, indexed by PDBK:
4072 * $options is a bit field, RLH_FOR_UPDATE to select for update
4074 function replaceLinkHolders( &$text, $options = 0 ) {
4078 $fname = 'Parser::replaceLinkHolders';
4079 wfProfileIn( $fname );
4083 $sk = $this->mOptions
->getSkin();
4084 $linkCache =& LinkCache
::singleton();
4086 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4087 wfProfileIn( $fname.'-check' );
4088 $dbr = wfGetDB( DB_SLAVE
);
4089 $page = $dbr->tableName( 'page' );
4090 $threshold = $wgUser->getOption('stubthreshold');
4093 asort( $this->mLinkHolders
['namespaces'] );
4098 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4100 $title = $this->mLinkHolders
['titles'][$key];
4102 # Skip invalid entries.
4103 # Result will be ugly, but prevents crash.
4104 if ( is_null( $title ) ) {
4107 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4109 # Check if it's a static known link, e.g. interwiki
4110 if ( $title->isAlwaysKnown() ) {
4111 $colours[$pdbk] = 1;
4112 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4113 $colours[$pdbk] = 1;
4114 $this->mOutput
->addLink( $title, $id );
4115 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4116 $colours[$pdbk] = 0;
4117 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4118 $colours[$pdbk] = 0;
4120 # Not in the link cache, add it to the query
4121 if ( !isset( $current ) ) {
4123 $query = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect";
4125 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4126 } elseif ( $current != $ns ) {
4128 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4133 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4138 if ( $options & RLH_FOR_UPDATE
) {
4139 $query .= ' FOR UPDATE';
4142 $res = $dbr->query( $query, $fname );
4144 # Fetch data and form into an associative array
4145 # non-existent = broken
4148 while ( $s = $dbr->fetchObject($res) ) {
4149 $title = Title
::newFromRow( $s );
4150 $pdbk = $title->getPrefixedDBkey();
4151 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4152 $this->mOutput
->addLink( $title, $s->page_id
);
4154 $colours[$pdbk] = ( $threshold == 0 ||
(
4155 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4156 $s->page_is_redirect ||
4157 !MWNamespace
::isContent( $s->page_namespace
) )
4161 wfProfileOut( $fname.'-check' );
4163 # Do a second query for different language variants of links and categories
4164 if( $wgContLang->hasVariants() ){
4165 $linkBatch = new LinkBatch();
4166 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4167 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4168 $varCategories = array(); // category replacements oldDBkey => newDBkey
4170 $categories = $this->mOutput
->getCategoryLinks();
4172 // Add variants of links to link batch
4173 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4174 $title = $this->mLinkHolders
['titles'][$key];
4175 if ( is_null( $title ) )
4178 $pdbk = $title->getPrefixedDBkey();
4179 $titleText = $title->getText();
4181 // generate all variants of the link title text
4182 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4184 // if link was not found (in first query), add all variants to query
4185 if ( !isset($colours[$pdbk]) ){
4186 foreach($allTextVariants as $textVariant){
4187 if($textVariant != $titleText){
4188 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4189 if(is_null($variantTitle)) continue;
4190 $linkBatch->addObj( $variantTitle );
4191 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4197 // process categories, check if a category exists in some variant
4198 foreach( $categories as $category ){
4199 $variants = $wgContLang->convertLinkToAllVariants($category);
4200 foreach($variants as $variant){
4201 if($variant != $category){
4202 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4203 if(is_null($variantTitle)) continue;
4204 $linkBatch->addObj( $variantTitle );
4205 $categoryMap[$variant] = $category;
4211 if ( !$linkBatch->isEmpty() ){
4213 $titleClause = $linkBatch->constructSet('page', $dbr);
4215 $variantQuery = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect";
4218 $variantQuery .= " FROM $page WHERE $titleClause";
4219 if ( $options & RLH_FOR_UPDATE
) {
4220 $variantQuery .= ' FOR UPDATE';
4223 $varRes = $dbr->query( $variantQuery, $fname );
4225 // for each found variants, figure out link holders and replace
4226 while ( $s = $dbr->fetchObject($varRes) ) {
4228 $variantTitle = Title
::newFromRow( $s );
4229 $varPdbk = $variantTitle->getPrefixedDBkey();
4230 $vardbk = $variantTitle->getDBkey();
4232 $holderKeys = array();
4233 if(isset($variantMap[$varPdbk])){
4234 $holderKeys = $variantMap[$varPdbk];
4235 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4236 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4239 // loop over link holders
4240 foreach($holderKeys as $key){
4241 $title = $this->mLinkHolders
['titles'][$key];
4242 if ( is_null( $title ) ) continue;
4244 $pdbk = $title->getPrefixedDBkey();
4246 if(!isset($colours[$pdbk])){
4247 // found link in some of the variants, replace the link holder data
4248 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4249 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4251 // set pdbk and colour
4252 $pdbks[$key] = $varPdbk;
4253 if ( $threshold > 0 ) {
4254 $size = $s->page_len
;
4255 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4256 $colours[$varPdbk] = 1;
4258 $colours[$varPdbk] = 2;
4262 $colours[$varPdbk] = 1;
4267 // check if the object is a variant of a category
4268 if(isset($categoryMap[$vardbk])){
4269 $oldkey = $categoryMap[$vardbk];
4270 if($oldkey != $vardbk)
4271 $varCategories[$oldkey]=$vardbk;
4275 // rebuild the categories in original order (if there are replacements)
4276 if(count($varCategories)>0){
4278 $originalCats = $this->mOutput
->getCategories();
4279 foreach($originalCats as $cat => $sortkey){
4280 // make the replacement
4281 if( array_key_exists($cat,$varCategories) )
4282 $newCats[$varCategories[$cat]] = $sortkey;
4283 else $newCats[$cat] = $sortkey;
4285 $this->mOutput
->setCategoryLinks($newCats);
4290 # Construct search and replace arrays
4291 wfProfileIn( $fname.'-construct' );
4292 $replacePairs = array();
4293 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4294 $pdbk = $pdbks[$key];
4295 $searchkey = "<!--LINK $key-->";
4296 $title = $this->mLinkHolders
['titles'][$key];
4297 if ( empty( $colours[$pdbk] ) ) {
4298 $linkCache->addBadLinkObj( $title );
4299 $colours[$pdbk] = 0;
4300 $this->mOutput
->addLink( $title, 0 );
4301 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4302 $this->mLinkHolders
['texts'][$key],
4303 $this->mLinkHolders
['queries'][$key] );
4304 } elseif ( $colours[$pdbk] == 1 ) {
4305 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4306 $this->mLinkHolders
['texts'][$key],
4307 $this->mLinkHolders
['queries'][$key] );
4308 } elseif ( $colours[$pdbk] == 2 ) {
4309 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4310 $this->mLinkHolders
['texts'][$key],
4311 $this->mLinkHolders
['queries'][$key] );
4314 $replacer = new HashtableReplacer( $replacePairs, 1 );
4315 wfProfileOut( $fname.'-construct' );
4318 wfProfileIn( $fname.'-replace' );
4319 $text = preg_replace_callback(
4320 '/(<!--LINK .*?-->)/',
4324 wfProfileOut( $fname.'-replace' );
4327 # Now process interwiki link holders
4328 # This is quite a bit simpler than internal links
4329 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4330 wfProfileIn( $fname.'-interwiki' );
4331 # Make interwiki link HTML
4332 $replacePairs = array();
4333 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4334 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4335 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4337 $replacer = new HashtableReplacer( $replacePairs, 1 );
4339 $text = preg_replace_callback(
4340 '/<!--IWLINK (.*?)-->/',
4343 wfProfileOut( $fname.'-interwiki' );
4346 wfProfileOut( $fname );
4351 * Replace <!--LINK--> link placeholders with plain text of links
4352 * (not HTML-formatted).
4353 * @param string $text
4356 function replaceLinkHoldersText( $text ) {
4357 $fname = 'Parser::replaceLinkHoldersText';
4358 wfProfileIn( $fname );
4360 $text = preg_replace_callback(
4361 '/<!--(LINK|IWLINK) (.*?)-->/',
4362 array( &$this, 'replaceLinkHoldersTextCallback' ),
4365 wfProfileOut( $fname );
4370 * @param array $matches
4374 function replaceLinkHoldersTextCallback( $matches ) {
4375 $type = $matches[1];
4377 if( $type == 'LINK' ) {
4378 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4379 return $this->mLinkHolders
['texts'][$key];
4381 } elseif( $type == 'IWLINK' ) {
4382 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4383 return $this->mInterwikiLinkHolders
['texts'][$key];
4390 * Tag hook handler for 'pre'.
4392 function renderPreTag( $text, $attribs ) {
4393 // Backwards-compatibility hack
4394 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4396 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4397 return wfOpenElement( 'pre', $attribs ) .
4398 Xml
::escapeTagsOnly( $content ) .
4403 * Renders an image gallery from a text with one line per image.
4404 * text labels may be given by using |-style alternative text. E.g.
4405 * Image:one.jpg|The number "1"
4406 * Image:tree.jpg|A tree
4407 * given as text will return the HTML of a gallery with two images,
4408 * labeled 'The number "1"' and
4411 function renderImageGallery( $text, $params ) {
4412 $ig = new ImageGallery();
4413 $ig->setContextTitle( $this->mTitle
);
4414 $ig->setShowBytes( false );
4415 $ig->setShowFilename( false );
4416 $ig->setParser( $this );
4417 $ig->setHideBadImages();
4418 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4419 $ig->useSkin( $this->mOptions
->getSkin() );
4420 $ig->mRevisionId
= $this->mRevisionId
;
4422 if( isset( $params['caption'] ) ) {
4423 $caption = $params['caption'];
4424 $caption = htmlspecialchars( $caption );
4425 $caption = $this->replaceInternalLinks( $caption );
4426 $ig->setCaptionHtml( $caption );
4428 if( isset( $params['perrow'] ) ) {
4429 $ig->setPerRow( $params['perrow'] );
4431 if( isset( $params['widths'] ) ) {
4432 $ig->setWidths( $params['widths'] );
4434 if( isset( $params['heights'] ) ) {
4435 $ig->setHeights( $params['heights'] );
4438 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4440 $lines = explode( "\n", $text );
4441 foreach ( $lines as $line ) {
4442 # match lines like these:
4443 # Image:someimage.jpg|This is some image
4445 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4447 if ( count( $matches ) == 0 ) {
4450 $tp = Title
::newFromText( $matches[1] );
4452 if( is_null( $nt ) ) {
4453 # Bogus title. Ignore these so we don't bomb out later.
4456 if ( isset( $matches[3] ) ) {
4457 $label = $matches[3];
4462 $pout = $this->parse( $label,
4465 false, // Strip whitespace...?
4466 false // Don't clear state!
4468 $html = $pout->getText();
4470 $ig->add( $nt, $html );
4472 # Only add real images (bug #5586)
4473 if ( $nt->getNamespace() == NS_IMAGE
) {
4474 $this->mOutput
->addImage( $nt->getDBkey() );
4477 return $ig->toHTML();
4480 function getImageParams( $handler ) {
4482 $handlerClass = get_class( $handler );
4486 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4487 // Initialise static lists
4488 static $internalParamNames = array(
4489 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4490 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4491 'bottom', 'text-bottom' ),
4492 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4493 'upright', 'border' ),
4495 static $internalParamMap;
4496 if ( !$internalParamMap ) {
4497 $internalParamMap = array();
4498 foreach ( $internalParamNames as $type => $names ) {
4499 foreach ( $names as $name ) {
4500 $magicName = str_replace( '-', '_', "img_$name" );
4501 $internalParamMap[$magicName] = array( $type, $name );
4506 // Add handler params
4507 $paramMap = $internalParamMap;
4509 $handlerParamMap = $handler->getParamMap();
4510 foreach ( $handlerParamMap as $magic => $paramName ) {
4511 $paramMap[$magic] = array( 'handler', $paramName );
4514 $this->mImageParams
[$handlerClass] = $paramMap;
4515 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4517 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4521 * Parse image options text and use it to make an image
4523 function makeImage( $title, $options ) {
4524 # @TODO: let the MediaHandler specify its transform parameters
4526 # Check if the options text is of the form "options|alt text"
4528 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4529 # * left no resizing, just left align. label is used for alt= only
4530 # * right same, but right aligned
4531 # * none same, but not aligned
4532 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4533 # * center center the image
4534 # * framed Keep original image size, no magnify-button.
4535 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4536 # * upright reduce width for upright images, rounded to full __0 px
4537 # * border draw a 1px border around the image
4538 # vertical-align values (no % or length right now):
4548 $parts = array_map( 'trim', explode( '|', $options) );
4549 $sk = $this->mOptions
->getSkin();
4551 # Give extensions a chance to select the file revision for us
4552 $skip = $time = false;
4553 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4556 return $sk->makeLinkObj( $title );
4560 $file = wfFindFile( $title, $time );
4561 $handler = $file ?
$file->getHandler() : false;
4563 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4565 # Process the input parameters
4567 $params = array( 'frame' => array(), 'handler' => array(),
4568 'horizAlign' => array(), 'vertAlign' => array() );
4569 foreach( $parts as $part ) {
4570 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4571 if ( isset( $paramMap[$magicName] ) ) {
4572 list( $type, $paramName ) = $paramMap[$magicName];
4573 $params[$type][$paramName] = $value;
4575 // Special case; width and height come in one variable together
4576 if( $type == 'handler' && $paramName == 'width' ) {
4578 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4579 $params[$type]['width'] = intval( $m[1] );
4580 $params[$type]['height'] = intval( $m[2] );
4582 $params[$type]['width'] = intval( $value );
4590 # Process alignment parameters
4591 if ( $params['horizAlign'] ) {
4592 $params['frame']['align'] = key( $params['horizAlign'] );
4594 if ( $params['vertAlign'] ) {
4595 $params['frame']['valign'] = key( $params['vertAlign'] );
4598 # Validate the handler parameters
4600 foreach ( $params['handler'] as $name => $value ) {
4601 if ( !$handler->validateParam( $name, $value ) ) {
4602 unset( $params['handler'][$name] );
4607 # Strip bad stuff out of the alt text
4608 $alt = $this->replaceLinkHoldersText( $caption );
4610 # make sure there are no placeholders in thumbnail attributes
4611 # that are later expanded to html- so expand them now and
4613 $alt = $this->mStripState
->unstripBoth( $alt );
4614 $alt = Sanitizer
::stripAllTags( $alt );
4616 $params['frame']['alt'] = $alt;
4617 $params['frame']['caption'] = $caption;
4619 # Linker does the rest
4620 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4622 # Give the handler a chance to modify the parser object
4624 $handler->parserTransformHook( $this, $file );
4631 * Set a flag in the output object indicating that the content is dynamic and
4632 * shouldn't be cached.
4634 function disableCache() {
4635 wfDebug( "Parser output marked as uncacheable.\n" );
4636 $this->mOutput
->mCacheTime
= -1;
4640 * Callback from the Sanitizer for expanding items found in HTML attribute
4641 * values, so they can be safely tested and escaped.
4642 * @param string $text
4643 * @param array $args
4647 function attributeStripCallback( &$text, $args ) {
4648 $text = $this->replaceVariables( $text, $args );
4649 $text = $this->mStripState
->unstripBoth( $text );
4658 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4659 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4660 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4666 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4671 * Break wikitext input into sections, and either pull or replace
4672 * some particular section's text.
4674 * External callers should use the getSection and replaceSection methods.
4676 * @param $text Page wikitext
4677 * @param $section Numbered section. 0 pulls the text before the first
4678 * heading; other numbers will pull the given section
4679 * along with its lower-level subsections.
4680 * @param $mode One of "get" or "replace"
4681 * @param $newtext Replacement text for section data.
4682 * @return string for "get", the extracted section text.
4683 * for "replace", the whole page with the section replaced.
4685 private function extractSections( $text, $section, $mode, $newtext='' ) {
4686 # I.... _hope_ this is right.
4687 # Otherwise, sometimes we don't have things initialized properly.
4688 $this->clearState();
4690 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4691 # comments to be stripped as well)
4692 $stripState = new StripState
;
4694 $oldOutputType = $this->mOutputType
;
4695 $oldOptions = $this->mOptions
;
4696 $this->mOptions
= new ParserOptions();
4697 $this->setOutputType( self
::OT_WIKI
);
4699 $striptext = $this->strip( $text, $stripState, true );
4701 $this->setOutputType( $oldOutputType );
4702 $this->mOptions
= $oldOptions;
4704 # now that we can be sure that no pseudo-sections are in the source,
4705 # split it up by section
4706 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4707 $comment = "(?:$uniq-!--.*?QINU\x07)";
4712 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4713 (=+) # Should this be limited to 6?
4714 .+? # Section title...
4715 \\2 # Ending = count must match start
4716 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4725 PREG_SPLIT_DELIM_CAPTURE
);
4727 if( $mode == "get" ) {
4728 if( $section == 0 ) {
4729 // "Section 0" returns the content before any other section.
4732 //track missing section, will replace if found.
4735 } elseif( $mode == "replace" ) {
4736 if( $section == 0 ) {
4737 $rv = $newtext . "\n\n";
4746 for( $index = 1; $index < count( $secs ); ) {
4747 $headerLine = $secs[$index++
];
4748 if( $secs[$index] ) {
4750 $headerLevel = strlen( $secs[$index++
] );
4754 $headerLevel = intval( $secs[$index++
] );
4756 $content = $secs[$index++
];
4759 if( $mode == "get" ) {
4760 if( $count == $section ) {
4761 $rv = $headerLine . $content;
4762 $sectionLevel = $headerLevel;
4763 } elseif( $count > $section ) {
4764 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4765 $rv .= $headerLine . $content;
4767 // Broke out to a higher-level section
4771 } elseif( $mode == "replace" ) {
4772 if( $count < $section ) {
4773 $rv .= $headerLine . $content;
4774 } elseif( $count == $section ) {
4775 $rv .= $newtext . "\n\n";
4776 $sectionLevel = $headerLevel;
4777 } elseif( $count > $section ) {
4778 if( $headerLevel <= $sectionLevel ) {
4779 // Passed the section's sub-parts.
4783 $rv .= $headerLine . $content;
4789 # reinsert stripped tags
4790 $rv = trim( $stripState->unstripBoth( $rv ) );
4796 * This function returns the text of a section, specified by a number ($section).
4797 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4798 * the first section before any such heading (section 0).
4800 * If a section contains subsections, these are also returned.
4802 * @param $text String: text to look in
4803 * @param $section Integer: section number
4804 * @param $deftext: default to return if section is not found
4805 * @return string text of the requested section
4807 public function getSection( $text, $section, $deftext='' ) {
4808 return $this->extractSections( $text, $section, "get", $deftext );
4811 public function replaceSection( $oldtext, $section, $text ) {
4812 return $this->extractSections( $oldtext, $section, "replace", $text );
4816 * Get the timestamp associated with the current revision, adjusted for
4817 * the default server-local timestamp
4819 function getRevisionTimestamp() {
4820 if ( is_null( $this->mRevisionTimestamp
) ) {
4821 wfProfileIn( __METHOD__
);
4823 $dbr = wfGetDB( DB_SLAVE
);
4824 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4825 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4827 // Normalize timestamp to internal MW format for timezone processing.
4828 // This has the added side-effect of replacing a null value with
4829 // the current time, which gives us more sensible behavior for
4831 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4833 // The cryptic '' timezone parameter tells to use the site-default
4834 // timezone offset instead of the user settings.
4836 // Since this value will be saved into the parser cache, served
4837 // to other users, and potentially even used inside links and such,
4838 // it needs to be consistent for all visitors.
4839 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4841 wfProfileOut( __METHOD__
);
4843 return $this->mRevisionTimestamp
;
4847 * Mutator for $mDefaultSort
4849 * @param $sort New value
4851 public function setDefaultSort( $sort ) {
4852 $this->mDefaultSort
= $sort;
4856 * Accessor for $mDefaultSort
4857 * Will use the title/prefixed title if none is set
4861 public function getDefaultSort() {
4862 if( $this->mDefaultSort
!== false ) {
4863 return $this->mDefaultSort
;
4865 return $this->mTitle
->getNamespace() == NS_CATEGORY
4866 ?
$this->mTitle
->getText()
4867 : $this->mTitle
->getPrefixedText();
4872 * Try to guess the section anchor name based on a wikitext fragment
4873 * presumably extracted from a heading, for example "Header" from
4876 public function guessSectionNameFromWikiText( $text ) {
4877 # Strip out wikitext links(they break the anchor)
4878 $text = $this->stripSectionName( $text );
4879 $headline = Sanitizer
::decodeCharReferences( $text );
4881 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4882 $headline = trim( $headline );
4883 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4884 $replacearray = array(
4889 array_keys( $replacearray ),
4890 array_values( $replacearray ),
4895 * Strips a text string of wikitext for use in a section anchor
4897 * Accepts a text string and then removes all wikitext from the
4898 * string and leaves only the resultant text (i.e. the result of
4899 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4900 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4901 * to create valid section anchors by mimicing the output of the
4902 * parser when headings are parsed.
4904 * @param $text string Text string to be stripped of wikitext
4905 * for use in a Section anchor
4906 * @return Filtered text string
4908 public function stripSectionName( $text ) {
4909 # Strip internal link markup
4910 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4911 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4913 # Strip external link markup (FIXME: Not Tolerant to blank link text
4914 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4915 # on how many empty links there are on the page - need to figure that out.
4916 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4918 # Parse wikitext quotes (italics & bold)
4919 $text = $this->doQuotes($text);
4922 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4927 * strip/replaceVariables/unstrip for preprocessor regression testing
4929 function srvus( $text ) {
4930 $text = $this->strip( $text, $this->mStripState
);
4931 $text = Sanitizer
::removeHTMLtags( $text );
4932 $text = $this->replaceVariables( $text );
4933 $text = preg_replace( '/<!--MWTEMPLATESECTION.*?-->/', '', $text );
4934 $text = $this->mStripState
->unstripBoth( $text );