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;
37 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
38 $mImageParams, $mImageParamsMagicArray, $mExtLinkBracketedRegex;
40 # Cleared with clearState():
41 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
42 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
43 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
44 var $mIncludeSizes, $mDefaultSort;
45 var $mTemplates, // cache of already loaded templates, avoids
46 // multiple SQL queries for the same string
47 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
48 // in this path. Used for loop detection.
51 # These are variables reset at least once per parse regardless of $clearState
52 var $mOptions, // ParserOptions object
53 $mTitle, // Title context, used for self-link rendering and similar things
54 $mOutputType, // Output type, one of the OT_xxx constants
55 $ot, // Shortcut alias, see setOutputType()
56 $mRevisionId, // ID to display in {{REVISIONID}} tags
57 $mRevisionTimestamp, // The timestamp of the specified revision ID
58 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
67 function __construct( $conf = array() ) {
68 $this->mTagHooks
= array();
69 $this->mTransparentTagHooks
= array();
70 $this->mFunctionHooks
= array();
71 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
72 $this->mFirstCall
= true;
73 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
74 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
78 * Do various kinds of initialisation on the first call of the parser
80 function firstCallInit() {
81 if ( !$this->mFirstCall
) {
85 wfProfileIn( __METHOD__
);
86 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
88 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
90 # Syntax for arguments (see self::setFunctionHook):
91 # "name for lookup in localized magic words array",
93 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
94 # instead of {{#int:...}})
95 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
96 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
97 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
98 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
99 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
100 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
101 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
102 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
103 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
104 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
105 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
106 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
107 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
108 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
109 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
110 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
111 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
112 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
113 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
114 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
115 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
116 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
117 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
118 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
119 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
120 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
121 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
123 if ( $wgAllowDisplayTitle ) {
124 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
126 if ( $wgAllowSlowParserFunctions ) {
127 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
130 $this->initialiseVariables();
131 $this->mFirstCall
= false;
132 wfProfileOut( __METHOD__
);
140 function clearState() {
141 wfProfileIn( __METHOD__
);
142 if ( $this->mFirstCall
) {
143 $this->firstCallInit();
145 $this->mOutput
= new ParserOutput
;
146 $this->mAutonumber
= 0;
147 $this->mLastSection
= '';
148 $this->mDTopen
= false;
149 $this->mIncludeCount
= array();
150 $this->mStripState
= new StripState
;
151 $this->mArgStack
= array();
152 $this->mInPre
= false;
153 $this->mInterwikiLinkHolders
= array(
157 $this->mLinkHolders
= array(
158 'namespaces' => array(),
160 'queries' => array(),
164 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
167 * Prefix for temporary replacement strings for the multipass parser.
168 * \x07 should never appear in input as it's disallowed in XML.
169 * Using it at the front also gives us a little extra robustness
170 * since it shouldn't match when butted up against identifier-like
173 $this->mUniqPrefix
= "\x07UNIQ" . self
::getRandomString();
175 # Clear these on every parse, bug 4549
176 $this->mTemplates
= array();
177 $this->mTemplatePath
= array();
179 $this->mShowToc
= true;
180 $this->mForceTocPosition
= false;
181 $this->mIncludeSizes
= array(
186 $this->mDefaultSort
= false;
188 wfRunHooks( 'ParserClearState', array( &$this ) );
189 wfProfileOut( __METHOD__
);
192 function setOutputType( $ot ) {
193 $this->mOutputType
= $ot;
196 'html' => $ot == OT_HTML
,
197 'wiki' => $ot == OT_WIKI
,
198 'msg' => $ot == OT_MSG
,
199 'pre' => $ot == OT_PREPROCESS
,
204 * Accessor for mUniqPrefix.
208 function uniqPrefix() {
209 return $this->mUniqPrefix
;
213 * Convert wikitext to HTML
214 * Do not call this function recursively.
216 * @param string $text Text we want to parse
217 * @param Title &$title A title object
218 * @param array $options
219 * @param boolean $linestart
220 * @param boolean $clearState
221 * @param int $revid number to pass in {{REVISIONID}}
222 * @return ParserOutput a ParserOutput
224 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
226 * First pass--just handle <nowiki> sections, pass the rest off
227 * to internalParse() which does all the real work.
230 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
231 $fname = 'Parser::parse-' . wfGetCaller();
232 wfProfileIn( __METHOD__
);
233 wfProfileIn( $fname );
239 $this->mOptions
= $options;
240 $this->mTitle
=& $title;
241 $oldRevisionId = $this->mRevisionId
;
242 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
243 if( $revid !== null ) {
244 $this->mRevisionId
= $revid;
245 $this->mRevisionTimestamp
= null;
247 $this->setOutputType( OT_HTML
);
248 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
249 $text = $this->strip( $text, $this->mStripState
);
250 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
251 $text = $this->internalParse( $text );
252 $text = $this->mStripState
->unstripGeneral( $text );
254 # Clean up special characters, only run once, next-to-last before doBlockLevels
256 # french spaces, last one Guillemet-left
257 # only if there is something before the space
258 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
259 # french spaces, Guillemet-right
260 '/(\\302\\253) /' => '\\1 ',
262 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
265 $text = $this->doBlockLevels( $text, $linestart );
267 $this->replaceLinkHolders( $text );
269 # the position of the parserConvert() call should not be changed. it
270 # assumes that the links are all replaced and the only thing left
271 # is the <nowiki> mark.
272 # Side-effects: this calls $this->mOutput->setTitleText()
273 $text = $wgContLang->parserConvert( $text, $this );
275 $text = $this->mStripState
->unstripNoWiki( $text );
277 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
279 //!JF Move to its own function
281 $uniq_prefix = $this->mUniqPrefix
;
283 $elements = array_keys( $this->mTransparentTagHooks
);
284 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
286 foreach( $matches as $marker => $data ) {
287 list( $element, $content, $params, $tag ) = $data;
288 $tagName = strtolower( $element );
289 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
290 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
291 array( $content, $params, $this ) );
295 $this->mStripState
->general
->setPair( $marker, $output );
297 $text = $this->mStripState
->unstripGeneral( $text );
299 $text = Sanitizer
::normalizeCharReferences( $text );
301 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
302 $text = self
::tidy($text);
304 # attempt to sanitize at least some nesting problems
305 # (bug #2702 and quite a few others)
307 # ''Something [http://www.cool.com cool''] -->
308 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
309 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
310 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
311 # fix up an anchor inside another anchor, only
312 # at least for a single single nested link (bug 3695)
313 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
314 '\\1\\2</a>\\3</a>\\1\\4</a>',
315 # fix div inside inline elements- doBlockLevels won't wrap a line which
316 # contains a div, so fix it up here; replace
317 # div with escaped text
318 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
319 '\\1\\3<div\\5>\\6</div>\\8\\9',
320 # remove empty italic or bold tag pairs, some
321 # introduced by rules above
322 '/<([bi])><\/\\1>/' => '',
325 $text = preg_replace(
326 array_keys( $tidyregs ),
327 array_values( $tidyregs ),
331 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
333 # Information on include size limits, for the benefit of users who try to skirt them
334 if ( $this->mOptions
->getEnableLimitReport() ) {
335 $max = $this->mOptions
->getMaxIncludeSize();
337 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']}/$max bytes\n" .
338 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
339 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
340 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
341 $text .= "<!-- \n$limitReport-->\n";
343 $this->mOutput
->setText( $text );
344 $this->mRevisionId
= $oldRevisionId;
345 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
346 wfProfileOut( $fname );
347 wfProfileOut( __METHOD__
);
349 return $this->mOutput
;
353 * Recursive parser entry point that can be called from an extension tag
356 function recursiveTagParse( $text ) {
357 wfProfileIn( __METHOD__
);
358 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
359 $text = $this->strip( $text, $this->mStripState
);
360 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
361 $text = $this->internalParse( $text );
362 wfProfileOut( __METHOD__
);
367 * Expand templates and variables in the text, producing valid, static wikitext.
368 * Also removes comments.
370 function preprocess( $text, $title, $options, $revid = null ) {
371 wfProfileIn( __METHOD__
);
373 $this->setOutputType( OT_PREPROCESS
);
374 $this->mOptions
= $options;
375 $this->mTitle
= $title;
376 if( $revid !== null ) {
377 $this->mRevisionId
= $revid;
379 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
380 $text = $this->strip( $text, $this->mStripState
);
381 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
382 if ( $this->mOptions
->getRemoveComments() ) {
383 $text = Sanitizer
::removeHTMLcomments( $text );
385 $text = $this->replaceVariables( $text );
386 $text = $this->mStripState
->unstripBoth( $text );
387 wfProfileOut( __METHOD__
);
392 * Get a random string
397 function getRandomString() {
398 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
401 function &getTitle() { return $this->mTitle
; }
402 function getOptions() { return $this->mOptions
; }
404 function getFunctionLang() {
405 global $wgLang, $wgContLang;
406 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
410 * Replaces all occurrences of HTML-style comments and the given tags
411 * in the text with a random marker and returns teh next text. The output
412 * parameter $matches will be an associative array filled with data in
414 * 'UNIQ-xxxxx' => array(
417 * array( 'param' => 'x' ),
418 * '<element param="x">tag content</element>' ) )
420 * @param $elements list of element names. Comments are always extracted.
421 * @param $text Source text string.
422 * @param $uniq_prefix
427 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
432 $taglist = implode( '|', $elements );
433 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
435 while ( '' != $text ) {
436 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
438 if( count( $p ) < 5 ) {
441 if( count( $p ) > 5 ) {
455 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
456 $stripped .= $marker;
458 if ( $close === '/>' ) {
459 // Empty element tag, <tag />
464 if( $element == '!--' ) {
467 $end = "/(<\\/$element\\s*>)/i";
469 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
471 if( count( $q ) < 3 ) {
472 # No end tag -- let it run out to the end of the text.
481 $matches[$marker] = array( $element,
483 Sanitizer
::decodeTagAttributes( $attributes ),
484 "<$element$attributes$close$content$tail" );
490 * Strips and renders nowiki, pre, math, hiero
491 * If $render is set, performs necessary rendering operations on plugins
492 * Returns the text, and fills an array with data needed in unstrip()
494 * @param StripState $state
496 * @param bool $stripcomments when set, HTML comments <!-- like this -->
497 * will be stripped in addition to other tags. This is important
498 * for section editing, where these comments cause confusion when
499 * counting the sections in the wikisource
501 * @param array dontstrip contains tags which should not be stripped;
502 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
506 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
508 wfProfileIn( __METHOD__
);
509 $render = ($this->mOutputType
== OT_HTML
);
511 $uniq_prefix = $this->mUniqPrefix
;
512 $commentState = new ReplacementArray
;
513 $nowikiItems = array();
514 $generalItems = array();
516 $elements = array_merge(
517 array( 'nowiki', 'gallery' ),
518 array_keys( $this->mTagHooks
) );
521 $elements[] = 'html';
523 if( $this->mOptions
->getUseTeX() ) {
524 $elements[] = 'math';
527 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
528 foreach ( $elements AS $k => $v ) {
529 if ( !in_array ( $v , $dontstrip ) ) continue;
530 unset ( $elements[$k] );
534 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
536 foreach( $matches as $marker => $data ) {
537 list( $element, $content, $params, $tag ) = $data;
539 $tagName = strtolower( $element );
540 wfProfileIn( __METHOD__
."-render-$tagName" );
544 if( substr( $tag, -3 ) == '-->' ) {
547 // Unclosed comment in input.
548 // Close it so later stripping can remove it
557 // Shouldn't happen otherwise. :)
559 $output = Xml
::escapeTagsOnly( $content );
562 $output = $wgContLang->armourMath(
563 MathRenderer
::renderMath( $content, $params ) );
566 $output = $this->renderImageGallery( $content, $params );
569 if( isset( $this->mTagHooks
[$tagName] ) ) {
570 $output = call_user_func_array( $this->mTagHooks
[$tagName],
571 array( $content, $params, $this ) );
573 throw new MWException( "Invalid call hook $element" );
576 wfProfileOut( __METHOD__
."-render-$tagName" );
578 // Just stripping tags; keep the source
582 // Unstrip the output, to support recursive strip() calls
583 $output = $state->unstripBoth( $output );
585 if( !$stripcomments && $element == '!--' ) {
586 $commentState->setPair( $marker, $output );
587 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
588 $nowikiItems[$marker] = $output;
590 $generalItems[$marker] = $output;
593 # Add the new items to the state
594 # We do this after the loop instead of during it to avoid slowing
595 # down the recursive unstrip
596 $state->nowiki
->mergeArray( $nowikiItems );
597 $state->general
->mergeArray( $generalItems );
599 # Unstrip comments unless explicitly told otherwise.
600 # (The comments are always stripped prior to this point, so as to
601 # not invoke any extension tags / parser hooks contained within
603 if ( !$stripcomments ) {
604 // Put them all back and forget them
605 $text = $commentState->replace( $text );
608 wfProfileOut( __METHOD__
);
613 * Restores pre, math, and other extensions removed by strip()
615 * always call unstripNoWiki() after this one
617 * @deprecated use $this->mStripState->unstrip()
619 function unstrip( $text, $state ) {
620 return $state->unstripGeneral( $text );
624 * Always call this after unstrip() to preserve the order
627 * @deprecated use $this->mStripState->unstrip()
629 function unstripNoWiki( $text, $state ) {
630 return $state->unstripNoWiki( $text );
634 * @deprecated use $this->mStripState->unstripBoth()
636 function unstripForHTML( $text ) {
637 return $this->mStripState
->unstripBoth( $text );
641 * Add an item to the strip state
642 * Returns the unique tag which must be inserted into the stripped text
643 * The tag will be replaced with the original text in unstrip()
647 function insertStripItem( $text, &$state ) {
648 $rnd = $this->mUniqPrefix
. '-item' . self
::getRandomString();
649 $state->general
->setPair( $rnd, $text );
654 * Interface with html tidy, used if $wgUseTidy = true.
655 * If tidy isn't able to correct the markup, the original will be
656 * returned in all its glory with a warning comment appended.
658 * Either the external tidy program or the in-process tidy extension
659 * will be used depending on availability. Override the default
660 * $wgTidyInternal setting to disable the internal if it's not working.
662 * @param string $text Hideous HTML input
663 * @return string Corrected HTML output
667 function tidy( $text ) {
668 global $wgTidyInternal;
669 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
670 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
671 '<head><title>test</title></head><body>'.$text.'</body></html>';
672 if( $wgTidyInternal ) {
673 $correctedtext = self
::internalTidy( $wrappedtext );
675 $correctedtext = self
::externalTidy( $wrappedtext );
677 if( is_null( $correctedtext ) ) {
678 wfDebug( "Tidy error detected!\n" );
679 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
681 return $correctedtext;
685 * Spawn an external HTML tidy process and get corrected markup back from it.
690 function externalTidy( $text ) {
691 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
692 $fname = 'Parser::externalTidy';
693 wfProfileIn( $fname );
698 $descriptorspec = array(
699 0 => array('pipe', 'r'),
700 1 => array('pipe', 'w'),
701 2 => array('file', wfGetNull(), 'a')
704 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
705 if (is_resource($process)) {
706 // Theoretically, this style of communication could cause a deadlock
707 // here. If the stdout buffer fills up, then writes to stdin could
708 // block. This doesn't appear to happen with tidy, because tidy only
709 // writes to stdout after it's finished reading from stdin. Search
710 // for tidyParseStdin and tidySaveStdout in console/tidy.c
711 fwrite($pipes[0], $text);
713 while (!feof($pipes[1])) {
714 $cleansource .= fgets($pipes[1], 1024);
717 proc_close($process);
720 wfProfileOut( $fname );
722 if( $cleansource == '' && $text != '') {
723 // Some kind of error happened, so we couldn't get the corrected text.
724 // Just give up; we'll use the source text and append a warning.
732 * Use the HTML tidy PECL extension to use the tidy library in-process,
733 * saving the overhead of spawning a new process.
735 * 'pear install tidy' should be able to compile the extension module.
740 function internalTidy( $text ) {
741 global $wgTidyConf, $IP;
742 $fname = 'Parser::internalTidy';
743 wfProfileIn( $fname );
746 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
747 $tidy->cleanRepair();
748 if( $tidy->getStatus() == 2 ) {
749 // 2 is magic number for fatal error
750 // http://www.php.net/manual/en/function.tidy-get-status.php
753 $cleansource = tidy_get_output( $tidy );
755 wfProfileOut( $fname );
760 * parse the wiki syntax used to render tables
764 function doTableStuff ( $text ) {
765 $fname = 'Parser::doTableStuff';
766 wfProfileIn( $fname );
768 $lines = explode ( "\n" , $text );
769 $td_history = array (); // Is currently a td tag open?
770 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
771 $tr_history = array (); // Is currently a tr tag open?
772 $tr_attributes = array (); // history of tr attributes
773 $has_opened_tr = array(); // Did this table open a <tr> element?
774 $indent_level = 0; // indent level of the table
775 foreach ( $lines as $key => $line )
777 $line = trim ( $line );
779 if( $line == '' ) { // empty line, go to next line
782 $first_character = $line{0};
785 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
786 // First check if we are starting a new table
787 $indent_level = strlen( $matches[1] );
789 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
790 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
792 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
793 array_push ( $td_history , false );
794 array_push ( $last_tag_history , '' );
795 array_push ( $tr_history , false );
796 array_push ( $tr_attributes , '' );
797 array_push ( $has_opened_tr , false );
798 } else if ( count ( $td_history ) == 0 ) {
799 // Don't do any of the following
801 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
802 // We are ending a table
803 $line = '</table>' . substr ( $line , 2 );
804 $last_tag = array_pop ( $last_tag_history );
806 if ( !array_pop ( $has_opened_tr ) ) {
807 $line = "<tr><td></td></tr>{$line}";
810 if ( array_pop ( $tr_history ) ) {
811 $line = "</tr>{$line}";
814 if ( array_pop ( $td_history ) ) {
815 $line = "</{$last_tag}>{$line}";
817 array_pop ( $tr_attributes );
818 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
819 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
820 // Now we have a table row
821 $line = preg_replace( '#^\|-+#', '', $line );
823 // Whats after the tag is now only attributes
824 $attributes = $this->mStripState
->unstripBoth( $line );
825 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
826 array_pop ( $tr_attributes );
827 array_push ( $tr_attributes , $attributes );
830 $last_tag = array_pop ( $last_tag_history );
831 array_pop ( $has_opened_tr );
832 array_push ( $has_opened_tr , true );
834 if ( array_pop ( $tr_history ) ) {
838 if ( array_pop ( $td_history ) ) {
839 $line = "</{$last_tag}>{$line}";
842 $lines[$key] = $line;
843 array_push ( $tr_history , false );
844 array_push ( $td_history , false );
845 array_push ( $last_tag_history , '' );
847 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
848 // This might be cell elements, td, th or captions
849 if ( substr ( $line , 0 , 2 ) == '|+' ) {
850 $first_character = '+';
851 $line = substr ( $line , 1 );
854 $line = substr ( $line , 1 );
856 if ( $first_character == '!' ) {
857 $line = str_replace ( '!!' , '||' , $line );
860 // Split up multiple cells on the same line.
861 // FIXME : This can result in improper nesting of tags processed
862 // by earlier parser steps, but should avoid splitting up eg
863 // attribute values containing literal "||".
864 $cells = StringUtils
::explodeMarkup( '||' , $line );
868 // Loop through each table cell
869 foreach ( $cells as $cell )
872 if ( $first_character != '+' )
874 $tr_after = array_pop ( $tr_attributes );
875 if ( !array_pop ( $tr_history ) ) {
876 $previous = "<tr{$tr_after}>\n";
878 array_push ( $tr_history , true );
879 array_push ( $tr_attributes , '' );
880 array_pop ( $has_opened_tr );
881 array_push ( $has_opened_tr , true );
884 $last_tag = array_pop ( $last_tag_history );
886 if ( array_pop ( $td_history ) ) {
887 $previous = "</{$last_tag}>{$previous}";
890 if ( $first_character == '|' ) {
892 } else if ( $first_character == '!' ) {
894 } else if ( $first_character == '+' ) {
895 $last_tag = 'caption';
900 array_push ( $last_tag_history , $last_tag );
902 // A cell could contain both parameters and data
903 $cell_data = explode ( '|' , $cell , 2 );
905 // Bug 553: Note that a '|' inside an invalid link should not
906 // be mistaken as delimiting cell parameters
907 if ( strpos( $cell_data[0], '[[' ) !== false ) {
908 $cell = "{$previous}<{$last_tag}>{$cell}";
909 } else if ( count ( $cell_data ) == 1 )
910 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
912 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
913 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
914 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
917 $lines[$key] .= $cell;
918 array_push ( $td_history , true );
923 // Closing open td, tr && table
924 while ( count ( $td_history ) > 0 )
926 if ( array_pop ( $td_history ) ) {
929 if ( array_pop ( $tr_history ) ) {
932 if ( !array_pop ( $has_opened_tr ) ) {
933 $lines[] = "<tr><td></td></tr>" ;
936 $lines[] = '</table>' ;
939 $output = implode ( "\n" , $lines ) ;
941 // special case: don't return empty table
942 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
946 wfProfileOut( $fname );
952 * Helper function for parse() that transforms wiki markup into
953 * HTML. Only called for $mOutputType == OT_HTML.
957 function internalParse( $text ) {
960 $fname = 'Parser::internalParse';
961 wfProfileIn( $fname );
963 # Hook to suspend the parser in this state
964 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
965 wfProfileOut( $fname );
969 # Remove <noinclude> tags and <includeonly> sections
970 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
971 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
972 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
974 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
976 $text = $this->replaceVariables( $text, $args );
977 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
979 // Tables need to come after variable replacement for things to work
980 // properly; putting them before other transformations should keep
981 // exciting things like link expansions from showing up in surprising
983 $text = $this->doTableStuff( $text );
985 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
987 $text = $this->stripToc( $text );
988 $this->stripNoGallery( $text );
989 $text = $this->doHeadings( $text );
990 if($this->mOptions
->getUseDynamicDates()) {
991 $df =& DateFormatter
::getInstance();
992 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
994 $text = $this->doAllQuotes( $text );
995 $text = $this->replaceInternalLinks( $text );
996 $text = $this->replaceExternalLinks( $text );
998 # replaceInternalLinks may sometimes leave behind
999 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1000 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1002 $text = $this->doMagicLinks( $text );
1003 $text = $this->formatHeadings( $text, $isMain );
1005 wfProfileOut( $fname );
1010 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1011 * magic external links.
1015 function &doMagicLinks( &$text ) {
1016 wfProfileIn( __METHOD__
);
1017 $text = preg_replace_callback(
1019 <a.*?</a> | # Skip link text
1020 <.*?> | # Skip stuff inside HTML elements
1021 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1022 ISBN\s+(\b # ISBN, capture number as m[2]
1023 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1024 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1025 [0-9Xx] # check digit
1027 )!x', array( &$this, 'magicLinkCallback' ), $text );
1028 wfProfileOut( __METHOD__
);
1032 function magicLinkCallback( $m ) {
1033 if ( substr( $m[0], 0, 1 ) == '<' ) {
1036 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1038 $num = strtr( $isbn, array(
1043 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1044 $text = '<a href="' .
1045 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1046 "\" class=\"internal\">ISBN $isbn</a>";
1048 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1052 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1054 $urlmsg = 'pubmedurl';
1057 throw new MWException( __METHOD__
.': unrecognised match type "' .
1058 substr($m[0], 0, 20 ) . '"' );
1061 $url = wfMsg( $urlmsg, $id);
1062 $sk = $this->mOptions
->getSkin();
1063 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1064 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1070 * Parse headers and return html
1074 function doHeadings( $text ) {
1075 $fname = 'Parser::doHeadings';
1076 wfProfileIn( $fname );
1077 for ( $i = 6; $i >= 1; --$i ) {
1078 $h = str_repeat( '=', $i );
1079 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1080 "<h{$i}>\\1</h{$i}>\\2", $text );
1082 wfProfileOut( $fname );
1087 * Replace single quotes with HTML markup
1089 * @return string the altered text
1091 function doAllQuotes( $text ) {
1092 $fname = 'Parser::doAllQuotes';
1093 wfProfileIn( $fname );
1095 $lines = explode( "\n", $text );
1096 foreach ( $lines as $line ) {
1097 $outtext .= $this->doQuotes ( $line ) . "\n";
1099 $outtext = substr($outtext, 0,-1);
1100 wfProfileOut( $fname );
1105 * Helper function for doAllQuotes()
1107 public function doQuotes( $text ) {
1108 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1109 if ( count( $arr ) == 1 )
1113 # First, do some preliminary work. This may shift some apostrophes from
1114 # being mark-up to being text. It also counts the number of occurrences
1115 # of bold and italics mark-ups.
1119 foreach ( $arr as $r )
1121 if ( ( $i %
2 ) == 1 )
1123 # If there are ever four apostrophes, assume the first is supposed to
1124 # be text, and the remaining three constitute mark-up for bold text.
1125 if ( strlen( $arr[$i] ) == 4 )
1130 # If there are more than 5 apostrophes in a row, assume they're all
1131 # text except for the last 5.
1132 else if ( strlen( $arr[$i] ) > 5 )
1134 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1137 # Count the number of occurrences of bold and italics mark-ups.
1138 # We are not counting sequences of five apostrophes.
1139 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1140 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1141 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1146 # If there is an odd number of both bold and italics, it is likely
1147 # that one of the bold ones was meant to be an apostrophe followed
1148 # by italics. Which one we cannot know for certain, but it is more
1149 # likely to be one that has a single-letter word before it.
1150 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1153 $firstsingleletterword = -1;
1154 $firstmultiletterword = -1;
1156 foreach ( $arr as $r )
1158 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1160 $x1 = substr ($arr[$i-1], -1);
1161 $x2 = substr ($arr[$i-1], -2, 1);
1163 if ($firstspace == -1) $firstspace = $i;
1164 } else if ($x2 == ' ') {
1165 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1167 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1173 # If there is a single-letter word, use it!
1174 if ($firstsingleletterword > -1)
1176 $arr [ $firstsingleletterword ] = "''";
1177 $arr [ $firstsingleletterword-1 ] .= "'";
1179 # If not, but there's a multi-letter word, use that one.
1180 else if ($firstmultiletterword > -1)
1182 $arr [ $firstmultiletterword ] = "''";
1183 $arr [ $firstmultiletterword-1 ] .= "'";
1185 # ... otherwise use the first one that has neither.
1186 # (notice that it is possible for all three to be -1 if, for example,
1187 # there is only one pentuple-apostrophe in the line)
1188 else if ($firstspace > -1)
1190 $arr [ $firstspace ] = "''";
1191 $arr [ $firstspace-1 ] .= "'";
1195 # Now let's actually convert our apostrophic mush to HTML!
1200 foreach ($arr as $r)
1204 if ($state == 'both')
1211 if (strlen ($r) == 2)
1214 { $output .= '</i>'; $state = ''; }
1215 else if ($state == 'bi')
1216 { $output .= '</i>'; $state = 'b'; }
1217 else if ($state == 'ib')
1218 { $output .= '</b></i><b>'; $state = 'b'; }
1219 else if ($state == 'both')
1220 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1221 else # $state can be 'b' or ''
1222 { $output .= '<i>'; $state .= 'i'; }
1224 else if (strlen ($r) == 3)
1227 { $output .= '</b>'; $state = ''; }
1228 else if ($state == 'bi')
1229 { $output .= '</i></b><i>'; $state = 'i'; }
1230 else if ($state == 'ib')
1231 { $output .= '</b>'; $state = 'i'; }
1232 else if ($state == 'both')
1233 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1234 else # $state can be 'i' or ''
1235 { $output .= '<b>'; $state .= 'b'; }
1237 else if (strlen ($r) == 5)
1240 { $output .= '</b><i>'; $state = 'i'; }
1241 else if ($state == 'i')
1242 { $output .= '</i><b>'; $state = 'b'; }
1243 else if ($state == 'bi')
1244 { $output .= '</i></b>'; $state = ''; }
1245 else if ($state == 'ib')
1246 { $output .= '</b></i>'; $state = ''; }
1247 else if ($state == 'both')
1248 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1249 else # ($state == '')
1250 { $buffer = ''; $state = 'both'; }
1255 # Now close all remaining tags. Notice that the order is important.
1256 if ($state == 'b' ||
$state == 'ib')
1258 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1262 # There might be lonely ''''', so make sure we have a buffer
1263 if ($state == 'both' && $buffer)
1264 $output .= '<b><i>'.$buffer.'</i></b>';
1270 * Replace external links
1272 * Note: this is all very hackish and the order of execution matters a lot.
1273 * Make sure to run maintenance/parserTests.php if you change this code.
1277 function replaceExternalLinks( $text ) {
1279 $fname = 'Parser::replaceExternalLinks';
1280 wfProfileIn( $fname );
1282 $sk = $this->mOptions
->getSkin();
1284 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1286 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1289 while ( $i<count( $bits ) ) {
1291 $protocol = $bits[$i++
];
1292 $text = $bits[$i++
];
1293 $trail = $bits[$i++
];
1295 # The characters '<' and '>' (which were escaped by
1296 # removeHTMLtags()) should not be included in
1297 # URLs, per RFC 2396.
1299 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1300 $text = substr($url, $m2[0][1]) . ' ' . $text;
1301 $url = substr($url, 0, $m2[0][1]);
1304 # If the link text is an image URL, replace it with an <img> tag
1305 # This happened by accident in the original parser, but some people used it extensively
1306 $img = $this->maybeMakeExternalImage( $text );
1307 if ( $img !== false ) {
1313 # Set linktype for CSS - if URL==text, link is essentially free
1314 $linktype = ($text == $url) ?
'free' : 'text';
1316 # No link text, e.g. [http://domain.tld/some.link]
1317 if ( $text == '' ) {
1318 # Autonumber if allowed. See bug #5918
1319 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1320 $text = '[' . ++
$this->mAutonumber
. ']';
1321 $linktype = 'autonumber';
1323 # Otherwise just use the URL
1324 $text = htmlspecialchars( $url );
1328 # Have link text, e.g. [http://domain.tld/some.link text]s
1330 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1333 $text = $wgContLang->markNoConversion($text);
1335 $url = Sanitizer
::cleanUrl( $url );
1337 # Process the trail (i.e. everything after this link up until start of the next link),
1338 # replacing any non-bracketed links
1339 $trail = $this->replaceFreeExternalLinks( $trail );
1341 # Use the encoded URL
1342 # This means that users can paste URLs directly into the text
1343 # Funny characters like ö aren't valid in URLs anyway
1344 # This was changed in August 2004
1345 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1347 # Register link in the output object.
1348 # Replace unnecessary URL escape codes with the referenced character
1349 # This prevents spammers from hiding links from the filters
1350 $pasteurized = self
::replaceUnusualEscapes( $url );
1351 $this->mOutput
->addExternalLink( $pasteurized );
1354 wfProfileOut( $fname );
1359 * Replace anything that looks like a URL with a link
1362 function replaceFreeExternalLinks( $text ) {
1364 $fname = 'Parser::replaceFreeExternalLinks';
1365 wfProfileIn( $fname );
1367 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1368 $s = array_shift( $bits );
1371 $sk = $this->mOptions
->getSkin();
1373 while ( $i < count( $bits ) ){
1374 $protocol = $bits[$i++
];
1375 $remainder = $bits[$i++
];
1378 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1379 # Found some characters after the protocol that look promising
1380 $url = $protocol . $m[1];
1383 # special case: handle urls as url args:
1384 # http://www.example.com/foo?=http://www.example.com/bar
1385 if(strlen($trail) == 0 &&
1387 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1388 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1391 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1396 # The characters '<' and '>' (which were escaped by
1397 # removeHTMLtags()) should not be included in
1398 # URLs, per RFC 2396.
1400 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1401 $trail = substr($url, $m2[0][1]) . $trail;
1402 $url = substr($url, 0, $m2[0][1]);
1405 # Move trailing punctuation to $trail
1407 # If there is no left bracket, then consider right brackets fair game too
1408 if ( strpos( $url, '(' ) === false ) {
1412 $numSepChars = strspn( strrev( $url ), $sep );
1413 if ( $numSepChars ) {
1414 $trail = substr( $url, -$numSepChars ) . $trail;
1415 $url = substr( $url, 0, -$numSepChars );
1418 $url = Sanitizer
::cleanUrl( $url );
1420 # Is this an external image?
1421 $text = $this->maybeMakeExternalImage( $url );
1422 if ( $text === false ) {
1423 # Not an image, make a link
1424 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1425 # Register it in the output object...
1426 # Replace unnecessary URL escape codes with their equivalent characters
1427 $pasteurized = self
::replaceUnusualEscapes( $url );
1428 $this->mOutput
->addExternalLink( $pasteurized );
1430 $s .= $text . $trail;
1432 $s .= $protocol . $remainder;
1435 wfProfileOut( $fname );
1440 * Replace unusual URL escape codes with their equivalent characters
1444 * @todo This can merge genuinely required bits in the path or query string,
1445 * breaking legit URLs. A proper fix would treat the various parts of
1446 * the URL differently; as a workaround, just use the output for
1447 * statistical records, not for actual linking/output.
1449 static function replaceUnusualEscapes( $url ) {
1450 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1451 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1455 * Callback function used in replaceUnusualEscapes().
1456 * Replaces unusual URL escape codes with their equivalent character
1460 private static function replaceUnusualEscapesCallback( $matches ) {
1461 $char = urldecode( $matches[0] );
1462 $ord = ord( $char );
1463 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1464 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1465 // No, shouldn't be escaped
1468 // Yes, leave it escaped
1474 * make an image if it's allowed, either through the global
1475 * option or through the exception
1478 function maybeMakeExternalImage( $url ) {
1479 $sk = $this->mOptions
->getSkin();
1480 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1481 $imagesexception = !empty($imagesfrom);
1483 if ( $this->mOptions
->getAllowExternalImages()
1484 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1485 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1487 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1494 * Process [[ ]] wikilinks
1498 function replaceInternalLinks( $s ) {
1500 static $fname = 'Parser::replaceInternalLinks' ;
1502 wfProfileIn( $fname );
1504 wfProfileIn( $fname.'-setup' );
1506 # the % is needed to support urlencoded titles as well
1507 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1509 $sk = $this->mOptions
->getSkin();
1511 #split the entire text string on occurences of [[
1512 $a = explode( '[[', ' ' . $s );
1513 #get the first element (all text up to first [[), and remove the space we added
1514 $s = array_shift( $a );
1515 $s = substr( $s, 1 );
1517 # Match a link having the form [[namespace:link|alternate]]trail
1519 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1520 # Match cases where there is no "]]", which might still be images
1521 static $e1_img = FALSE;
1522 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1523 # Match the end of a line for a word that's not followed by whitespace,
1524 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1525 $e2 = wfMsgForContent( 'linkprefix' );
1527 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1528 if( is_null( $this->mTitle
) ) {
1529 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1531 $nottalk = !$this->mTitle
->isTalkPage();
1533 if ( $useLinkPrefixExtension ) {
1535 if ( preg_match( $e2, $s, $m ) ) {
1536 $first_prefix = $m[2];
1538 $first_prefix = false;
1544 if($wgContLang->hasVariants()) {
1545 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1547 $selflink = array($this->mTitle
->getPrefixedText());
1549 $useSubpages = $this->areSubpagesAllowed();
1550 wfProfileOut( $fname.'-setup' );
1552 # Loop for each link
1553 for ($k = 0; isset( $a[$k] ); $k++
) {
1555 if ( $useLinkPrefixExtension ) {
1556 wfProfileIn( $fname.'-prefixhandling' );
1557 if ( preg_match( $e2, $s, $m ) ) {
1565 $prefix = $first_prefix;
1566 $first_prefix = false;
1568 wfProfileOut( $fname.'-prefixhandling' );
1571 $might_be_img = false;
1573 wfProfileIn( "$fname-e1" );
1574 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1576 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1577 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1578 # the real problem is with the $e1 regex
1581 # Still some problems for cases where the ] is meant to be outside punctuation,
1582 # and no image is in sight. See bug 2095.
1585 substr( $m[3], 0, 1 ) === ']' &&
1586 strpos($text, '[') !== false
1589 $text .= ']'; # so that replaceExternalLinks($text) works later
1590 $m[3] = substr( $m[3], 1 );
1592 # fix up urlencoded title texts
1593 if( strpos( $m[1], '%' ) !== false ) {
1594 # Should anchors '#' also be rejected?
1595 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1598 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1599 $might_be_img = true;
1601 if ( strpos( $m[1], '%' ) !== false ) {
1602 $m[1] = urldecode($m[1]);
1605 } else { # Invalid form; output directly
1606 $s .= $prefix . '[[' . $line ;
1607 wfProfileOut( "$fname-e1" );
1610 wfProfileOut( "$fname-e1" );
1611 wfProfileIn( "$fname-misc" );
1613 # Don't allow internal links to pages containing
1614 # PROTO: where PROTO is a valid URL protocol; these
1615 # should be external links.
1616 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1617 $s .= $prefix . '[[' . $line ;
1621 # Make subpage if necessary
1622 if( $useSubpages ) {
1623 $link = $this->maybeDoSubpageLink( $m[1], $text );
1628 $noforce = (substr($m[1], 0, 1) != ':');
1630 # Strip off leading ':'
1631 $link = substr($link, 1);
1634 wfProfileOut( "$fname-misc" );
1635 wfProfileIn( "$fname-title" );
1636 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1638 $s .= $prefix . '[[' . $line;
1639 wfProfileOut( "$fname-title" );
1643 $ns = $nt->getNamespace();
1644 $iw = $nt->getInterWiki();
1645 wfProfileOut( "$fname-title" );
1647 if ($might_be_img) { # if this is actually an invalid link
1648 wfProfileIn( "$fname-might_be_img" );
1649 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1651 while (isset ($a[$k+
1]) ) {
1652 #look at the next 'line' to see if we can close it there
1653 $spliced = array_splice( $a, $k +
1, 1 );
1654 $next_line = array_shift( $spliced );
1655 $m = explode( ']]', $next_line, 3 );
1656 if ( count( $m ) == 3 ) {
1657 # the first ]] closes the inner link, the second the image
1659 $text .= "[[{$m[0]}]]{$m[1]}";
1662 } elseif ( count( $m ) == 2 ) {
1663 #if there's exactly one ]] that's fine, we'll keep looking
1664 $text .= "[[{$m[0]}]]{$m[1]}";
1666 #if $next_line is invalid too, we need look no further
1667 $text .= '[[' . $next_line;
1672 # we couldn't find the end of this imageLink, so output it raw
1673 #but don't ignore what might be perfectly normal links in the text we've examined
1674 $text = $this->replaceInternalLinks($text);
1675 $s .= "{$prefix}[[$link|$text";
1676 # note: no $trail, because without an end, there *is* no trail
1677 wfProfileOut( "$fname-might_be_img" );
1680 } else { #it's not an image, so output it raw
1681 $s .= "{$prefix}[[$link|$text";
1682 # note: no $trail, because without an end, there *is* no trail
1683 wfProfileOut( "$fname-might_be_img" );
1686 wfProfileOut( "$fname-might_be_img" );
1689 $wasblank = ( '' == $text );
1690 if( $wasblank ) $text = $link;
1692 # Link not escaped by : , create the various objects
1696 wfProfileIn( "$fname-interwiki" );
1697 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1698 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1699 $s = rtrim($s . $prefix);
1700 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1701 wfProfileOut( "$fname-interwiki" );
1704 wfProfileOut( "$fname-interwiki" );
1706 if ( $ns == NS_IMAGE
) {
1707 wfProfileIn( "$fname-image" );
1708 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1709 # recursively parse links inside the image caption
1710 # actually, this will parse them in any other parameters, too,
1711 # but it might be hard to fix that, and it doesn't matter ATM
1712 $text = $this->replaceExternalLinks($text);
1713 $text = $this->replaceInternalLinks($text);
1715 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1716 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1717 $this->mOutput
->addImage( $nt->getDBkey() );
1719 wfProfileOut( "$fname-image" );
1722 # We still need to record the image's presence on the page
1723 $this->mOutput
->addImage( $nt->getDBkey() );
1725 wfProfileOut( "$fname-image" );
1729 if ( $ns == NS_CATEGORY
) {
1730 wfProfileIn( "$fname-category" );
1731 $s = rtrim($s . "\n"); # bug 87
1734 $sortkey = $this->getDefaultSort();
1738 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1739 $sortkey = str_replace( "\n", '', $sortkey );
1740 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1741 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1744 * Strip the whitespace Category links produce, see bug 87
1745 * @todo We might want to use trim($tmp, "\n") here.
1747 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1749 wfProfileOut( "$fname-category" );
1754 # Self-link checking
1755 if( $nt->getFragment() === '' ) {
1756 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1757 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1762 # Special and Media are pseudo-namespaces; no pages actually exist in them
1763 if( $ns == NS_MEDIA
) {
1764 $link = $sk->makeMediaLinkObj( $nt, $text );
1765 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1766 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1767 $this->mOutput
->addImage( $nt->getDBkey() );
1769 } elseif( $ns == NS_SPECIAL
) {
1770 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1771 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1773 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1776 } elseif( $ns == NS_IMAGE
) {
1777 $img = wfFindFile( $nt );
1779 // Force a blue link if the file exists; may be a remote
1780 // upload on the shared repository, and we want to see its
1781 // auto-generated page.
1782 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1783 $this->mOutput
->addLink( $nt );
1787 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1789 wfProfileOut( $fname );
1794 * Make a link placeholder. The text returned can be later resolved to a real link with
1795 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1796 * parsing of interwiki links, and secondly to allow all existence checks and
1797 * article length checks (for stub links) to be bundled into a single query.
1800 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1801 wfProfileIn( __METHOD__
);
1802 if ( ! is_object($nt) ) {
1804 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1806 # Separate the link trail from the rest of the link
1807 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1809 if ( $nt->isExternal() ) {
1810 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1811 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1812 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1814 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1815 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1816 $this->mLinkHolders
['queries'][] = $query;
1817 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1818 $this->mLinkHolders
['titles'][] = $nt;
1820 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1823 wfProfileOut( __METHOD__
);
1828 * Render a forced-blue link inline; protect against double expansion of
1829 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1830 * Since this little disaster has to split off the trail text to avoid
1831 * breaking URLs in the following text without breaking trails on the
1832 * wiki links, it's been made into a horrible function.
1835 * @param string $text
1836 * @param string $query
1837 * @param string $trail
1838 * @param string $prefix
1839 * @return string HTML-wikitext mix oh yuck
1841 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1842 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1843 $sk = $this->mOptions
->getSkin();
1844 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1845 return $this->armorLinks( $link ) . $trail;
1849 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1850 * going to go through further parsing steps before inline URL expansion.
1852 * In particular this is important when using action=render, which causes
1853 * full URLs to be included.
1855 * Oh man I hate our multi-layer parser!
1857 * @param string more-or-less HTML
1858 * @return string less-or-more HTML with NOPARSE bits
1860 function armorLinks( $text ) {
1861 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1862 "{$this->mUniqPrefix}NOPARSE$1", $text );
1866 * Return true if subpage links should be expanded on this page.
1869 function areSubpagesAllowed() {
1870 # Some namespaces don't allow subpages
1871 global $wgNamespacesWithSubpages;
1872 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1876 * Handle link to subpage if necessary
1877 * @param string $target the source of the link
1878 * @param string &$text the link text, modified as necessary
1879 * @return string the full name of the link
1882 function maybeDoSubpageLink($target, &$text) {
1885 # :Foobar -- override special treatment of prefix (images, language links)
1886 # /Foobar -- convert to CurrentPage/Foobar
1887 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1888 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1889 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1891 $fname = 'Parser::maybeDoSubpageLink';
1892 wfProfileIn( $fname );
1893 $ret = $target; # default return value is no change
1895 # Some namespaces don't allow subpages,
1896 # so only perform processing if subpages are allowed
1897 if( $this->areSubpagesAllowed() ) {
1898 $hash = strpos( $target, '#' );
1899 if( $hash !== false ) {
1900 $suffix = substr( $target, $hash );
1901 $target = substr( $target, 0, $hash );
1906 $target = trim( $target );
1907 # Look at the first character
1908 if( $target != '' && $target{0} == '/' ) {
1909 # / at end means we don't want the slash to be shown
1911 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1912 if( $trailingSlashes ) {
1913 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1915 $noslash = substr( $target, 1 );
1918 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1919 if( '' === $text ) {
1920 $text = $target . $suffix;
1921 } # this might be changed for ugliness reasons
1923 # check for .. subpage backlinks
1925 $nodotdot = $target;
1926 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1928 $nodotdot = substr( $nodotdot, 3 );
1930 if($dotdotcount > 0) {
1931 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1932 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1933 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1934 # / at the end means don't show full path
1935 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1936 $nodotdot = substr( $nodotdot, 0, -1 );
1937 if( '' === $text ) {
1938 $text = $nodotdot . $suffix;
1941 $nodotdot = trim( $nodotdot );
1942 if( $nodotdot != '' ) {
1943 $ret .= '/' . $nodotdot;
1951 wfProfileOut( $fname );
1956 * Used by doBlockLevels()
1959 /* private */ function closeParagraph() {
1961 if ( '' != $this->mLastSection
) {
1962 $result = '</' . $this->mLastSection
. ">\n";
1964 $this->mInPre
= false;
1965 $this->mLastSection
= '';
1968 # getCommon() returns the length of the longest common substring
1969 # of both arguments, starting at the beginning of both.
1971 /* private */ function getCommon( $st1, $st2 ) {
1972 $fl = strlen( $st1 );
1973 $shorter = strlen( $st2 );
1974 if ( $fl < $shorter ) { $shorter = $fl; }
1976 for ( $i = 0; $i < $shorter; ++
$i ) {
1977 if ( $st1{$i} != $st2{$i} ) { break; }
1981 # These next three functions open, continue, and close the list
1982 # element appropriate to the prefix character passed into them.
1984 /* private */ function openList( $char ) {
1985 $result = $this->closeParagraph();
1987 if ( '*' == $char ) { $result .= '<ul><li>'; }
1988 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1989 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1990 else if ( ';' == $char ) {
1991 $result .= '<dl><dt>';
1992 $this->mDTopen
= true;
1994 else { $result = '<!-- ERR 1 -->'; }
1999 /* private */ function nextItem( $char ) {
2000 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2001 else if ( ':' == $char ||
';' == $char ) {
2003 if ( $this->mDTopen
) { $close = '</dt>'; }
2004 if ( ';' == $char ) {
2005 $this->mDTopen
= true;
2006 return $close . '<dt>';
2008 $this->mDTopen
= false;
2009 return $close . '<dd>';
2012 return '<!-- ERR 2 -->';
2015 /* private */ function closeList( $char ) {
2016 if ( '*' == $char ) { $text = '</li></ul>'; }
2017 else if ( '#' == $char ) { $text = '</li></ol>'; }
2018 else if ( ':' == $char ) {
2019 if ( $this->mDTopen
) {
2020 $this->mDTopen
= false;
2021 $text = '</dt></dl>';
2023 $text = '</dd></dl>';
2026 else { return '<!-- ERR 3 -->'; }
2032 * Make lists from lines starting with ':', '*', '#', etc.
2035 * @return string the lists rendered as HTML
2037 function doBlockLevels( $text, $linestart ) {
2038 $fname = 'Parser::doBlockLevels';
2039 wfProfileIn( $fname );
2041 # Parsing through the text line by line. The main thing
2042 # happening here is handling of block-level elements p, pre,
2043 # and making lists from lines starting with * # : etc.
2045 $textLines = explode( "\n", $text );
2047 $lastPrefix = $output = '';
2048 $this->mDTopen
= $inBlockElem = false;
2050 $paragraphStack = false;
2052 if ( !$linestart ) {
2053 $output .= array_shift( $textLines );
2055 foreach ( $textLines as $oLine ) {
2056 $lastPrefixLength = strlen( $lastPrefix );
2057 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2058 $preOpenMatch = preg_match('/<pre/i', $oLine );
2059 if ( !$this->mInPre
) {
2060 # Multiple prefixes may abut each other for nested lists.
2061 $prefixLength = strspn( $oLine, '*#:;' );
2062 $pref = substr( $oLine, 0, $prefixLength );
2065 $pref2 = str_replace( ';', ':', $pref );
2066 $t = substr( $oLine, $prefixLength );
2067 $this->mInPre
= !empty($preOpenMatch);
2069 # Don't interpret any other prefixes in preformatted text
2071 $pref = $pref2 = '';
2076 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2077 # Same as the last item, so no need to deal with nesting or opening stuff
2078 $output .= $this->nextItem( substr( $pref, -1 ) );
2079 $paragraphStack = false;
2081 if ( substr( $pref, -1 ) == ';') {
2082 # The one nasty exception: definition lists work like this:
2083 # ; title : definition text
2084 # So we check for : in the remainder text to split up the
2085 # title and definition, without b0rking links.
2087 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2089 $output .= $term . $this->nextItem( ':' );
2092 } elseif( $prefixLength ||
$lastPrefixLength ) {
2093 # Either open or close a level...
2094 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2095 $paragraphStack = false;
2097 while( $commonPrefixLength < $lastPrefixLength ) {
2098 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2099 --$lastPrefixLength;
2101 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2102 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2104 while ( $prefixLength > $commonPrefixLength ) {
2105 $char = substr( $pref, $commonPrefixLength, 1 );
2106 $output .= $this->openList( $char );
2108 if ( ';' == $char ) {
2109 # FIXME: This is dupe of code above
2110 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2112 $output .= $term . $this->nextItem( ':' );
2115 ++
$commonPrefixLength;
2117 $lastPrefix = $pref2;
2119 if( 0 == $prefixLength ) {
2120 wfProfileIn( "$fname-paragraph" );
2121 # No prefix (not in list)--go to paragraph mode
2122 // XXX: use a stack for nestable elements like span, table and div
2123 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2124 $closematch = preg_match(
2125 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2126 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2127 if ( $openmatch or $closematch ) {
2128 $paragraphStack = false;
2129 #Â TODO bug 5718: paragraph closed
2130 $output .= $this->closeParagraph();
2131 if ( $preOpenMatch and !$preCloseMatch ) {
2132 $this->mInPre
= true;
2134 if ( $closematch ) {
2135 $inBlockElem = false;
2137 $inBlockElem = true;
2139 } else if ( !$inBlockElem && !$this->mInPre
) {
2140 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2142 if ($this->mLastSection
!= 'pre') {
2143 $paragraphStack = false;
2144 $output .= $this->closeParagraph().'<pre>';
2145 $this->mLastSection
= 'pre';
2147 $t = substr( $t, 1 );
2150 if ( '' == trim($t) ) {
2151 if ( $paragraphStack ) {
2152 $output .= $paragraphStack.'<br />';
2153 $paragraphStack = false;
2154 $this->mLastSection
= 'p';
2156 if ($this->mLastSection
!= 'p' ) {
2157 $output .= $this->closeParagraph();
2158 $this->mLastSection
= '';
2159 $paragraphStack = '<p>';
2161 $paragraphStack = '</p><p>';
2165 if ( $paragraphStack ) {
2166 $output .= $paragraphStack;
2167 $paragraphStack = false;
2168 $this->mLastSection
= 'p';
2169 } else if ($this->mLastSection
!= 'p') {
2170 $output .= $this->closeParagraph().'<p>';
2171 $this->mLastSection
= 'p';
2176 wfProfileOut( "$fname-paragraph" );
2178 // somewhere above we forget to get out of pre block (bug 785)
2179 if($preCloseMatch && $this->mInPre
) {
2180 $this->mInPre
= false;
2182 if ($paragraphStack === false) {
2186 while ( $prefixLength ) {
2187 $output .= $this->closeList( $pref2{$prefixLength-1} );
2190 if ( '' != $this->mLastSection
) {
2191 $output .= '</' . $this->mLastSection
. '>';
2192 $this->mLastSection
= '';
2195 wfProfileOut( $fname );
2200 * Split up a string on ':', ignoring any occurences inside tags
2201 * to prevent illegal overlapping.
2202 * @param string $str the string to split
2203 * @param string &$before set to everything before the ':'
2204 * @param string &$after set to everything after the ':'
2205 * return string the position of the ':', or false if none found
2207 function findColonNoLinks($str, &$before, &$after) {
2208 $fname = 'Parser::findColonNoLinks';
2209 wfProfileIn( $fname );
2211 $pos = strpos( $str, ':' );
2212 if( $pos === false ) {
2214 wfProfileOut( $fname );
2218 $lt = strpos( $str, '<' );
2219 if( $lt === false ||
$lt > $pos ) {
2220 // Easy; no tag nesting to worry about
2221 $before = substr( $str, 0, $pos );
2222 $after = substr( $str, $pos+
1 );
2223 wfProfileOut( $fname );
2227 // Ugly state machine to walk through avoiding tags.
2228 $state = self
::COLON_STATE_TEXT
;
2230 $len = strlen( $str );
2231 for( $i = 0; $i < $len; $i++
) {
2235 // (Using the number is a performance hack for common cases)
2236 case 0: // self::COLON_STATE_TEXT:
2239 // Could be either a <start> tag or an </end> tag
2240 $state = self
::COLON_STATE_TAGSTART
;
2245 $before = substr( $str, 0, $i );
2246 $after = substr( $str, $i +
1 );
2247 wfProfileOut( $fname );
2250 // Embedded in a tag; don't break it.
2253 // Skip ahead looking for something interesting
2254 $colon = strpos( $str, ':', $i );
2255 if( $colon === false ) {
2256 // Nothing else interesting
2257 wfProfileOut( $fname );
2260 $lt = strpos( $str, '<', $i );
2261 if( $stack === 0 ) {
2262 if( $lt === false ||
$colon < $lt ) {
2264 $before = substr( $str, 0, $colon );
2265 $after = substr( $str, $colon +
1 );
2266 wfProfileOut( $fname );
2270 if( $lt === false ) {
2271 // Nothing else interesting to find; abort!
2272 // We're nested, but there's no close tags left. Abort!
2275 // Skip ahead to next tag start
2277 $state = self
::COLON_STATE_TAGSTART
;
2280 case 1: // self::COLON_STATE_TAG:
2285 $state = self
::COLON_STATE_TEXT
;
2288 // Slash may be followed by >?
2289 $state = self
::COLON_STATE_TAGSLASH
;
2295 case 2: // self::COLON_STATE_TAGSTART:
2298 $state = self
::COLON_STATE_CLOSETAG
;
2301 $state = self
::COLON_STATE_COMMENT
;
2304 // Illegal early close? This shouldn't happen D:
2305 $state = self
::COLON_STATE_TEXT
;
2308 $state = self
::COLON_STATE_TAG
;
2311 case 3: // self::COLON_STATE_CLOSETAG:
2316 wfDebug( "Invalid input in $fname; too many close tags\n" );
2317 wfProfileOut( $fname );
2320 $state = self
::COLON_STATE_TEXT
;
2323 case self
::COLON_STATE_TAGSLASH
:
2325 // Yes, a self-closed tag <blah/>
2326 $state = self
::COLON_STATE_TEXT
;
2328 // Probably we're jumping the gun, and this is an attribute
2329 $state = self
::COLON_STATE_TAG
;
2332 case 5: // self::COLON_STATE_COMMENT:
2334 $state = self
::COLON_STATE_COMMENTDASH
;
2337 case self
::COLON_STATE_COMMENTDASH
:
2339 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2341 $state = self
::COLON_STATE_COMMENT
;
2344 case self
::COLON_STATE_COMMENTDASHDASH
:
2346 $state = self
::COLON_STATE_TEXT
;
2348 $state = self
::COLON_STATE_COMMENT
;
2352 throw new MWException( "State machine error in $fname" );
2356 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2359 wfProfileOut( $fname );
2364 * Return value of a magic variable (like PAGENAME)
2368 function getVariableValue( $index ) {
2369 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2372 * Some of these require message or data lookups and can be
2373 * expensive to check many times.
2375 static $varCache = array();
2376 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2377 if ( isset( $varCache[$index] ) ) {
2378 return $varCache[$index];
2383 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2386 global $wgLocaltimezone;
2387 if ( isset( $wgLocaltimezone ) ) {
2388 $oldtz = getenv( 'TZ' );
2389 putenv( 'TZ='.$wgLocaltimezone );
2392 wfSuppressWarnings(); // E_STRICT system time bitching
2393 $localTimestamp = date( 'YmdHis', $ts );
2394 $localMonth = date( 'm', $ts );
2395 $localMonthName = date( 'n', $ts );
2396 $localDay = date( 'j', $ts );
2397 $localDay2 = date( 'd', $ts );
2398 $localDayOfWeek = date( 'w', $ts );
2399 $localWeek = date( 'W', $ts );
2400 $localYear = date( 'Y', $ts );
2401 $localHour = date( 'H', $ts );
2402 if ( isset( $wgLocaltimezone ) ) {
2403 putenv( 'TZ='.$oldtz );
2405 wfRestoreWarnings();
2408 case 'currentmonth':
2409 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2410 case 'currentmonthname':
2411 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2412 case 'currentmonthnamegen':
2413 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2414 case 'currentmonthabbrev':
2415 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2417 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2419 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2421 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2422 case 'localmonthname':
2423 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2424 case 'localmonthnamegen':
2425 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2426 case 'localmonthabbrev':
2427 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2429 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2431 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2433 return wfEscapeWikiText( $this->mTitle
->getText() );
2435 return $this->mTitle
->getPartialURL();
2436 case 'fullpagename':
2437 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2438 case 'fullpagenamee':
2439 return $this->mTitle
->getPrefixedURL();
2441 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2442 case 'subpagenamee':
2443 return $this->mTitle
->getSubpageUrlForm();
2444 case 'basepagename':
2445 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2446 case 'basepagenamee':
2447 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2448 case 'talkpagename':
2449 if( $this->mTitle
->canTalk() ) {
2450 $talkPage = $this->mTitle
->getTalkPage();
2451 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2455 case 'talkpagenamee':
2456 if( $this->mTitle
->canTalk() ) {
2457 $talkPage = $this->mTitle
->getTalkPage();
2458 return $talkPage->getPrefixedUrl();
2462 case 'subjectpagename':
2463 $subjPage = $this->mTitle
->getSubjectPage();
2464 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2465 case 'subjectpagenamee':
2466 $subjPage = $this->mTitle
->getSubjectPage();
2467 return $subjPage->getPrefixedUrl();
2469 return $this->mRevisionId
;
2471 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2472 case 'revisionday2':
2473 return substr( $this->getRevisionTimestamp(), 6, 2 );
2474 case 'revisionmonth':
2475 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2476 case 'revisionyear':
2477 return substr( $this->getRevisionTimestamp(), 0, 4 );
2478 case 'revisiontimestamp':
2479 return $this->getRevisionTimestamp();
2481 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2483 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2485 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2487 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2488 case 'subjectspace':
2489 return $this->mTitle
->getSubjectNsText();
2490 case 'subjectspacee':
2491 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2492 case 'currentdayname':
2493 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2495 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2497 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2499 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2501 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2502 // int to remove the padding
2503 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2505 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2506 case 'localdayname':
2507 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2509 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2511 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2513 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2515 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2516 // int to remove the padding
2517 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2519 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2520 case 'numberofarticles':
2521 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2522 case 'numberoffiles':
2523 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2524 case 'numberofusers':
2525 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2526 case 'numberofpages':
2527 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2528 case 'numberofadmins':
2529 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2530 case 'numberofedits':
2531 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2532 case 'currenttimestamp':
2533 return $varCache[$index] = wfTimestampNow();
2534 case 'localtimestamp':
2535 return $varCache[$index] = $localTimestamp;
2536 case 'currentversion':
2537 return $varCache[$index] = SpecialVersion
::getVersion();
2543 return $wgServerName;
2545 return $wgScriptPath;
2546 case 'directionmark':
2547 return $wgContLang->getDirMark();
2548 case 'contentlanguage':
2549 global $wgContLanguageCode;
2550 return $wgContLanguageCode;
2553 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2561 * initialise the magic variables (like CURRENTMONTHNAME)
2565 function initialiseVariables() {
2566 $fname = 'Parser::initialiseVariables';
2567 wfProfileIn( $fname );
2568 $variableIDs = MagicWord
::getVariableIDs();
2570 $this->mVariables
= array();
2571 foreach ( $variableIDs as $id ) {
2572 $mw =& MagicWord
::get( $id );
2573 $mw->addToArray( $this->mVariables
, $id );
2575 wfProfileOut( $fname );
2579 * parse any parentheses in format ((title|part|part))
2580 * and call callbacks to get a replacement text for any found piece
2582 * @param string $text The text to parse
2583 * @param array $callbacks rules in form:
2584 * '{' => array( # opening parentheses
2585 * 'end' => '}', # closing parentheses
2586 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2587 * 3 => callback # replacement callback to call if {{{..}}} is found
2590 * 'min' => 2, # Minimum parenthesis count in cb
2591 * 'max' => 3, # Maximum parenthesis count in cb
2594 function replace_callback ($text, $callbacks) {
2595 wfProfileIn( __METHOD__
);
2596 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2597 $lastOpeningBrace = -1; # last not closed parentheses
2599 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2602 while ( $i < strlen( $text ) ) {
2603 # Find next opening brace, closing brace or pipe
2604 if ( $lastOpeningBrace == -1 ) {
2605 $currentClosing = '';
2606 $search = $validOpeningBraces;
2608 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2609 $search = $validOpeningBraces . '|' . $currentClosing;
2612 $i +
= strcspn( $text, $search, $i );
2613 if ( $i < strlen( $text ) ) {
2614 if ( $text[$i] == '|' ) {
2616 } elseif ( $text[$i] == $currentClosing ) {
2618 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2620 $rule = $callbacks[$text[$i]];
2622 # Some versions of PHP have a strcspn which stops on null characters
2623 # Ignore and continue
2632 if ( $found == 'open' ) {
2633 # found opening brace, let's add it to parentheses stack
2634 $piece = array('brace' => $text[$i],
2635 'braceEnd' => $rule['end'],
2639 # count opening brace characters
2640 $piece['count'] = strspn( $text, $piece['brace'], $i );
2641 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2642 $i +
= $piece['count'];
2644 # we need to add to stack only if opening brace count is enough for one of the rules
2645 if ( $piece['count'] >= $rule['min'] ) {
2646 $lastOpeningBrace ++
;
2647 $openingBraceStack[$lastOpeningBrace] = $piece;
2649 } elseif ( $found == 'close' ) {
2650 # lets check if it is enough characters for closing brace
2651 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2652 $count = strspn( $text, $text[$i], $i, $maxCount );
2654 # check for maximum matching characters (if there are 5 closing
2655 # characters, we will probably need only 3 - depending on the rules)
2657 $matchingCallback = null;
2658 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2659 if ( $count > $cbType['max'] ) {
2660 # The specified maximum exists in the callback array, unless the caller
2662 $matchingCount = $cbType['max'];
2664 # Count is less than the maximum
2665 # Skip any gaps in the callback array to find the true largest match
2666 # Need to use array_key_exists not isset because the callback can be null
2667 $matchingCount = $count;
2668 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2673 if ($matchingCount <= 0) {
2677 $matchingCallback = $cbType['cb'][$matchingCount];
2679 # let's set a title or last part (if '|' was found)
2680 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2681 $openingBraceStack[$lastOpeningBrace]['title'] =
2682 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2683 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2685 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2686 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2687 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2690 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2691 $pieceEnd = $i +
$matchingCount;
2693 if( is_callable( $matchingCallback ) ) {
2695 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2696 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2697 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2698 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2700 # finally we can call a user callback and replace piece of text
2701 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2702 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2703 $i = $pieceStart +
strlen($replaceWith);
2705 # null value for callback means that parentheses should be parsed, but not replaced
2706 $i +
= $matchingCount;
2709 # reset last opening parentheses, but keep it in case there are unused characters
2710 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2711 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2712 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2715 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2716 $openingBraceStack[$lastOpeningBrace--] = null;
2718 if ($matchingCount < $piece['count']) {
2719 $piece['count'] -= $matchingCount;
2720 $piece['startAt'] -= $matchingCount;
2721 $piece['partStart'] = $piece['startAt'];
2722 # do we still qualify for any callback with remaining count?
2723 $currentCbList = $callbacks[$piece['brace']]['cb'];
2724 while ( $piece['count'] ) {
2725 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2726 $lastOpeningBrace++
;
2727 $openingBraceStack[$lastOpeningBrace] = $piece;
2733 } elseif ( $found == 'pipe' ) {
2734 # lets set a title if it is a first separator, or next part otherwise
2735 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2736 $openingBraceStack[$lastOpeningBrace]['title'] =
2737 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2738 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2739 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2741 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2742 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2743 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2745 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2749 wfProfileOut( __METHOD__
);
2754 * Replace magic variables, templates, and template arguments
2755 * with the appropriate text. Templates are substituted recursively,
2756 * taking care to avoid infinite loops.
2758 * Note that the substitution depends on value of $mOutputType:
2759 * OT_WIKI: only {{subst:}} templates
2760 * OT_MSG: only magic variables
2761 * OT_HTML: all templates and magic variables
2763 * @param string $tex The text to transform
2764 * @param array $args Key-value pairs representing template parameters to substitute
2765 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2768 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2769 # Prevent too big inclusions
2770 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2774 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2775 wfProfileIn( $fname );
2777 # This function is called recursively. To keep track of arguments we need a stack:
2778 array_push( $this->mArgStack
, $args );
2780 $braceCallbacks = array();
2782 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2784 if ( $this->mOutputType
!= OT_MSG
) {
2785 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2787 if ( $braceCallbacks ) {
2791 'cb' => $braceCallbacks,
2792 'min' => $argsOnly ?
3 : 2,
2793 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2797 'cb' => array(2=>null),
2802 $text = $this->replace_callback ($text, $callbacks);
2804 array_pop( $this->mArgStack
);
2806 wfProfileOut( $fname );
2811 * Replace magic variables
2814 function variableSubstitution( $matches ) {
2816 $fname = 'Parser::variableSubstitution';
2817 $varname = $wgContLang->lc($matches[1]);
2818 wfProfileIn( $fname );
2820 if ( $this->mOutputType
== OT_WIKI
) {
2821 # Do only magic variables prefixed by SUBST
2822 $mwSubst =& MagicWord
::get( 'subst' );
2823 if (!$mwSubst->matchStartAndRemove( $varname ))
2825 # Note that if we don't substitute the variable below,
2826 # we don't remove the {{subst:}} magic word, in case
2827 # it is a template rather than a magic variable.
2829 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2830 $id = $this->mVariables
[$varname];
2831 # Now check if we did really match, case sensitive or not
2832 $mw =& MagicWord
::get( $id );
2833 if ($mw->match($matches[1])) {
2834 $text = $this->getVariableValue( $id );
2835 if (MagicWord
::getCacheTTL($id)>-1)
2836 $this->mOutput
->mContainsOldMagic
= true;
2838 $text = $matches[0];
2841 $text = $matches[0];
2843 wfProfileOut( $fname );
2848 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2849 static function createAssocArgs( $args ) {
2850 $assocArgs = array();
2852 foreach( $args as $arg ) {
2853 $eqpos = strpos( $arg, '=' );
2854 if ( $eqpos === false ) {
2855 $assocArgs[$index++
] = $arg;
2857 $name = trim( substr( $arg, 0, $eqpos ) );
2858 $value = trim( substr( $arg, $eqpos+
1 ) );
2859 if ( $value === false ) {
2862 if ( $name !== false ) {
2863 $assocArgs[$name] = $value;
2872 * Return the text of a template, after recursively
2873 * replacing any variables or templates within the template.
2875 * @param array $piece The parts of the template
2876 * $piece['text']: matched text
2877 * $piece['title']: the title, i.e. the part before the |
2878 * $piece['parts']: the parameter array
2879 * @return string the text of the template
2882 function braceSubstitution( $piece ) {
2883 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2884 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2885 wfProfileIn( $fname );
2886 wfProfileIn( __METHOD__
.'-setup' );
2889 $found = false; # $text has been filled
2890 $nowiki = false; # wiki markup in $text should be escaped
2891 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2892 $noargs = false; # Don't replace triple-brace arguments in $text
2893 $replaceHeadings = false; # Make the edit section links go to the template not the article
2894 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2895 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2896 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2898 # Title object, where $text came from
2904 # $part1 is the bit before the first |, and must contain only title characters
2905 # $args is a list of arguments, starting from index 0, not including $part1
2907 $titleText = $part1 = $piece['title'];
2908 # If the third subpattern matched anything, it will start with |
2910 if (null == $piece['parts']) {
2911 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2912 if ($replaceWith != $piece['text']) {
2913 $text = $replaceWith;
2920 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2921 wfProfileOut( __METHOD__
.'-setup' );
2924 wfProfileIn( __METHOD__
.'-modifiers' );
2926 $mwSubst =& MagicWord
::get( 'subst' );
2927 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2928 # One of two possibilities is true:
2929 # 1) Found SUBST but not in the PST phase
2930 # 2) Didn't find SUBST and in the PST phase
2931 # In either case, return without further processing
2932 $text = $piece['text'];
2939 # MSG, MSGNW and RAW
2942 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2943 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2946 # Remove obsolete MSG:
2947 $mwMsg =& MagicWord
::get( 'msg' );
2948 $mwMsg->matchStartAndRemove( $part1 );
2952 $mwRaw =& MagicWord
::get( 'raw' );
2953 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2954 $forceRawInterwiki = true;
2957 wfProfileOut( __METHOD__
.'-modifiers' );
2959 //save path level before recursing into functions & templates.
2960 $lastPathLevel = $this->mTemplatePath
;
2964 wfProfileIn( __METHOD__
. '-pfunc' );
2966 $colonPos = strpos( $part1, ':' );
2967 if ( $colonPos !== false ) {
2968 # Case sensitive functions
2969 $function = substr( $part1, 0, $colonPos );
2970 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2971 $function = $this->mFunctionSynonyms
[1][$function];
2973 # Case insensitive functions
2974 $function = strtolower( $function );
2975 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2976 $function = $this->mFunctionSynonyms
[0][$function];
2982 $funcArgs = array_map( 'trim', $args );
2983 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2984 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2987 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2991 if ( is_array( $result ) ) {
2992 if ( isset( $result[0] ) ) {
2993 $text = $linestart . $result[0];
2994 unset( $result[0] );
2997 // Extract flags into the local scope
2998 // This allows callers to set flags such as nowiki, noparse, found, etc.
3001 $text = $linestart . $result;
3005 wfProfileOut( __METHOD__
. '-pfunc' );
3008 # Template table test
3010 # Did we encounter this template already? If yes, it is in the cache
3011 # and we need to check for loops.
3012 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3015 # Infinite loop test
3016 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3020 $text = $linestart .
3021 "[[$part1]]<!-- WARNING: template loop detected -->";
3022 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3024 # set $text to cached message.
3025 $text = $linestart . $this->mTemplates
[$piece['title']];
3026 #treat title for cached page the same as others
3029 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3030 if ($subpage !== '') {
3031 $ns = $this->mTitle
->getNamespace();
3033 $title = Title
::newFromText( $part1, $ns );
3034 //used by include size checking
3035 $titleText = $title->getPrefixedText();
3036 //used by edit section links
3037 $replaceHeadings = true;
3042 # Load from database
3044 wfProfileIn( __METHOD__
. '-loadtpl' );
3046 # declaring $subpage directly in the function call
3047 # does not work correctly with references and breaks
3048 # {{/subpage}}-style inclusions
3050 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3051 if ($subpage !== '') {
3052 $ns = $this->mTitle
->getNamespace();
3054 $title = Title
::newFromText( $part1, $ns );
3057 if ( !is_null( $title ) ) {
3058 $titleText = $title->getPrefixedText();
3059 # Check for language variants if the template is not found
3060 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3061 $wgContLang->findVariantLink($part1, $title);
3064 if ( !$title->isExternal() ) {
3065 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3066 $text = SpecialPage
::capturePath( $title );
3067 if ( is_string( $text ) ) {
3072 $this->disableCache();
3074 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3075 $found = false; //access denied
3076 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3078 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3079 if ( $articleContent !== false ) {
3081 $text = $articleContent;
3082 $replaceHeadings = true;
3086 # If the title is valid but undisplayable, make a link to it
3087 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3088 $text = "[[:$titleText]]";
3091 } elseif ( $title->isTrans() ) {
3092 // Interwiki transclusion
3093 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3094 $text = $this->interwikiTransclude( $title, 'render' );
3098 $text = $this->interwikiTransclude( $title, 'raw' );
3099 $replaceHeadings = true;
3104 # Template cache array insertion
3105 # Use the original $piece['title'] not the mangled $part1, so that
3106 # modifiers such as RAW: produce separate cache entries
3109 // A special page; don't store it in the template cache.
3111 $this->mTemplates
[$piece['title']] = $text;
3113 $text = $linestart . $text;
3116 wfProfileOut( __METHOD__
. '-loadtpl' );
3119 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3120 # Error, oversize inclusion
3121 $text = $linestart .
3122 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3127 # Recursive parsing, escaping and link table handling
3128 # Only for HTML output
3129 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3130 $text = wfEscapeWikiText( $text );
3131 } elseif ( !$this->ot
['msg'] && $found ) {
3133 $assocArgs = array();
3135 # Clean up argument array
3136 $assocArgs = self
::createAssocArgs($args);
3137 # Add a new element to the templace recursion path
3138 $this->mTemplatePath
[$part1] = 1;
3142 # If there are any <onlyinclude> tags, only include them
3143 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3144 $replacer = new OnlyIncludeReplacer
;
3145 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3146 array( &$replacer, 'replace' ), $text );
3147 $text = $replacer->output
;
3149 # Remove <noinclude> sections and <includeonly> tags
3150 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3151 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3153 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3154 # Strip <nowiki>, <pre>, etc.
3155 $text = $this->strip( $text, $this->mStripState
);
3156 if ( $this->ot
['html'] ) {
3157 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3158 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3159 $text = Sanitizer
::removeHTMLcomments( $text );
3162 $text = $this->replaceVariables( $text, $assocArgs );
3164 # If the template begins with a table or block-level
3165 # element, it should be treated as beginning a new line.
3166 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3167 $text = "\n" . $text;
3169 } elseif ( !$noargs ) {
3170 # $noparse and !$noargs
3171 # Just replace the arguments, not any double-brace items
3172 # This is used for rendered interwiki transclusion
3173 $text = $this->replaceVariables( $text, $assocArgs, true );
3176 # Prune lower levels off the recursion check path
3177 $this->mTemplatePath
= $lastPathLevel;
3179 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3180 # Error, oversize inclusion
3181 $text = $linestart .
3182 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3188 wfProfileOut( $fname );
3189 return $piece['text'];
3191 wfProfileIn( __METHOD__
. '-placeholders' );
3193 # Replace raw HTML by a placeholder
3194 # Add a blank line preceding, to prevent it from mucking up
3195 # immediately preceding headings
3196 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3198 # replace ==section headers==
3199 # XXX this needs to go away once we have a better parser.
3200 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3201 if( !is_null( $title ) )
3202 $encodedname = base64_encode($title->getPrefixedDBkey());
3204 $encodedname = base64_encode("");
3205 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3206 PREG_SPLIT_DELIM_CAPTURE
);
3208 $nsec = $headingOffset;
3210 for( $i = 0; $i < count($m); $i +
= 2 ) {
3212 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3214 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3219 preg_match('/^(={1,6})(.*?)(={1,6}\s*?)$/m', $hl, $m2);
3220 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3221 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3227 wfProfileOut( __METHOD__
. '-placeholders' );
3230 # Prune lower levels off the recursion check path
3231 $this->mTemplatePath
= $lastPathLevel;
3234 wfProfileOut( $fname );
3235 return $piece['text'];
3237 wfProfileOut( $fname );
3243 * Fetch the unparsed text of a template and register a reference to it.
3245 function fetchTemplateAndTitle( $title ) {
3246 $templateCb = $this->mOptions
->getTemplateCallback();
3247 $stuff = call_user_func( $templateCb, $title );
3248 $text = $stuff['text'];
3249 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3250 if ( isset( $stuff['deps'] ) ) {
3251 foreach ( $stuff['deps'] as $dep ) {
3252 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3255 return array($text,$finalTitle);
3258 function fetchTemplate( $title ) {
3259 $rv = $this->fetchTemplateAndtitle($title);
3264 * Static function to get a template
3265 * Can be overridden via ParserOptions::setTemplateCallback().
3267 * Returns an associative array:
3268 * text The unparsed template text
3269 * finalTitle (Optional) The title after following redirects
3270 * deps (Optional) An array of associative array dependencies:
3271 * title: The dependency title, to be registered in templatelinks
3272 * page_id: The page_id of the title
3273 * rev_id: The revision ID loaded
3275 static function statelessFetchTemplate( $title ) {
3276 $text = $skip = false;
3277 $finalTitle = $title;
3280 // Loop to fetch the article, with up to 1 redirect
3281 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3282 # Give extensions a chance to select the revision instead
3283 $id = false; // Assume current
3284 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3290 'page_id' => $title->getArticleID(),
3294 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3295 $rev_id = $rev ?
$rev->getId() : 0;
3299 'page_id' => $title->getArticleID(),
3300 'rev_id' => $rev_id );
3303 $text = $rev->getText();
3304 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3306 $message = $wgLang->lcfirst( $title->getText() );
3307 $text = wfMsgForContentNoTrans( $message );
3308 if( wfEmptyMsg( $message, $text ) ) {
3315 if ( $text === false ) {
3319 $finalTitle = $title;
3320 $title = Title
::newFromRedirect( $text );
3324 'finalTitle' => $finalTitle,
3329 * Transclude an interwiki link.
3331 function interwikiTransclude( $title, $action ) {
3332 global $wgEnableScaryTranscluding;
3334 if (!$wgEnableScaryTranscluding)
3335 return wfMsg('scarytranscludedisabled');
3337 $url = $title->getFullUrl( "action=$action" );
3339 if (strlen($url) > 255)
3340 return wfMsg('scarytranscludetoolong');
3341 return $this->fetchScaryTemplateMaybeFromCache($url);
3344 function fetchScaryTemplateMaybeFromCache($url) {
3345 global $wgTranscludeCacheExpiry;
3346 $dbr = wfGetDB(DB_SLAVE
);
3347 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3348 array('tc_url' => $url));
3350 $time = $obj->tc_time
;
3351 $text = $obj->tc_contents
;
3352 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3357 $text = Http
::get($url);
3359 return wfMsg('scarytranscludefailed', $url);
3361 $dbw = wfGetDB(DB_MASTER
);
3362 $dbw->replace('transcache', array('tc_url'), array(
3364 'tc_time' => time(),
3365 'tc_contents' => $text));
3371 * Triple brace replacement -- used for template arguments
3374 function argSubstitution( $matches ) {
3375 $arg = trim( $matches['title'] );
3376 $text = $matches['text'];
3377 $inputArgs = end( $this->mArgStack
);
3379 if ( array_key_exists( $arg, $inputArgs ) ) {
3380 $text = $inputArgs[$arg];
3381 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3382 null != $matches['parts'] && count($matches['parts']) > 0) {
3383 $text = $matches['parts'][0];
3385 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3386 $text = $matches['text'] .
3387 '<!-- WARNING: argument omitted, expansion size too large -->';
3394 * Increment an include size counter
3396 * @param string $type The type of expansion
3397 * @param integer $size The size of the text
3398 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3400 function incrementIncludeSize( $type, $size ) {
3401 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3404 $this->mIncludeSizes
[$type] +
= $size;
3410 * Detect __NOGALLERY__ magic word and set a placeholder
3412 function stripNoGallery( &$text ) {
3413 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3415 $mw = MagicWord
::get( 'nogallery' );
3416 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3420 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3421 * placeholder that will then be replaced by the real TOC in
3422 * ->formatHeadings, this works because at this points real
3423 * comments will have already been discarded by the sanitizer.
3425 * Any additional __TOC__ magic words left over will be discarded
3426 * as there can only be one TOC on the page.
3428 function stripToc( $text ) {
3429 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3431 $mw = MagicWord
::get( 'notoc' );
3432 if( $mw->matchAndRemove( $text ) ) {
3433 $this->mShowToc
= false;
3436 $mw = MagicWord
::get( 'toc' );
3437 if( $mw->match( $text ) ) {
3438 $this->mShowToc
= true;
3439 $this->mForceTocPosition
= true;
3441 // Set a placeholder. At the end we'll fill it in with the TOC.
3442 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3444 // Only keep the first one.
3445 $text = $mw->replace( '', $text );
3451 * This function accomplishes several tasks:
3452 * 1) Auto-number headings if that option is enabled
3453 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3454 * 3) Add a Table of contents on the top for users who have enabled the option
3455 * 4) Auto-anchor headings
3457 * It loops through all headlines, collects the necessary data, then splits up the
3458 * string and re-inserts the newly formatted headlines.
3460 * @param string $text
3461 * @param boolean $isMain
3464 function formatHeadings( $text, $isMain=true ) {
3465 global $wgMaxTocLevel, $wgContLang;
3467 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3468 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3471 $showEditLink = $this->mOptions
->getEditSection();
3474 # Inhibit editsection links if requested in the page
3475 $esw =& MagicWord
::get( 'noeditsection' );
3476 if( $esw->matchAndRemove( $text ) ) {
3480 # Get all headlines for numbering them and adding funky stuff like [edit]
3481 # links - this is for later, but we need the number of headlines right now
3483 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3485 # if there are fewer than 4 headlines in the article, do not show TOC
3486 # unless it's been explicitly enabled.
3487 $enoughToc = $this->mShowToc
&&
3488 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3490 # Allow user to stipulate that a page should have a "new section"
3491 # link added via __NEWSECTIONLINK__
3492 $mw =& MagicWord
::get( 'newsectionlink' );
3493 if( $mw->matchAndRemove( $text ) )
3494 $this->mOutput
->setNewSection( true );
3496 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3497 # override above conditions and always show TOC above first header
3498 $mw =& MagicWord
::get( 'forcetoc' );
3499 if ($mw->matchAndRemove( $text ) ) {
3500 $this->mShowToc
= true;
3504 # We need this to perform operations on the HTML
3505 $sk = $this->mOptions
->getSkin();
3509 $sectionCount = 0; # headlineCount excluding template sections
3512 # Ugh .. the TOC should have neat indentation levels which can be
3513 # passed to the skin functions. These are determined here
3517 $sublevelCount = array();
3518 $levelCount = array();
3526 foreach( $matches[3] as $headline ) {
3528 $templatetitle = '';
3529 $templatesection = 0;
3532 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3534 $templatetitle = base64_decode($mat[1]);
3535 $templatesection = 1 +
(int)base64_decode($mat[2]);
3536 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3540 $prevlevel = $level;
3541 $prevtoclevel = $toclevel;
3543 $level = $matches[1][$headlineCount];
3545 if( $doNumberHeadings ||
$enoughToc ) {
3547 if ( $level > $prevlevel ) {
3548 # Increase TOC level
3550 $sublevelCount[$toclevel] = 0;
3551 if( $toclevel<$wgMaxTocLevel ) {
3552 $prevtoclevel = $toclevel;
3553 $toc .= $sk->tocIndent();
3557 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3558 # Decrease TOC level, find level to jump to
3560 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3561 # Can only go down to level 1
3564 for ($i = $toclevel; $i > 0; $i--) {
3565 if ( $levelCount[$i] == $level ) {
3566 # Found last matching level
3570 elseif ( $levelCount[$i] < $level ) {
3571 # Found first matching level below current level
3577 if( $toclevel<$wgMaxTocLevel ) {
3578 if($prevtoclevel < $wgMaxTocLevel) {
3579 # Unindent only if the previous toc level was shown :p
3580 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3582 $toc .= $sk->tocLineEnd();
3587 # No change in level, end TOC line
3588 if( $toclevel<$wgMaxTocLevel ) {
3589 $toc .= $sk->tocLineEnd();
3593 $levelCount[$toclevel] = $level;
3595 # count number of headlines for each level
3596 @$sublevelCount[$toclevel]++
;
3598 for( $i = 1; $i <= $toclevel; $i++
) {
3599 if( !empty( $sublevelCount[$i] ) ) {
3603 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3609 # The canonized header is a version of the header text safe to use for links
3610 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3611 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3613 # Remove link placeholders by the link text.
3614 # <!--LINK number-->
3616 # link text with suffix
3617 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3618 "\$this->mLinkHolders['texts'][\$1]",
3619 $canonized_headline );
3620 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3621 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3622 $canonized_headline );
3624 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3625 $tocline = preg_replace(
3626 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3630 $tocline = trim( $tocline );
3632 # For the anchor, strip out HTML-y stuff period
3633 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3634 $canonized_headline = trim( $canonized_headline );
3636 # Save headline for section edit hint before it's escaped
3637 $headline_hint = $canonized_headline;
3638 $canonized_headline = Sanitizer
::escapeId( $canonized_headline );
3639 $refers[$headlineCount] = $canonized_headline;
3641 # count how many in assoc. array so we can track dupes in anchors
3642 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3643 $refcount[$headlineCount]=$refers[$canonized_headline];
3645 # Don't number the heading if it is the only one (looks silly)
3646 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3647 # the two are different if the line contains a link
3648 $headline=$numbering . ' ' . $headline;
3651 # Create the anchor for linking from the TOC to the section
3652 $anchor = $canonized_headline;
3653 if($refcount[$headlineCount] > 1 ) {
3654 $anchor .= '_' . $refcount[$headlineCount];
3656 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3657 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3658 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3660 # give headline the correct <h#> tag
3661 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3663 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3665 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3669 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3676 $this->mOutput
->setSections( $tocraw );
3678 # Never ever show TOC if no headers
3679 if( $numVisible < 1 ) {
3684 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3685 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3687 $toc = $sk->tocList( $toc );
3690 # split up and insert constructed headlines
3692 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3695 foreach( $blocks as $block ) {
3696 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3697 # This is the [edit] link that appears for the top block of text when
3698 # section editing is enabled
3700 # Disabled because it broke block formatting
3701 # For example, a bullet point in the top line
3702 # $full .= $sk->editSectionLink(0);
3705 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3706 # Top anchor now in skin
3710 if( !empty( $head[$i] ) ) {
3715 if( $this->mForceTocPosition
) {
3716 return str_replace( '<!--MWTOC-->', $toc, $full );
3723 * Transform wiki markup when saving a page by doing \r\n -> \n
3724 * conversion, substitting signatures, {{subst:}} templates, etc.
3726 * @param string $text the text to transform
3727 * @param Title &$title the Title object for the current article
3728 * @param User &$user the User object describing the current user
3729 * @param ParserOptions $options parsing options
3730 * @param bool $clearState whether to clear the parser state first
3731 * @return string the altered wiki markup
3734 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3735 $this->mOptions
= $options;
3736 $this->mTitle
=& $title;
3737 $this->setOutputType( OT_WIKI
);
3739 if ( $clearState ) {
3740 $this->clearState();
3743 $stripState = new StripState
;
3747 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3748 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3749 $text = $this->pstPass2( $text, $stripState, $user );
3750 $text = $stripState->unstripBoth( $text );
3755 * Pre-save transform helper function
3758 function pstPass2( $text, &$stripState, $user ) {
3759 global $wgContLang, $wgLocaltimezone;
3761 /* Note: This is the timestamp saved as hardcoded wikitext to
3762 * the database, we use $wgContLang here in order to give
3763 * everyone the same signature and use the default one rather
3764 * than the one selected in each user's preferences.
3766 if ( isset( $wgLocaltimezone ) ) {
3767 $oldtz = getenv( 'TZ' );
3768 putenv( 'TZ='.$wgLocaltimezone );
3770 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3771 ' (' . date( 'T' ) . ')';
3772 if ( isset( $wgLocaltimezone ) ) {
3773 putenv( 'TZ='.$oldtz );
3776 # Variable replacement
3777 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3778 $text = $this->replaceVariables( $text );
3780 # Strip out <nowiki> etc. added via replaceVariables
3781 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3784 $sigText = $this->getUserSig( $user );
3785 $text = strtr( $text, array(
3787 '~~~~' => "$sigText $d",
3791 # Context links: [[|name]] and [[name (context)|]]
3793 global $wgLegalTitleChars;
3794 $tc = "[$wgLegalTitleChars]";
3795 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3797 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3798 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3799 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3801 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3802 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3803 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3805 $t = $this->mTitle
->getText();
3807 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3808 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3809 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3810 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3812 # if there's no context, don't bother duplicating the title
3813 $text = preg_replace( $p2, '[[\\1]]', $text );
3816 # Trim trailing whitespace
3817 $text = rtrim( $text );
3823 * Fetch the user's signature text, if any, and normalize to
3824 * validated, ready-to-insert wikitext.
3830 function getUserSig( &$user ) {
3831 global $wgMaxSigChars;
3833 $username = $user->getName();
3834 $nickname = $user->getOption( 'nickname' );
3835 $nickname = $nickname === '' ?
$username : $nickname;
3837 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3838 $nickname = $username;
3839 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3840 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3841 # Sig. might contain markup; validate this
3842 if( $this->validateSig( $nickname ) !== false ) {
3843 # Validated; clean up (if needed) and return it
3844 return $this->cleanSig( $nickname, true );
3846 # Failed to validate; fall back to the default
3847 $nickname = $username;
3848 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3852 // Make sure nickname doesnt get a sig in a sig
3853 $nickname = $this->cleanSigInSig( $nickname );
3855 # If we're still here, make it a link to the user page
3856 $userText = wfEscapeWikiText( $username );
3857 $nickText = wfEscapeWikiText( $nickname );
3858 if ( $user->isAnon() ) {
3859 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3861 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3866 * Check that the user's signature contains no bad XML
3868 * @param string $text
3869 * @return mixed An expanded string, or false if invalid.
3871 function validateSig( $text ) {
3872 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3876 * Clean up signature text
3878 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3879 * 2) Substitute all transclusions
3881 * @param string $text
3882 * @param $parsing Whether we're cleaning (preferences save) or parsing
3883 * @return string Signature text
3885 function cleanSig( $text, $parsing = false ) {
3887 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3889 $substWord = MagicWord
::get( 'subst' );
3890 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3891 $substText = '{{' . $substWord->getSynonym( 0 );
3893 $text = preg_replace( $substRegex, $substText, $text );
3894 $text = $this->cleanSigInSig( $text );
3895 $text = $this->replaceVariables( $text );
3897 $this->clearState();
3902 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3903 * @param string $text
3904 * @return string Signature text with /~{3,5}/ removed
3906 function cleanSigInSig( $text ) {
3907 $text = preg_replace( '/~{3,5}/', '', $text );
3912 * Set up some variables which are usually set up in parse()
3913 * so that an external function can call some class members with confidence
3916 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3917 $this->mTitle
=& $title;
3918 $this->mOptions
= $options;
3919 $this->setOutputType( $outputType );
3920 if ( $clearState ) {
3921 $this->clearState();
3926 * Transform a MediaWiki message by replacing magic variables.
3928 * @param string $text the text to transform
3929 * @param ParserOptions $options options
3930 * @return string the text with variables substituted
3933 function transformMsg( $text, $options ) {
3935 static $executing = false;
3937 $fname = "Parser::transformMsg";
3939 # Guard against infinite recursion
3945 wfProfileIn($fname);
3947 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3948 $this->mTitle
= $wgTitle;
3950 $this->mTitle
= Title
::newFromText('msg');
3952 $this->mOptions
= $options;
3953 $this->setOutputType( OT_MSG
);
3954 $this->clearState();
3955 $text = $this->replaceVariables( $text );
3958 wfProfileOut($fname);
3963 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3964 * The callback should have the following form:
3965 * function myParserHook( $text, $params, &$parser ) { ... }
3967 * Transform and return $text. Use $parser for any required context, e.g. use
3968 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3972 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3973 * @param mixed $callback The callback function (and object) to use for the tag
3975 * @return The old value of the mTagHooks array associated with the hook
3977 function setHook( $tag, $callback ) {
3978 $tag = strtolower( $tag );
3979 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3980 $this->mTagHooks
[$tag] = $callback;
3985 function setTransparentTagHook( $tag, $callback ) {
3986 $tag = strtolower( $tag );
3987 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3988 $this->mTransparentTagHooks
[$tag] = $callback;
3994 * Create a function, e.g. {{sum:1|2|3}}
3995 * The callback function should have the form:
3996 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3998 * The callback may either return the text result of the function, or an array with the text
3999 * in element 0, and a number of flags in the other elements. The names of the flags are
4000 * specified in the keys. Valid flags are:
4001 * found The text returned is valid, stop processing the template. This
4003 * nowiki Wiki markup in the return value should be escaped
4004 * noparse Unsafe HTML tags should not be stripped, etc.
4005 * noargs Don't replace triple-brace arguments in the return value
4006 * isHTML The returned text is HTML, armour it against wikitext transformation
4010 * @param string $id The magic word ID
4011 * @param mixed $callback The callback function (and object) to use
4012 * @param integer $flags a combination of the following flags:
4013 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4015 * @return The old callback function for this name, if any
4017 function setFunctionHook( $id, $callback, $flags = 0 ) {
4018 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4019 $this->mFunctionHooks
[$id] = $callback;
4021 # Add to function cache
4022 $mw = MagicWord
::get( $id );
4024 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4026 $synonyms = $mw->getSynonyms();
4027 $sensitive = intval( $mw->isCaseSensitive() );
4029 foreach ( $synonyms as $syn ) {
4031 if ( !$sensitive ) {
4032 $syn = strtolower( $syn );
4035 if ( !( $flags & SFH_NO_HASH
) ) {
4038 # Remove trailing colon
4039 if ( substr( $syn, -1, 1 ) == ':' ) {
4040 $syn = substr( $syn, 0, -1 );
4042 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4048 * Get all registered function hook identifiers
4052 function getFunctionHooks() {
4053 return array_keys( $this->mFunctionHooks
);
4057 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4058 * Placeholders created in Skin::makeLinkObj()
4059 * Returns an array of links found, indexed by PDBK:
4063 * $options is a bit field, RLH_FOR_UPDATE to select for update
4065 function replaceLinkHolders( &$text, $options = 0 ) {
4069 $fname = 'Parser::replaceLinkHolders';
4070 wfProfileIn( $fname );
4074 $sk = $this->mOptions
->getSkin();
4075 $linkCache =& LinkCache
::singleton();
4077 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4078 wfProfileIn( $fname.'-check' );
4079 $dbr = wfGetDB( DB_SLAVE
);
4080 $page = $dbr->tableName( 'page' );
4081 $threshold = $wgUser->getOption('stubthreshold');
4084 asort( $this->mLinkHolders
['namespaces'] );
4089 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4091 $title = $this->mLinkHolders
['titles'][$key];
4093 # Skip invalid entries.
4094 # Result will be ugly, but prevents crash.
4095 if ( is_null( $title ) ) {
4098 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4100 # Check if it's a static known link, e.g. interwiki
4101 if ( $title->isAlwaysKnown() ) {
4102 $colours[$pdbk] = 1;
4103 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4104 $colours[$pdbk] = 1;
4105 $this->mOutput
->addLink( $title, $id );
4106 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4107 $colours[$pdbk] = 0;
4108 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4109 $colours[$pdbk] = 0;
4111 # Not in the link cache, add it to the query
4112 if ( !isset( $current ) ) {
4114 $query = "SELECT page_id, page_namespace, page_title";
4115 if ( $threshold > 0 ) {
4116 $query .= ', page_len, page_is_redirect';
4118 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4119 } elseif ( $current != $ns ) {
4121 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4126 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4131 if ( $options & RLH_FOR_UPDATE
) {
4132 $query .= ' FOR UPDATE';
4135 $res = $dbr->query( $query, $fname );
4137 # Fetch data and form into an associative array
4138 # non-existent = broken
4141 while ( $s = $dbr->fetchObject($res) ) {
4142 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4143 $pdbk = $title->getPrefixedDBkey();
4144 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4145 $this->mOutput
->addLink( $title, $s->page_id
);
4147 $colours[$pdbk] = ( $threshold == 0 ||
(
4148 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4149 $s->page_is_redirect ||
4150 !Namespace::isContent( $s->page_namespace
) )
4154 wfProfileOut( $fname.'-check' );
4156 # Do a second query for different language variants of links and categories
4157 if($wgContLang->hasVariants()){
4158 $linkBatch = new LinkBatch();
4159 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4160 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4161 $varCategories = array(); // category replacements oldDBkey => newDBkey
4163 $categories = $this->mOutput
->getCategoryLinks();
4165 // Add variants of links to link batch
4166 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4167 $title = $this->mLinkHolders
['titles'][$key];
4168 if ( is_null( $title ) )
4171 $pdbk = $title->getPrefixedDBkey();
4172 $titleText = $title->getText();
4174 // generate all variants of the link title text
4175 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4177 // if link was not found (in first query), add all variants to query
4178 if ( !isset($colours[$pdbk]) ){
4179 foreach($allTextVariants as $textVariant){
4180 if($textVariant != $titleText){
4181 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4182 if(is_null($variantTitle)) continue;
4183 $linkBatch->addObj( $variantTitle );
4184 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4190 // process categories, check if a category exists in some variant
4191 foreach( $categories as $category ){
4192 $variants = $wgContLang->convertLinkToAllVariants($category);
4193 foreach($variants as $variant){
4194 if($variant != $category){
4195 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4196 if(is_null($variantTitle)) continue;
4197 $linkBatch->addObj( $variantTitle );
4198 $categoryMap[$variant] = $category;
4204 if(!$linkBatch->isEmpty()){
4206 $titleClause = $linkBatch->constructSet('page', $dbr);
4208 $variantQuery = "SELECT page_id, page_namespace, page_title";
4209 if ( $threshold > 0 ) {
4210 $variantQuery .= ', page_len, page_is_redirect';
4213 $variantQuery .= " FROM $page WHERE $titleClause";
4214 if ( $options & RLH_FOR_UPDATE
) {
4215 $variantQuery .= ' FOR UPDATE';
4218 $varRes = $dbr->query( $variantQuery, $fname );
4220 // for each found variants, figure out link holders and replace
4221 while ( $s = $dbr->fetchObject($varRes) ) {
4223 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4224 $varPdbk = $variantTitle->getPrefixedDBkey();
4225 $vardbk = $variantTitle->getDBkey();
4227 $holderKeys = array();
4228 if(isset($variantMap[$varPdbk])){
4229 $holderKeys = $variantMap[$varPdbk];
4230 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4231 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4234 // loop over link holders
4235 foreach($holderKeys as $key){
4236 $title = $this->mLinkHolders
['titles'][$key];
4237 if ( is_null( $title ) ) continue;
4239 $pdbk = $title->getPrefixedDBkey();
4241 if(!isset($colours[$pdbk])){
4242 // found link in some of the variants, replace the link holder data
4243 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4244 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4246 // set pdbk and colour
4247 $pdbks[$key] = $varPdbk;
4248 if ( $threshold > 0 ) {
4249 $size = $s->page_len
;
4250 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4251 $colours[$varPdbk] = 1;
4253 $colours[$varPdbk] = 2;
4257 $colours[$varPdbk] = 1;
4262 // check if the object is a variant of a category
4263 if(isset($categoryMap[$vardbk])){
4264 $oldkey = $categoryMap[$vardbk];
4265 if($oldkey != $vardbk)
4266 $varCategories[$oldkey]=$vardbk;
4270 // rebuild the categories in original order (if there are replacements)
4271 if(count($varCategories)>0){
4273 $originalCats = $this->mOutput
->getCategories();
4274 foreach($originalCats as $cat => $sortkey){
4275 // make the replacement
4276 if( array_key_exists($cat,$varCategories) )
4277 $newCats[$varCategories[$cat]] = $sortkey;
4278 else $newCats[$cat] = $sortkey;
4280 $this->mOutput
->setCategoryLinks($newCats);
4285 # Construct search and replace arrays
4286 wfProfileIn( $fname.'-construct' );
4287 $replacePairs = array();
4288 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4289 $pdbk = $pdbks[$key];
4290 $searchkey = "<!--LINK $key-->";
4291 $title = $this->mLinkHolders
['titles'][$key];
4292 if ( empty( $colours[$pdbk] ) ) {
4293 $linkCache->addBadLinkObj( $title );
4294 $colours[$pdbk] = 0;
4295 $this->mOutput
->addLink( $title, 0 );
4296 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4297 $this->mLinkHolders
['texts'][$key],
4298 $this->mLinkHolders
['queries'][$key] );
4299 } elseif ( $colours[$pdbk] == 1 ) {
4300 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4301 $this->mLinkHolders
['texts'][$key],
4302 $this->mLinkHolders
['queries'][$key] );
4303 } elseif ( $colours[$pdbk] == 2 ) {
4304 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4305 $this->mLinkHolders
['texts'][$key],
4306 $this->mLinkHolders
['queries'][$key] );
4309 $replacer = new HashtableReplacer( $replacePairs, 1 );
4310 wfProfileOut( $fname.'-construct' );
4313 wfProfileIn( $fname.'-replace' );
4314 $text = preg_replace_callback(
4315 '/(<!--LINK .*?-->)/',
4319 wfProfileOut( $fname.'-replace' );
4322 # Now process interwiki link holders
4323 # This is quite a bit simpler than internal links
4324 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4325 wfProfileIn( $fname.'-interwiki' );
4326 # Make interwiki link HTML
4327 $replacePairs = array();
4328 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4329 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4330 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4332 $replacer = new HashtableReplacer( $replacePairs, 1 );
4334 $text = preg_replace_callback(
4335 '/<!--IWLINK (.*?)-->/',
4338 wfProfileOut( $fname.'-interwiki' );
4341 wfProfileOut( $fname );
4346 * Replace <!--LINK--> link placeholders with plain text of links
4347 * (not HTML-formatted).
4348 * @param string $text
4351 function replaceLinkHoldersText( $text ) {
4352 $fname = 'Parser::replaceLinkHoldersText';
4353 wfProfileIn( $fname );
4355 $text = preg_replace_callback(
4356 '/<!--(LINK|IWLINK) (.*?)-->/',
4357 array( &$this, 'replaceLinkHoldersTextCallback' ),
4360 wfProfileOut( $fname );
4365 * @param array $matches
4369 function replaceLinkHoldersTextCallback( $matches ) {
4370 $type = $matches[1];
4372 if( $type == 'LINK' ) {
4373 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4374 return $this->mLinkHolders
['texts'][$key];
4376 } elseif( $type == 'IWLINK' ) {
4377 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4378 return $this->mInterwikiLinkHolders
['texts'][$key];
4385 * Tag hook handler for 'pre'.
4387 function renderPreTag( $text, $attribs ) {
4388 // Backwards-compatibility hack
4389 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4391 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4392 return wfOpenElement( 'pre', $attribs ) .
4393 Xml
::escapeTagsOnly( $content ) .
4398 * Renders an image gallery from a text with one line per image.
4399 * text labels may be given by using |-style alternative text. E.g.
4400 * Image:one.jpg|The number "1"
4401 * Image:tree.jpg|A tree
4402 * given as text will return the HTML of a gallery with two images,
4403 * labeled 'The number "1"' and
4406 function renderImageGallery( $text, $params ) {
4407 $ig = new ImageGallery();
4408 $ig->setContextTitle( $this->mTitle
);
4409 $ig->setShowBytes( false );
4410 $ig->setShowFilename( false );
4411 $ig->setParser( $this );
4412 $ig->setHideBadImages();
4413 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4414 $ig->useSkin( $this->mOptions
->getSkin() );
4415 $ig->mRevisionId
= $this->mRevisionId
;
4417 if( isset( $params['caption'] ) ) {
4418 $caption = $params['caption'];
4419 $caption = htmlspecialchars( $caption );
4420 $caption = $this->replaceInternalLinks( $caption );
4421 $ig->setCaptionHtml( $caption );
4423 if( isset( $params['perrow'] ) ) {
4424 $ig->setPerRow( $params['perrow'] );
4426 if( isset( $params['widths'] ) ) {
4427 $ig->setWidths( $params['widths'] );
4429 if( isset( $params['heights'] ) ) {
4430 $ig->setHeights( $params['heights'] );
4433 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4435 $lines = explode( "\n", $text );
4436 foreach ( $lines as $line ) {
4437 # match lines like these:
4438 # Image:someimage.jpg|This is some image
4440 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4442 if ( count( $matches ) == 0 ) {
4445 $tp = Title
::newFromText( $matches[1] );
4447 if( is_null( $nt ) ) {
4448 # Bogus title. Ignore these so we don't bomb out later.
4451 if ( isset( $matches[3] ) ) {
4452 $label = $matches[3];
4457 $pout = $this->parse( $label,
4460 false, // Strip whitespace...?
4461 false // Don't clear state!
4463 $html = $pout->getText();
4465 $ig->add( $nt, $html );
4467 # Only add real images (bug #5586)
4468 if ( $nt->getNamespace() == NS_IMAGE
) {
4469 $this->mOutput
->addImage( $nt->getDBkey() );
4472 return $ig->toHTML();
4475 function getImageParams( $handler ) {
4477 $handlerClass = get_class( $handler );
4481 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4482 // Initialise static lists
4483 static $internalParamNames = array(
4484 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4485 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4486 'bottom', 'text-bottom' ),
4487 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4488 'upright', 'border' ),
4490 static $internalParamMap;
4491 if ( !$internalParamMap ) {
4492 $internalParamMap = array();
4493 foreach ( $internalParamNames as $type => $names ) {
4494 foreach ( $names as $name ) {
4495 $magicName = str_replace( '-', '_', "img_$name" );
4496 $internalParamMap[$magicName] = array( $type, $name );
4501 // Add handler params
4502 $paramMap = $internalParamMap;
4504 $handlerParamMap = $handler->getParamMap();
4505 foreach ( $handlerParamMap as $magic => $paramName ) {
4506 $paramMap[$magic] = array( 'handler', $paramName );
4509 $this->mImageParams
[$handlerClass] = $paramMap;
4510 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4512 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4516 * Parse image options text and use it to make an image
4518 function makeImage( $title, $options ) {
4519 # @TODO: let the MediaHandler specify its transform parameters
4521 # Check if the options text is of the form "options|alt text"
4523 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4524 # * left no resizing, just left align. label is used for alt= only
4525 # * right same, but right aligned
4526 # * none same, but not aligned
4527 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4528 # * center center the image
4529 # * framed Keep original image size, no magnify-button.
4530 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4531 # * upright reduce width for upright images, rounded to full __0 px
4532 # * border draw a 1px border around the image
4533 # vertical-align values (no % or length right now):
4543 $parts = array_map( 'trim', explode( '|', $options) );
4544 $sk = $this->mOptions
->getSkin();
4546 # Give extensions a chance to select the file revision for us
4547 $skip = $time = false;
4548 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4551 return $sk->makeLinkObj( $title );
4555 $file = wfFindFile( $title, $time );
4556 $handler = $file ?
$file->getHandler() : false;
4558 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4560 # Process the input parameters
4562 $params = array( 'frame' => array(), 'handler' => array(),
4563 'horizAlign' => array(), 'vertAlign' => array() );
4564 foreach( $parts as $part ) {
4565 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4566 if ( isset( $paramMap[$magicName] ) ) {
4567 list( $type, $paramName ) = $paramMap[$magicName];
4568 $params[$type][$paramName] = $value;
4570 // Special case; width and height come in one variable together
4571 if( $type == 'handler' && $paramName == 'width' ) {
4573 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4574 $params[$type]['width'] = intval( $m[1] );
4575 $params[$type]['height'] = intval( $m[2] );
4577 $params[$type]['width'] = intval( $value );
4585 # Process alignment parameters
4586 if ( $params['horizAlign'] ) {
4587 $params['frame']['align'] = key( $params['horizAlign'] );
4589 if ( $params['vertAlign'] ) {
4590 $params['frame']['valign'] = key( $params['vertAlign'] );
4593 # Validate the handler parameters
4595 foreach ( $params['handler'] as $name => $value ) {
4596 if ( !$handler->validateParam( $name, $value ) ) {
4597 unset( $params['handler'][$name] );
4602 # Strip bad stuff out of the alt text
4603 $alt = $this->replaceLinkHoldersText( $caption );
4605 # make sure there are no placeholders in thumbnail attributes
4606 # that are later expanded to html- so expand them now and
4608 $alt = $this->mStripState
->unstripBoth( $alt );
4609 $alt = Sanitizer
::stripAllTags( $alt );
4611 $params['frame']['alt'] = $alt;
4612 $params['frame']['caption'] = $caption;
4614 # Linker does the rest
4615 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4617 # Give the handler a chance to modify the parser object
4619 $handler->parserTransformHook( $this, $file );
4626 * Set a flag in the output object indicating that the content is dynamic and
4627 * shouldn't be cached.
4629 function disableCache() {
4630 wfDebug( "Parser output marked as uncacheable.\n" );
4631 $this->mOutput
->mCacheTime
= -1;
4635 * Callback from the Sanitizer for expanding items found in HTML attribute
4636 * values, so they can be safely tested and escaped.
4637 * @param string $text
4638 * @param array $args
4642 function attributeStripCallback( &$text, $args ) {
4643 $text = $this->replaceVariables( $text, $args );
4644 $text = $this->mStripState
->unstripBoth( $text );
4653 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4654 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4655 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4661 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4666 * Break wikitext input into sections, and either pull or replace
4667 * some particular section's text.
4669 * External callers should use the getSection and replaceSection methods.
4671 * @param $text Page wikitext
4672 * @param $section Numbered section. 0 pulls the text before the first
4673 * heading; other numbers will pull the given section
4674 * along with its lower-level subsections.
4675 * @param $mode One of "get" or "replace"
4676 * @param $newtext Replacement text for section data.
4677 * @return string for "get", the extracted section text.
4678 * for "replace", the whole page with the section replaced.
4680 private function extractSections( $text, $section, $mode, $newtext='' ) {
4681 # I.... _hope_ this is right.
4682 # Otherwise, sometimes we don't have things initialized properly.
4683 $this->clearState();
4685 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4686 # comments to be stripped as well)
4687 $stripState = new StripState
;
4689 $oldOutputType = $this->mOutputType
;
4690 $oldOptions = $this->mOptions
;
4691 $this->mOptions
= new ParserOptions();
4692 $this->setOutputType( OT_WIKI
);
4694 $striptext = $this->strip( $text, $stripState, true );
4696 $this->setOutputType( $oldOutputType );
4697 $this->mOptions
= $oldOptions;
4699 # now that we can be sure that no pseudo-sections are in the source,
4700 # split it up by section
4701 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4702 $comment = "(?:$uniq-!--.*?QINU\x07)";
4707 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4708 (=+) # Should this be limited to 6?
4709 .+? # Section title...
4710 \\2 # Ending = count must match start
4711 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4720 PREG_SPLIT_DELIM_CAPTURE
);
4722 if( $mode == "get" ) {
4723 if( $section == 0 ) {
4724 // "Section 0" returns the content before any other section.
4727 //track missing section, will replace if found.
4730 } elseif( $mode == "replace" ) {
4731 if( $section == 0 ) {
4732 $rv = $newtext . "\n\n";
4741 for( $index = 1; $index < count( $secs ); ) {
4742 $headerLine = $secs[$index++
];
4743 if( $secs[$index] ) {
4745 $headerLevel = strlen( $secs[$index++
] );
4749 $headerLevel = intval( $secs[$index++
] );
4751 $content = $secs[$index++
];
4754 if( $mode == "get" ) {
4755 if( $count == $section ) {
4756 $rv = $headerLine . $content;
4757 $sectionLevel = $headerLevel;
4758 } elseif( $count > $section ) {
4759 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4760 $rv .= $headerLine . $content;
4762 // Broke out to a higher-level section
4766 } elseif( $mode == "replace" ) {
4767 if( $count < $section ) {
4768 $rv .= $headerLine . $content;
4769 } elseif( $count == $section ) {
4770 $rv .= $newtext . "\n\n";
4771 $sectionLevel = $headerLevel;
4772 } elseif( $count > $section ) {
4773 if( $headerLevel <= $sectionLevel ) {
4774 // Passed the section's sub-parts.
4778 $rv .= $headerLine . $content;
4784 # reinsert stripped tags
4785 $rv = trim( $stripState->unstripBoth( $rv ) );
4791 * This function returns the text of a section, specified by a number ($section).
4792 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4793 * the first section before any such heading (section 0).
4795 * If a section contains subsections, these are also returned.
4797 * @param $text String: text to look in
4798 * @param $section Integer: section number
4799 * @param $deftext: default to return if section is not found
4800 * @return string text of the requested section
4802 public function getSection( $text, $section, $deftext='' ) {
4803 return $this->extractSections( $text, $section, "get", $deftext );
4806 public function replaceSection( $oldtext, $section, $text ) {
4807 return $this->extractSections( $oldtext, $section, "replace", $text );
4811 * Get the timestamp associated with the current revision, adjusted for
4812 * the default server-local timestamp
4814 function getRevisionTimestamp() {
4815 if ( is_null( $this->mRevisionTimestamp
) ) {
4816 wfProfileIn( __METHOD__
);
4818 $dbr = wfGetDB( DB_SLAVE
);
4819 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4820 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4822 // Normalize timestamp to internal MW format for timezone processing.
4823 // This has the added side-effect of replacing a null value with
4824 // the current time, which gives us more sensible behavior for
4826 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4828 // The cryptic '' timezone parameter tells to use the site-default
4829 // timezone offset instead of the user settings.
4831 // Since this value will be saved into the parser cache, served
4832 // to other users, and potentially even used inside links and such,
4833 // it needs to be consistent for all visitors.
4834 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4836 wfProfileOut( __METHOD__
);
4838 return $this->mRevisionTimestamp
;
4842 * Mutator for $mDefaultSort
4844 * @param $sort New value
4846 public function setDefaultSort( $sort ) {
4847 $this->mDefaultSort
= $sort;
4851 * Accessor for $mDefaultSort
4852 * Will use the title/prefixed title if none is set
4856 public function getDefaultSort() {
4857 if( $this->mDefaultSort
!== false ) {
4858 return $this->mDefaultSort
;
4860 return $this->mTitle
->getNamespace() == NS_CATEGORY
4861 ?
$this->mTitle
->getText()
4862 : $this->mTitle
->getPrefixedText();
4867 * Try to guess the section anchor name based on a wikitext fragment
4868 * presumably extracted from a heading, for example "Header" from
4871 public function guessSectionNameFromWikiText( $text ) {
4872 # Strip out wikitext links(they break the anchor)
4873 $text = $this->stripSectionName( $text );
4874 $headline = Sanitizer
::decodeCharReferences( $text );
4876 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4877 $headline = trim( $headline );
4878 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4879 $replacearray = array(
4884 array_keys( $replacearray ),
4885 array_values( $replacearray ),
4890 * Strips a text string of wikitext for use in a section anchor
4892 * Accepts a text string and then removes all wikitext from the
4893 * string and leaves only the resultant text (i.e. the result of
4894 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4895 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4896 * to create valid section anchors by mimicing the output of the
4897 * parser when headings are parsed.
4899 * @param $text string Text string to be stripped of wikitext
4900 * for use in a Section anchor
4901 * @return Filtered text string
4903 public function stripSectionName( $text ) {
4904 # Strip internal link markup
4905 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4906 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4908 # Strip external link markup (FIXME: Not Tolerant to blank link text
4909 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4910 # on how many empty links there are on the page - need to figure that out.
4911 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4913 # Parse wikitext quotes (italics & bold)
4914 $text = $this->doQuotes($text);
4917 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4922 * strip/replaceVariables/unstrip for preprocessor regression testing
4924 function srvus( $text ) {
4925 $text = $this->strip( $text, $this->mStripState
);
4926 $text = Sanitizer
::removeHTMLtags( $text );
4927 $text = $this->replaceVariables( $text );
4928 $text = preg_replace( '/<!--MWTEMPLATESECTION.*?-->/', '', $text );
4929 $text = $this->mStripState
->unstripBoth( $text );