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
) {
84 $this->mFirstCall
= false;
86 wfProfileIn( __METHOD__
);
87 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
89 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
91 # Syntax for arguments (see self::setFunctionHook):
92 # "name for lookup in localized magic words array",
94 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
95 # instead of {{#int:...}})
96 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
97 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
98 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
99 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
100 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
101 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
102 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
103 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
104 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
105 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
106 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
107 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
108 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
109 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
110 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
111 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
112 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
113 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
114 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
115 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
116 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
117 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
118 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
119 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
120 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
121 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
122 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
124 if ( $wgAllowDisplayTitle ) {
125 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
127 if ( $wgAllowSlowParserFunctions ) {
128 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
131 $this->initialiseVariables();
133 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
134 wfProfileOut( __METHOD__
);
142 function clearState() {
143 wfProfileIn( __METHOD__
);
144 if ( $this->mFirstCall
) {
145 $this->firstCallInit();
147 $this->mOutput
= new ParserOutput
;
148 $this->mAutonumber
= 0;
149 $this->mLastSection
= '';
150 $this->mDTopen
= false;
151 $this->mIncludeCount
= array();
152 $this->mStripState
= new StripState
;
153 $this->mArgStack
= array();
154 $this->mInPre
= false;
155 $this->mInterwikiLinkHolders
= array(
159 $this->mLinkHolders
= array(
160 'namespaces' => array(),
162 'queries' => array(),
166 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
169 * Prefix for temporary replacement strings for the multipass parser.
170 * \x07 should never appear in input as it's disallowed in XML.
171 * Using it at the front also gives us a little extra robustness
172 * since it shouldn't match when butted up against identifier-like
175 $this->mUniqPrefix
= "\x07UNIQ" . self
::getRandomString();
177 # Clear these on every parse, bug 4549
178 $this->mTemplates
= array();
179 $this->mTemplatePath
= array();
181 $this->mShowToc
= true;
182 $this->mForceTocPosition
= false;
183 $this->mIncludeSizes
= array(
188 $this->mDefaultSort
= false;
190 wfRunHooks( 'ParserClearState', array( &$this ) );
191 wfProfileOut( __METHOD__
);
194 function setOutputType( $ot ) {
195 $this->mOutputType
= $ot;
198 'html' => $ot == OT_HTML
,
199 'wiki' => $ot == OT_WIKI
,
200 'msg' => $ot == OT_MSG
,
201 'pre' => $ot == OT_PREPROCESS
,
206 * Accessor for mUniqPrefix.
210 function uniqPrefix() {
211 return $this->mUniqPrefix
;
215 * Convert wikitext to HTML
216 * Do not call this function recursively.
218 * @param string $text Text we want to parse
219 * @param Title &$title A title object
220 * @param array $options
221 * @param boolean $linestart
222 * @param boolean $clearState
223 * @param int $revid number to pass in {{REVISIONID}}
224 * @return ParserOutput a ParserOutput
226 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
228 * First pass--just handle <nowiki> sections, pass the rest off
229 * to internalParse() which does all the real work.
232 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
233 $fname = 'Parser::parse-' . wfGetCaller();
234 wfProfileIn( __METHOD__
);
235 wfProfileIn( $fname );
241 $this->mOptions
= $options;
242 $this->mTitle
=& $title;
243 $oldRevisionId = $this->mRevisionId
;
244 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
245 if( $revid !== null ) {
246 $this->mRevisionId
= $revid;
247 $this->mRevisionTimestamp
= null;
249 $this->setOutputType( OT_HTML
);
250 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
251 $text = $this->strip( $text, $this->mStripState
);
252 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
253 $text = $this->internalParse( $text );
254 $text = $this->mStripState
->unstripGeneral( $text );
256 # Clean up special characters, only run once, next-to-last before doBlockLevels
258 # french spaces, last one Guillemet-left
259 # only if there is something before the space
260 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
261 # french spaces, Guillemet-right
262 '/(\\302\\253) /' => '\\1 ',
264 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
267 $text = $this->doBlockLevels( $text, $linestart );
269 $this->replaceLinkHolders( $text );
271 # the position of the parserConvert() call should not be changed. it
272 # assumes that the links are all replaced and the only thing left
273 # is the <nowiki> mark.
274 # Side-effects: this calls $this->mOutput->setTitleText()
275 $text = $wgContLang->parserConvert( $text, $this );
277 $text = $this->mStripState
->unstripNoWiki( $text );
279 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
281 //!JF Move to its own function
283 $uniq_prefix = $this->mUniqPrefix
;
285 $elements = array_keys( $this->mTransparentTagHooks
);
286 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
288 foreach( $matches as $marker => $data ) {
289 list( $element, $content, $params, $tag ) = $data;
290 $tagName = strtolower( $element );
291 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
292 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
293 array( $content, $params, $this ) );
297 $this->mStripState
->general
->setPair( $marker, $output );
299 $text = $this->mStripState
->unstripGeneral( $text );
301 $text = Sanitizer
::normalizeCharReferences( $text );
303 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
304 $text = self
::tidy($text);
306 # attempt to sanitize at least some nesting problems
307 # (bug #2702 and quite a few others)
309 # ''Something [http://www.cool.com cool''] -->
310 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
311 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
312 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
313 # fix up an anchor inside another anchor, only
314 # at least for a single single nested link (bug 3695)
315 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
316 '\\1\\2</a>\\3</a>\\1\\4</a>',
317 # fix div inside inline elements- doBlockLevels won't wrap a line which
318 # contains a div, so fix it up here; replace
319 # div with escaped text
320 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
321 '\\1\\3<div\\5>\\6</div>\\8\\9',
322 # remove empty italic or bold tag pairs, some
323 # introduced by rules above
324 '/<([bi])><\/\\1>/' => '',
327 $text = preg_replace(
328 array_keys( $tidyregs ),
329 array_values( $tidyregs ),
333 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
335 # Information on include size limits, for the benefit of users who try to skirt them
336 if ( $this->mOptions
->getEnableLimitReport() ) {
337 $max = $this->mOptions
->getMaxIncludeSize();
339 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']}/$max bytes\n" .
340 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
341 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
342 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
343 $text .= "<!-- \n$limitReport-->\n";
345 $this->mOutput
->setText( $text );
346 $this->mRevisionId
= $oldRevisionId;
347 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
348 wfProfileOut( $fname );
349 wfProfileOut( __METHOD__
);
351 return $this->mOutput
;
355 * Recursive parser entry point that can be called from an extension tag
358 function recursiveTagParse( $text ) {
359 wfProfileIn( __METHOD__
);
360 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
361 $text = $this->strip( $text, $this->mStripState
);
362 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
363 $text = $this->internalParse( $text );
364 wfProfileOut( __METHOD__
);
369 * Expand templates and variables in the text, producing valid, static wikitext.
370 * Also removes comments.
372 function preprocess( $text, $title, $options, $revid = null ) {
373 wfProfileIn( __METHOD__
);
375 $this->setOutputType( OT_PREPROCESS
);
376 $this->mOptions
= $options;
377 $this->mTitle
= $title;
378 if( $revid !== null ) {
379 $this->mRevisionId
= $revid;
381 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
382 $text = $this->strip( $text, $this->mStripState
);
383 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
384 if ( $this->mOptions
->getRemoveComments() ) {
385 $text = Sanitizer
::removeHTMLcomments( $text );
387 $text = $this->replaceVariables( $text );
388 $text = $this->mStripState
->unstripBoth( $text );
389 wfProfileOut( __METHOD__
);
394 * Get a random string
399 function getRandomString() {
400 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
403 function &getTitle() { return $this->mTitle
; }
404 function getOptions() { return $this->mOptions
; }
406 function getFunctionLang() {
407 global $wgLang, $wgContLang;
408 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
412 * Replaces all occurrences of HTML-style comments and the given tags
413 * in the text with a random marker and returns teh next text. The output
414 * parameter $matches will be an associative array filled with data in
416 * 'UNIQ-xxxxx' => array(
419 * array( 'param' => 'x' ),
420 * '<element param="x">tag content</element>' ) )
422 * @param $elements list of element names. Comments are always extracted.
423 * @param $text Source text string.
424 * @param $uniq_prefix
429 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
434 $taglist = implode( '|', $elements );
435 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
437 while ( '' != $text ) {
438 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
440 if( count( $p ) < 5 ) {
443 if( count( $p ) > 5 ) {
457 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
458 $stripped .= $marker;
460 if ( $close === '/>' ) {
461 // Empty element tag, <tag />
466 if( $element == '!--' ) {
469 $end = "/(<\\/$element\\s*>)/i";
471 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
473 if( count( $q ) < 3 ) {
474 # No end tag -- let it run out to the end of the text.
483 $matches[$marker] = array( $element,
485 Sanitizer
::decodeTagAttributes( $attributes ),
486 "<$element$attributes$close$content$tail" );
492 * Strips and renders nowiki, pre, math, hiero
493 * If $render is set, performs necessary rendering operations on plugins
494 * Returns the text, and fills an array with data needed in unstrip()
496 * @param StripState $state
498 * @param bool $stripcomments when set, HTML comments <!-- like this -->
499 * will be stripped in addition to other tags. This is important
500 * for section editing, where these comments cause confusion when
501 * counting the sections in the wikisource
503 * @param array dontstrip contains tags which should not be stripped;
504 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
508 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
510 wfProfileIn( __METHOD__
);
511 $render = ($this->mOutputType
== OT_HTML
);
513 $uniq_prefix = $this->mUniqPrefix
;
514 $commentState = new ReplacementArray
;
515 $nowikiItems = array();
516 $generalItems = array();
518 $elements = array_merge(
519 array( 'nowiki', 'gallery' ),
520 array_keys( $this->mTagHooks
) );
523 $elements[] = 'html';
525 if( $this->mOptions
->getUseTeX() ) {
526 $elements[] = 'math';
529 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
530 foreach ( $elements AS $k => $v ) {
531 if ( !in_array ( $v , $dontstrip ) ) continue;
532 unset ( $elements[$k] );
536 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
538 foreach( $matches as $marker => $data ) {
539 list( $element, $content, $params, $tag ) = $data;
541 $tagName = strtolower( $element );
542 wfProfileIn( __METHOD__
."-render-$tagName" );
546 if( substr( $tag, -3 ) == '-->' ) {
549 // Unclosed comment in input.
550 // Close it so later stripping can remove it
559 // Shouldn't happen otherwise. :)
561 $output = Xml
::escapeTagsOnly( $content );
564 $output = $wgContLang->armourMath(
565 MathRenderer
::renderMath( $content, $params ) );
568 $output = $this->renderImageGallery( $content, $params );
571 if( isset( $this->mTagHooks
[$tagName] ) ) {
572 $output = call_user_func_array( $this->mTagHooks
[$tagName],
573 array( $content, $params, $this ) );
575 throw new MWException( "Invalid call hook $element" );
578 wfProfileOut( __METHOD__
."-render-$tagName" );
580 // Just stripping tags; keep the source
584 // Unstrip the output, to support recursive strip() calls
585 $output = $state->unstripBoth( $output );
587 if( !$stripcomments && $element == '!--' ) {
588 $commentState->setPair( $marker, $output );
589 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
590 $nowikiItems[$marker] = $output;
592 $generalItems[$marker] = $output;
595 # Add the new items to the state
596 # We do this after the loop instead of during it to avoid slowing
597 # down the recursive unstrip
598 $state->nowiki
->mergeArray( $nowikiItems );
599 $state->general
->mergeArray( $generalItems );
601 # Unstrip comments unless explicitly told otherwise.
602 # (The comments are always stripped prior to this point, so as to
603 # not invoke any extension tags / parser hooks contained within
605 if ( !$stripcomments ) {
606 // Put them all back and forget them
607 $text = $commentState->replace( $text );
610 wfProfileOut( __METHOD__
);
615 * Restores pre, math, and other extensions removed by strip()
617 * always call unstripNoWiki() after this one
619 * @deprecated use $this->mStripState->unstrip()
621 function unstrip( $text, $state ) {
622 return $state->unstripGeneral( $text );
626 * Always call this after unstrip() to preserve the order
629 * @deprecated use $this->mStripState->unstrip()
631 function unstripNoWiki( $text, $state ) {
632 return $state->unstripNoWiki( $text );
636 * @deprecated use $this->mStripState->unstripBoth()
638 function unstripForHTML( $text ) {
639 return $this->mStripState
->unstripBoth( $text );
643 * Add an item to the strip state
644 * Returns the unique tag which must be inserted into the stripped text
645 * The tag will be replaced with the original text in unstrip()
649 function insertStripItem( $text, &$state ) {
650 $rnd = $this->mUniqPrefix
. '-item' . self
::getRandomString();
651 $state->general
->setPair( $rnd, $text );
656 * Interface with html tidy, used if $wgUseTidy = true.
657 * If tidy isn't able to correct the markup, the original will be
658 * returned in all its glory with a warning comment appended.
660 * Either the external tidy program or the in-process tidy extension
661 * will be used depending on availability. Override the default
662 * $wgTidyInternal setting to disable the internal if it's not working.
664 * @param string $text Hideous HTML input
665 * @return string Corrected HTML output
669 function tidy( $text ) {
670 global $wgTidyInternal;
671 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
672 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
673 '<head><title>test</title></head><body>'.$text.'</body></html>';
674 if( $wgTidyInternal ) {
675 $correctedtext = self
::internalTidy( $wrappedtext );
677 $correctedtext = self
::externalTidy( $wrappedtext );
679 if( is_null( $correctedtext ) ) {
680 wfDebug( "Tidy error detected!\n" );
681 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
683 return $correctedtext;
687 * Spawn an external HTML tidy process and get corrected markup back from it.
692 function externalTidy( $text ) {
693 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
694 $fname = 'Parser::externalTidy';
695 wfProfileIn( $fname );
700 $descriptorspec = array(
701 0 => array('pipe', 'r'),
702 1 => array('pipe', 'w'),
703 2 => array('file', wfGetNull(), 'a')
706 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
707 if (is_resource($process)) {
708 // Theoretically, this style of communication could cause a deadlock
709 // here. If the stdout buffer fills up, then writes to stdin could
710 // block. This doesn't appear to happen with tidy, because tidy only
711 // writes to stdout after it's finished reading from stdin. Search
712 // for tidyParseStdin and tidySaveStdout in console/tidy.c
713 fwrite($pipes[0], $text);
715 while (!feof($pipes[1])) {
716 $cleansource .= fgets($pipes[1], 1024);
719 proc_close($process);
722 wfProfileOut( $fname );
724 if( $cleansource == '' && $text != '') {
725 // Some kind of error happened, so we couldn't get the corrected text.
726 // Just give up; we'll use the source text and append a warning.
734 * Use the HTML tidy PECL extension to use the tidy library in-process,
735 * saving the overhead of spawning a new process.
737 * 'pear install tidy' should be able to compile the extension module.
742 function internalTidy( $text ) {
743 global $wgTidyConf, $IP;
744 $fname = 'Parser::internalTidy';
745 wfProfileIn( $fname );
748 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
749 $tidy->cleanRepair();
750 if( $tidy->getStatus() == 2 ) {
751 // 2 is magic number for fatal error
752 // http://www.php.net/manual/en/function.tidy-get-status.php
755 $cleansource = tidy_get_output( $tidy );
757 wfProfileOut( $fname );
762 * parse the wiki syntax used to render tables
766 function doTableStuff ( $text ) {
767 $fname = 'Parser::doTableStuff';
768 wfProfileIn( $fname );
770 $lines = explode ( "\n" , $text );
771 $td_history = array (); // Is currently a td tag open?
772 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
773 $tr_history = array (); // Is currently a tr tag open?
774 $tr_attributes = array (); // history of tr attributes
775 $has_opened_tr = array(); // Did this table open a <tr> element?
776 $indent_level = 0; // indent level of the table
777 foreach ( $lines as $key => $line )
779 $line = trim ( $line );
781 if( $line == '' ) { // empty line, go to next line
784 $first_character = $line{0};
787 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
788 // First check if we are starting a new table
789 $indent_level = strlen( $matches[1] );
791 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
792 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
794 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
795 array_push ( $td_history , false );
796 array_push ( $last_tag_history , '' );
797 array_push ( $tr_history , false );
798 array_push ( $tr_attributes , '' );
799 array_push ( $has_opened_tr , false );
800 } else if ( count ( $td_history ) == 0 ) {
801 // Don't do any of the following
803 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
804 // We are ending a table
805 $line = '</table>' . substr ( $line , 2 );
806 $last_tag = array_pop ( $last_tag_history );
808 if ( !array_pop ( $has_opened_tr ) ) {
809 $line = "<tr><td></td></tr>{$line}";
812 if ( array_pop ( $tr_history ) ) {
813 $line = "</tr>{$line}";
816 if ( array_pop ( $td_history ) ) {
817 $line = "</{$last_tag}>{$line}";
819 array_pop ( $tr_attributes );
820 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
821 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
822 // Now we have a table row
823 $line = preg_replace( '#^\|-+#', '', $line );
825 // Whats after the tag is now only attributes
826 $attributes = $this->mStripState
->unstripBoth( $line );
827 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
828 array_pop ( $tr_attributes );
829 array_push ( $tr_attributes , $attributes );
832 $last_tag = array_pop ( $last_tag_history );
833 array_pop ( $has_opened_tr );
834 array_push ( $has_opened_tr , true );
836 if ( array_pop ( $tr_history ) ) {
840 if ( array_pop ( $td_history ) ) {
841 $line = "</{$last_tag}>{$line}";
844 $lines[$key] = $line;
845 array_push ( $tr_history , false );
846 array_push ( $td_history , false );
847 array_push ( $last_tag_history , '' );
849 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
850 // This might be cell elements, td, th or captions
851 if ( substr ( $line , 0 , 2 ) == '|+' ) {
852 $first_character = '+';
853 $line = substr ( $line , 1 );
856 $line = substr ( $line , 1 );
858 if ( $first_character == '!' ) {
859 $line = str_replace ( '!!' , '||' , $line );
862 // Split up multiple cells on the same line.
863 // FIXME : This can result in improper nesting of tags processed
864 // by earlier parser steps, but should avoid splitting up eg
865 // attribute values containing literal "||".
866 $cells = StringUtils
::explodeMarkup( '||' , $line );
870 // Loop through each table cell
871 foreach ( $cells as $cell )
874 if ( $first_character != '+' )
876 $tr_after = array_pop ( $tr_attributes );
877 if ( !array_pop ( $tr_history ) ) {
878 $previous = "<tr{$tr_after}>\n";
880 array_push ( $tr_history , true );
881 array_push ( $tr_attributes , '' );
882 array_pop ( $has_opened_tr );
883 array_push ( $has_opened_tr , true );
886 $last_tag = array_pop ( $last_tag_history );
888 if ( array_pop ( $td_history ) ) {
889 $previous = "</{$last_tag}>{$previous}";
892 if ( $first_character == '|' ) {
894 } else if ( $first_character == '!' ) {
896 } else if ( $first_character == '+' ) {
897 $last_tag = 'caption';
902 array_push ( $last_tag_history , $last_tag );
904 // A cell could contain both parameters and data
905 $cell_data = explode ( '|' , $cell , 2 );
907 // Bug 553: Note that a '|' inside an invalid link should not
908 // be mistaken as delimiting cell parameters
909 if ( strpos( $cell_data[0], '[[' ) !== false ) {
910 $cell = "{$previous}<{$last_tag}>{$cell}";
911 } else if ( count ( $cell_data ) == 1 )
912 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
914 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
915 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
916 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
919 $lines[$key] .= $cell;
920 array_push ( $td_history , true );
925 // Closing open td, tr && table
926 while ( count ( $td_history ) > 0 )
928 if ( array_pop ( $td_history ) ) {
931 if ( array_pop ( $tr_history ) ) {
934 if ( !array_pop ( $has_opened_tr ) ) {
935 $lines[] = "<tr><td></td></tr>" ;
938 $lines[] = '</table>' ;
941 $output = implode ( "\n" , $lines ) ;
943 // special case: don't return empty table
944 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
948 wfProfileOut( $fname );
954 * Helper function for parse() that transforms wiki markup into
955 * HTML. Only called for $mOutputType == OT_HTML.
959 function internalParse( $text ) {
962 $fname = 'Parser::internalParse';
963 wfProfileIn( $fname );
965 # Hook to suspend the parser in this state
966 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
967 wfProfileOut( $fname );
971 # Remove <noinclude> tags and <includeonly> sections
972 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
973 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
974 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
976 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
978 $text = $this->replaceVariables( $text, $args );
979 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
981 // Tables need to come after variable replacement for things to work
982 // properly; putting them before other transformations should keep
983 // exciting things like link expansions from showing up in surprising
985 $text = $this->doTableStuff( $text );
987 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
989 $text = $this->stripToc( $text );
990 $this->stripNoGallery( $text );
991 $text = $this->doHeadings( $text );
992 if($this->mOptions
->getUseDynamicDates()) {
993 $df =& DateFormatter
::getInstance();
994 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
996 $text = $this->doAllQuotes( $text );
997 $text = $this->replaceInternalLinks( $text );
998 $text = $this->replaceExternalLinks( $text );
1000 # replaceInternalLinks may sometimes leave behind
1001 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1002 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1004 $text = $this->doMagicLinks( $text );
1005 $text = $this->formatHeadings( $text, $isMain );
1007 wfProfileOut( $fname );
1012 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1013 * magic external links.
1017 function &doMagicLinks( &$text ) {
1018 wfProfileIn( __METHOD__
);
1019 $text = preg_replace_callback(
1021 <a.*?</a> | # Skip link text
1022 <.*?> | # Skip stuff inside HTML elements
1023 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1024 ISBN\s+(\b # ISBN, capture number as m[2]
1025 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1026 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1027 [0-9Xx] # check digit
1029 )!x', array( &$this, 'magicLinkCallback' ), $text );
1030 wfProfileOut( __METHOD__
);
1034 function magicLinkCallback( $m ) {
1035 if ( substr( $m[0], 0, 1 ) == '<' ) {
1038 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1040 $num = strtr( $isbn, array(
1045 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1046 $text = '<a href="' .
1047 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1048 "\" class=\"internal\">ISBN $isbn</a>";
1050 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1054 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1056 $urlmsg = 'pubmedurl';
1059 throw new MWException( __METHOD__
.': unrecognised match type "' .
1060 substr($m[0], 0, 20 ) . '"' );
1063 $url = wfMsg( $urlmsg, $id);
1064 $sk = $this->mOptions
->getSkin();
1065 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1066 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1072 * Parse headers and return html
1076 function doHeadings( $text ) {
1077 $fname = 'Parser::doHeadings';
1078 wfProfileIn( $fname );
1079 for ( $i = 6; $i >= 1; --$i ) {
1080 $h = str_repeat( '=', $i );
1081 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1082 "<h{$i}>\\1</h{$i}>\\2", $text );
1084 wfProfileOut( $fname );
1089 * Replace single quotes with HTML markup
1091 * @return string the altered text
1093 function doAllQuotes( $text ) {
1094 $fname = 'Parser::doAllQuotes';
1095 wfProfileIn( $fname );
1097 $lines = explode( "\n", $text );
1098 foreach ( $lines as $line ) {
1099 $outtext .= $this->doQuotes ( $line ) . "\n";
1101 $outtext = substr($outtext, 0,-1);
1102 wfProfileOut( $fname );
1107 * Helper function for doAllQuotes()
1109 public function doQuotes( $text ) {
1110 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1111 if ( count( $arr ) == 1 )
1115 # First, do some preliminary work. This may shift some apostrophes from
1116 # being mark-up to being text. It also counts the number of occurrences
1117 # of bold and italics mark-ups.
1121 foreach ( $arr as $r )
1123 if ( ( $i %
2 ) == 1 )
1125 # If there are ever four apostrophes, assume the first is supposed to
1126 # be text, and the remaining three constitute mark-up for bold text.
1127 if ( strlen( $arr[$i] ) == 4 )
1132 # If there are more than 5 apostrophes in a row, assume they're all
1133 # text except for the last 5.
1134 else if ( strlen( $arr[$i] ) > 5 )
1136 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1139 # Count the number of occurrences of bold and italics mark-ups.
1140 # We are not counting sequences of five apostrophes.
1141 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1142 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1143 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1148 # If there is an odd number of both bold and italics, it is likely
1149 # that one of the bold ones was meant to be an apostrophe followed
1150 # by italics. Which one we cannot know for certain, but it is more
1151 # likely to be one that has a single-letter word before it.
1152 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1155 $firstsingleletterword = -1;
1156 $firstmultiletterword = -1;
1158 foreach ( $arr as $r )
1160 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1162 $x1 = substr ($arr[$i-1], -1);
1163 $x2 = substr ($arr[$i-1], -2, 1);
1165 if ($firstspace == -1) $firstspace = $i;
1166 } else if ($x2 == ' ') {
1167 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1169 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1175 # If there is a single-letter word, use it!
1176 if ($firstsingleletterword > -1)
1178 $arr [ $firstsingleletterword ] = "''";
1179 $arr [ $firstsingleletterword-1 ] .= "'";
1181 # If not, but there's a multi-letter word, use that one.
1182 else if ($firstmultiletterword > -1)
1184 $arr [ $firstmultiletterword ] = "''";
1185 $arr [ $firstmultiletterword-1 ] .= "'";
1187 # ... otherwise use the first one that has neither.
1188 # (notice that it is possible for all three to be -1 if, for example,
1189 # there is only one pentuple-apostrophe in the line)
1190 else if ($firstspace > -1)
1192 $arr [ $firstspace ] = "''";
1193 $arr [ $firstspace-1 ] .= "'";
1197 # Now let's actually convert our apostrophic mush to HTML!
1202 foreach ($arr as $r)
1206 if ($state == 'both')
1213 if (strlen ($r) == 2)
1216 { $output .= '</i>'; $state = ''; }
1217 else if ($state == 'bi')
1218 { $output .= '</i>'; $state = 'b'; }
1219 else if ($state == 'ib')
1220 { $output .= '</b></i><b>'; $state = 'b'; }
1221 else if ($state == 'both')
1222 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1223 else # $state can be 'b' or ''
1224 { $output .= '<i>'; $state .= 'i'; }
1226 else if (strlen ($r) == 3)
1229 { $output .= '</b>'; $state = ''; }
1230 else if ($state == 'bi')
1231 { $output .= '</i></b><i>'; $state = 'i'; }
1232 else if ($state == 'ib')
1233 { $output .= '</b>'; $state = 'i'; }
1234 else if ($state == 'both')
1235 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1236 else # $state can be 'i' or ''
1237 { $output .= '<b>'; $state .= 'b'; }
1239 else if (strlen ($r) == 5)
1242 { $output .= '</b><i>'; $state = 'i'; }
1243 else if ($state == 'i')
1244 { $output .= '</i><b>'; $state = 'b'; }
1245 else if ($state == 'bi')
1246 { $output .= '</i></b>'; $state = ''; }
1247 else if ($state == 'ib')
1248 { $output .= '</b></i>'; $state = ''; }
1249 else if ($state == 'both')
1250 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1251 else # ($state == '')
1252 { $buffer = ''; $state = 'both'; }
1257 # Now close all remaining tags. Notice that the order is important.
1258 if ($state == 'b' ||
$state == 'ib')
1260 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1264 # There might be lonely ''''', so make sure we have a buffer
1265 if ($state == 'both' && $buffer)
1266 $output .= '<b><i>'.$buffer.'</i></b>';
1272 * Replace external links
1274 * Note: this is all very hackish and the order of execution matters a lot.
1275 * Make sure to run maintenance/parserTests.php if you change this code.
1279 function replaceExternalLinks( $text ) {
1281 $fname = 'Parser::replaceExternalLinks';
1282 wfProfileIn( $fname );
1284 $sk = $this->mOptions
->getSkin();
1286 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1288 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1291 while ( $i<count( $bits ) ) {
1293 $protocol = $bits[$i++
];
1294 $text = $bits[$i++
];
1295 $trail = $bits[$i++
];
1297 # The characters '<' and '>' (which were escaped by
1298 # removeHTMLtags()) should not be included in
1299 # URLs, per RFC 2396.
1301 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1302 $text = substr($url, $m2[0][1]) . ' ' . $text;
1303 $url = substr($url, 0, $m2[0][1]);
1306 # If the link text is an image URL, replace it with an <img> tag
1307 # This happened by accident in the original parser, but some people used it extensively
1308 $img = $this->maybeMakeExternalImage( $text );
1309 if ( $img !== false ) {
1315 # Set linktype for CSS - if URL==text, link is essentially free
1316 $linktype = ($text == $url) ?
'free' : 'text';
1318 # No link text, e.g. [http://domain.tld/some.link]
1319 if ( $text == '' ) {
1320 # Autonumber if allowed. See bug #5918
1321 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1322 $text = '[' . ++
$this->mAutonumber
. ']';
1323 $linktype = 'autonumber';
1325 # Otherwise just use the URL
1326 $text = htmlspecialchars( $url );
1330 # Have link text, e.g. [http://domain.tld/some.link text]s
1332 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1335 $text = $wgContLang->markNoConversion($text);
1337 $url = Sanitizer
::cleanUrl( $url );
1339 # Process the trail (i.e. everything after this link up until start of the next link),
1340 # replacing any non-bracketed links
1341 $trail = $this->replaceFreeExternalLinks( $trail );
1343 # Use the encoded URL
1344 # This means that users can paste URLs directly into the text
1345 # Funny characters like ö aren't valid in URLs anyway
1346 # This was changed in August 2004
1347 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1349 # Register link in the output object.
1350 # Replace unnecessary URL escape codes with the referenced character
1351 # This prevents spammers from hiding links from the filters
1352 $pasteurized = self
::replaceUnusualEscapes( $url );
1353 $this->mOutput
->addExternalLink( $pasteurized );
1356 wfProfileOut( $fname );
1361 * Replace anything that looks like a URL with a link
1364 function replaceFreeExternalLinks( $text ) {
1366 $fname = 'Parser::replaceFreeExternalLinks';
1367 wfProfileIn( $fname );
1369 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1370 $s = array_shift( $bits );
1373 $sk = $this->mOptions
->getSkin();
1375 while ( $i < count( $bits ) ){
1376 $protocol = $bits[$i++
];
1377 $remainder = $bits[$i++
];
1380 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1381 # Found some characters after the protocol that look promising
1382 $url = $protocol . $m[1];
1385 # special case: handle urls as url args:
1386 # http://www.example.com/foo?=http://www.example.com/bar
1387 if(strlen($trail) == 0 &&
1389 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1390 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1393 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1398 # The characters '<' and '>' (which were escaped by
1399 # removeHTMLtags()) should not be included in
1400 # URLs, per RFC 2396.
1402 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1403 $trail = substr($url, $m2[0][1]) . $trail;
1404 $url = substr($url, 0, $m2[0][1]);
1407 # Move trailing punctuation to $trail
1409 # If there is no left bracket, then consider right brackets fair game too
1410 if ( strpos( $url, '(' ) === false ) {
1414 $numSepChars = strspn( strrev( $url ), $sep );
1415 if ( $numSepChars ) {
1416 $trail = substr( $url, -$numSepChars ) . $trail;
1417 $url = substr( $url, 0, -$numSepChars );
1420 $url = Sanitizer
::cleanUrl( $url );
1422 # Is this an external image?
1423 $text = $this->maybeMakeExternalImage( $url );
1424 if ( $text === false ) {
1425 # Not an image, make a link
1426 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1427 # Register it in the output object...
1428 # Replace unnecessary URL escape codes with their equivalent characters
1429 $pasteurized = self
::replaceUnusualEscapes( $url );
1430 $this->mOutput
->addExternalLink( $pasteurized );
1432 $s .= $text . $trail;
1434 $s .= $protocol . $remainder;
1437 wfProfileOut( $fname );
1442 * Replace unusual URL escape codes with their equivalent characters
1446 * @todo This can merge genuinely required bits in the path or query string,
1447 * breaking legit URLs. A proper fix would treat the various parts of
1448 * the URL differently; as a workaround, just use the output for
1449 * statistical records, not for actual linking/output.
1451 static function replaceUnusualEscapes( $url ) {
1452 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1453 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1457 * Callback function used in replaceUnusualEscapes().
1458 * Replaces unusual URL escape codes with their equivalent character
1462 private static function replaceUnusualEscapesCallback( $matches ) {
1463 $char = urldecode( $matches[0] );
1464 $ord = ord( $char );
1465 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1466 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1467 // No, shouldn't be escaped
1470 // Yes, leave it escaped
1476 * make an image if it's allowed, either through the global
1477 * option or through the exception
1480 function maybeMakeExternalImage( $url ) {
1481 $sk = $this->mOptions
->getSkin();
1482 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1483 $imagesexception = !empty($imagesfrom);
1485 if ( $this->mOptions
->getAllowExternalImages()
1486 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1487 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1489 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1496 * Process [[ ]] wikilinks
1500 function replaceInternalLinks( $s ) {
1502 static $fname = 'Parser::replaceInternalLinks' ;
1504 wfProfileIn( $fname );
1506 wfProfileIn( $fname.'-setup' );
1508 # the % is needed to support urlencoded titles as well
1509 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1511 $sk = $this->mOptions
->getSkin();
1513 #split the entire text string on occurences of [[
1514 $a = explode( '[[', ' ' . $s );
1515 #get the first element (all text up to first [[), and remove the space we added
1516 $s = array_shift( $a );
1517 $s = substr( $s, 1 );
1519 # Match a link having the form [[namespace:link|alternate]]trail
1521 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1522 # Match cases where there is no "]]", which might still be images
1523 static $e1_img = FALSE;
1524 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1525 # Match the end of a line for a word that's not followed by whitespace,
1526 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1527 $e2 = wfMsgForContent( 'linkprefix' );
1529 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1530 if( is_null( $this->mTitle
) ) {
1531 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1533 $nottalk = !$this->mTitle
->isTalkPage();
1535 if ( $useLinkPrefixExtension ) {
1537 if ( preg_match( $e2, $s, $m ) ) {
1538 $first_prefix = $m[2];
1540 $first_prefix = false;
1546 if($wgContLang->hasVariants()) {
1547 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1549 $selflink = array($this->mTitle
->getPrefixedText());
1551 $useSubpages = $this->areSubpagesAllowed();
1552 wfProfileOut( $fname.'-setup' );
1554 # Loop for each link
1555 for ($k = 0; isset( $a[$k] ); $k++
) {
1557 if ( $useLinkPrefixExtension ) {
1558 wfProfileIn( $fname.'-prefixhandling' );
1559 if ( preg_match( $e2, $s, $m ) ) {
1567 $prefix = $first_prefix;
1568 $first_prefix = false;
1570 wfProfileOut( $fname.'-prefixhandling' );
1573 $might_be_img = false;
1575 wfProfileIn( "$fname-e1" );
1576 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1578 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1579 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1580 # the real problem is with the $e1 regex
1583 # Still some problems for cases where the ] is meant to be outside punctuation,
1584 # and no image is in sight. See bug 2095.
1587 substr( $m[3], 0, 1 ) === ']' &&
1588 strpos($text, '[') !== false
1591 $text .= ']'; # so that replaceExternalLinks($text) works later
1592 $m[3] = substr( $m[3], 1 );
1594 # fix up urlencoded title texts
1595 if( strpos( $m[1], '%' ) !== false ) {
1596 # Should anchors '#' also be rejected?
1597 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1600 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1601 $might_be_img = true;
1603 if ( strpos( $m[1], '%' ) !== false ) {
1604 $m[1] = urldecode($m[1]);
1607 } else { # Invalid form; output directly
1608 $s .= $prefix . '[[' . $line ;
1609 wfProfileOut( "$fname-e1" );
1612 wfProfileOut( "$fname-e1" );
1613 wfProfileIn( "$fname-misc" );
1615 # Don't allow internal links to pages containing
1616 # PROTO: where PROTO is a valid URL protocol; these
1617 # should be external links.
1618 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1619 $s .= $prefix . '[[' . $line ;
1623 # Make subpage if necessary
1624 if( $useSubpages ) {
1625 $link = $this->maybeDoSubpageLink( $m[1], $text );
1630 $noforce = (substr($m[1], 0, 1) != ':');
1632 # Strip off leading ':'
1633 $link = substr($link, 1);
1636 wfProfileOut( "$fname-misc" );
1637 wfProfileIn( "$fname-title" );
1638 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1640 $s .= $prefix . '[[' . $line;
1641 wfProfileOut( "$fname-title" );
1645 $ns = $nt->getNamespace();
1646 $iw = $nt->getInterWiki();
1647 wfProfileOut( "$fname-title" );
1649 if ($might_be_img) { # if this is actually an invalid link
1650 wfProfileIn( "$fname-might_be_img" );
1651 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1653 while (isset ($a[$k+
1]) ) {
1654 #look at the next 'line' to see if we can close it there
1655 $spliced = array_splice( $a, $k +
1, 1 );
1656 $next_line = array_shift( $spliced );
1657 $m = explode( ']]', $next_line, 3 );
1658 if ( count( $m ) == 3 ) {
1659 # the first ]] closes the inner link, the second the image
1661 $text .= "[[{$m[0]}]]{$m[1]}";
1664 } elseif ( count( $m ) == 2 ) {
1665 #if there's exactly one ]] that's fine, we'll keep looking
1666 $text .= "[[{$m[0]}]]{$m[1]}";
1668 #if $next_line is invalid too, we need look no further
1669 $text .= '[[' . $next_line;
1674 # we couldn't find the end of this imageLink, so output it raw
1675 #but don't ignore what might be perfectly normal links in the text we've examined
1676 $text = $this->replaceInternalLinks($text);
1677 $s .= "{$prefix}[[$link|$text";
1678 # note: no $trail, because without an end, there *is* no trail
1679 wfProfileOut( "$fname-might_be_img" );
1682 } else { #it's not an image, so output it raw
1683 $s .= "{$prefix}[[$link|$text";
1684 # note: no $trail, because without an end, there *is* no trail
1685 wfProfileOut( "$fname-might_be_img" );
1688 wfProfileOut( "$fname-might_be_img" );
1691 $wasblank = ( '' == $text );
1692 if( $wasblank ) $text = $link;
1694 # Link not escaped by : , create the various objects
1698 wfProfileIn( "$fname-interwiki" );
1699 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1700 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1701 $s = rtrim($s . $prefix);
1702 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1703 wfProfileOut( "$fname-interwiki" );
1706 wfProfileOut( "$fname-interwiki" );
1708 if ( $ns == NS_IMAGE
) {
1709 wfProfileIn( "$fname-image" );
1710 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1711 # recursively parse links inside the image caption
1712 # actually, this will parse them in any other parameters, too,
1713 # but it might be hard to fix that, and it doesn't matter ATM
1714 $text = $this->replaceExternalLinks($text);
1715 $text = $this->replaceInternalLinks($text);
1717 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1718 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1719 $this->mOutput
->addImage( $nt->getDBkey() );
1721 wfProfileOut( "$fname-image" );
1724 # We still need to record the image's presence on the page
1725 $this->mOutput
->addImage( $nt->getDBkey() );
1727 wfProfileOut( "$fname-image" );
1731 if ( $ns == NS_CATEGORY
) {
1732 wfProfileIn( "$fname-category" );
1733 $s = rtrim($s . "\n"); # bug 87
1736 $sortkey = $this->getDefaultSort();
1740 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1741 $sortkey = str_replace( "\n", '', $sortkey );
1742 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1743 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1746 * Strip the whitespace Category links produce, see bug 87
1747 * @todo We might want to use trim($tmp, "\n") here.
1749 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1751 wfProfileOut( "$fname-category" );
1756 # Self-link checking
1757 if( $nt->getFragment() === '' ) {
1758 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1759 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1764 # Special and Media are pseudo-namespaces; no pages actually exist in them
1765 if( $ns == NS_MEDIA
) {
1766 $link = $sk->makeMediaLinkObj( $nt, $text );
1767 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1768 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1771 } elseif( $ns == NS_SPECIAL
) {
1772 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1773 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1775 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1778 } elseif( $ns == NS_IMAGE
) {
1779 $img = wfFindFile( $nt );
1781 // Force a blue link if the file exists; may be a remote
1782 // upload on the shared repository, and we want to see its
1783 // auto-generated page.
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1785 $this->mOutput
->addLink( $nt );
1789 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1791 wfProfileOut( $fname );
1796 * Make a link placeholder. The text returned can be later resolved to a real link with
1797 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1798 * parsing of interwiki links, and secondly to allow all existence checks and
1799 * article length checks (for stub links) to be bundled into a single query.
1802 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1803 wfProfileIn( __METHOD__
);
1804 if ( ! is_object($nt) ) {
1806 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1808 # Separate the link trail from the rest of the link
1809 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1811 if ( $nt->isExternal() ) {
1812 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1813 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1814 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1816 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1817 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1818 $this->mLinkHolders
['queries'][] = $query;
1819 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1820 $this->mLinkHolders
['titles'][] = $nt;
1822 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1825 wfProfileOut( __METHOD__
);
1830 * Render a forced-blue link inline; protect against double expansion of
1831 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1832 * Since this little disaster has to split off the trail text to avoid
1833 * breaking URLs in the following text without breaking trails on the
1834 * wiki links, it's been made into a horrible function.
1837 * @param string $text
1838 * @param string $query
1839 * @param string $trail
1840 * @param string $prefix
1841 * @return string HTML-wikitext mix oh yuck
1843 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1844 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1845 $sk = $this->mOptions
->getSkin();
1846 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1847 return $this->armorLinks( $link ) . $trail;
1851 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1852 * going to go through further parsing steps before inline URL expansion.
1854 * In particular this is important when using action=render, which causes
1855 * full URLs to be included.
1857 * Oh man I hate our multi-layer parser!
1859 * @param string more-or-less HTML
1860 * @return string less-or-more HTML with NOPARSE bits
1862 function armorLinks( $text ) {
1863 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1864 "{$this->mUniqPrefix}NOPARSE$1", $text );
1868 * Return true if subpage links should be expanded on this page.
1871 function areSubpagesAllowed() {
1872 # Some namespaces don't allow subpages
1873 global $wgNamespacesWithSubpages;
1874 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1878 * Handle link to subpage if necessary
1879 * @param string $target the source of the link
1880 * @param string &$text the link text, modified as necessary
1881 * @return string the full name of the link
1884 function maybeDoSubpageLink($target, &$text) {
1887 # :Foobar -- override special treatment of prefix (images, language links)
1888 # /Foobar -- convert to CurrentPage/Foobar
1889 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1890 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1891 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1893 $fname = 'Parser::maybeDoSubpageLink';
1894 wfProfileIn( $fname );
1895 $ret = $target; # default return value is no change
1897 # Some namespaces don't allow subpages,
1898 # so only perform processing if subpages are allowed
1899 if( $this->areSubpagesAllowed() ) {
1900 $hash = strpos( $target, '#' );
1901 if( $hash !== false ) {
1902 $suffix = substr( $target, $hash );
1903 $target = substr( $target, 0, $hash );
1908 $target = trim( $target );
1909 # Look at the first character
1910 if( $target != '' && $target{0} == '/' ) {
1911 # / at end means we don't want the slash to be shown
1913 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1914 if( $trailingSlashes ) {
1915 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1917 $noslash = substr( $target, 1 );
1920 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1921 if( '' === $text ) {
1922 $text = $target . $suffix;
1923 } # this might be changed for ugliness reasons
1925 # check for .. subpage backlinks
1927 $nodotdot = $target;
1928 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1930 $nodotdot = substr( $nodotdot, 3 );
1932 if($dotdotcount > 0) {
1933 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1934 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1935 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1936 # / at the end means don't show full path
1937 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1938 $nodotdot = substr( $nodotdot, 0, -1 );
1939 if( '' === $text ) {
1940 $text = $nodotdot . $suffix;
1943 $nodotdot = trim( $nodotdot );
1944 if( $nodotdot != '' ) {
1945 $ret .= '/' . $nodotdot;
1953 wfProfileOut( $fname );
1958 * Used by doBlockLevels()
1961 /* private */ function closeParagraph() {
1963 if ( '' != $this->mLastSection
) {
1964 $result = '</' . $this->mLastSection
. ">\n";
1966 $this->mInPre
= false;
1967 $this->mLastSection
= '';
1970 # getCommon() returns the length of the longest common substring
1971 # of both arguments, starting at the beginning of both.
1973 /* private */ function getCommon( $st1, $st2 ) {
1974 $fl = strlen( $st1 );
1975 $shorter = strlen( $st2 );
1976 if ( $fl < $shorter ) { $shorter = $fl; }
1978 for ( $i = 0; $i < $shorter; ++
$i ) {
1979 if ( $st1{$i} != $st2{$i} ) { break; }
1983 # These next three functions open, continue, and close the list
1984 # element appropriate to the prefix character passed into them.
1986 /* private */ function openList( $char ) {
1987 $result = $this->closeParagraph();
1989 if ( '*' == $char ) { $result .= '<ul><li>'; }
1990 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1991 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1992 else if ( ';' == $char ) {
1993 $result .= '<dl><dt>';
1994 $this->mDTopen
= true;
1996 else { $result = '<!-- ERR 1 -->'; }
2001 /* private */ function nextItem( $char ) {
2002 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2003 else if ( ':' == $char ||
';' == $char ) {
2005 if ( $this->mDTopen
) { $close = '</dt>'; }
2006 if ( ';' == $char ) {
2007 $this->mDTopen
= true;
2008 return $close . '<dt>';
2010 $this->mDTopen
= false;
2011 return $close . '<dd>';
2014 return '<!-- ERR 2 -->';
2017 /* private */ function closeList( $char ) {
2018 if ( '*' == $char ) { $text = '</li></ul>'; }
2019 else if ( '#' == $char ) { $text = '</li></ol>'; }
2020 else if ( ':' == $char ) {
2021 if ( $this->mDTopen
) {
2022 $this->mDTopen
= false;
2023 $text = '</dt></dl>';
2025 $text = '</dd></dl>';
2028 else { return '<!-- ERR 3 -->'; }
2034 * Make lists from lines starting with ':', '*', '#', etc.
2037 * @return string the lists rendered as HTML
2039 function doBlockLevels( $text, $linestart ) {
2040 $fname = 'Parser::doBlockLevels';
2041 wfProfileIn( $fname );
2043 # Parsing through the text line by line. The main thing
2044 # happening here is handling of block-level elements p, pre,
2045 # and making lists from lines starting with * # : etc.
2047 $textLines = explode( "\n", $text );
2049 $lastPrefix = $output = '';
2050 $this->mDTopen
= $inBlockElem = false;
2052 $paragraphStack = false;
2054 if ( !$linestart ) {
2055 $output .= array_shift( $textLines );
2057 foreach ( $textLines as $oLine ) {
2058 $lastPrefixLength = strlen( $lastPrefix );
2059 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2060 $preOpenMatch = preg_match('/<pre/i', $oLine );
2061 if ( !$this->mInPre
) {
2062 # Multiple prefixes may abut each other for nested lists.
2063 $prefixLength = strspn( $oLine, '*#:;' );
2064 $pref = substr( $oLine, 0, $prefixLength );
2067 $pref2 = str_replace( ';', ':', $pref );
2068 $t = substr( $oLine, $prefixLength );
2069 $this->mInPre
= !empty($preOpenMatch);
2071 # Don't interpret any other prefixes in preformatted text
2073 $pref = $pref2 = '';
2078 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2079 # Same as the last item, so no need to deal with nesting or opening stuff
2080 $output .= $this->nextItem( substr( $pref, -1 ) );
2081 $paragraphStack = false;
2083 if ( substr( $pref, -1 ) == ';') {
2084 # The one nasty exception: definition lists work like this:
2085 # ; title : definition text
2086 # So we check for : in the remainder text to split up the
2087 # title and definition, without b0rking links.
2089 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2091 $output .= $term . $this->nextItem( ':' );
2094 } elseif( $prefixLength ||
$lastPrefixLength ) {
2095 # Either open or close a level...
2096 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2097 $paragraphStack = false;
2099 while( $commonPrefixLength < $lastPrefixLength ) {
2100 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2101 --$lastPrefixLength;
2103 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2104 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2106 while ( $prefixLength > $commonPrefixLength ) {
2107 $char = substr( $pref, $commonPrefixLength, 1 );
2108 $output .= $this->openList( $char );
2110 if ( ';' == $char ) {
2111 # FIXME: This is dupe of code above
2112 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2114 $output .= $term . $this->nextItem( ':' );
2117 ++
$commonPrefixLength;
2119 $lastPrefix = $pref2;
2121 if( 0 == $prefixLength ) {
2122 wfProfileIn( "$fname-paragraph" );
2123 # No prefix (not in list)--go to paragraph mode
2124 // XXX: use a stack for nestable elements like span, table and div
2125 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2126 $closematch = preg_match(
2127 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2128 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2129 if ( $openmatch or $closematch ) {
2130 $paragraphStack = false;
2131 #Â TODO bug 5718: paragraph closed
2132 $output .= $this->closeParagraph();
2133 if ( $preOpenMatch and !$preCloseMatch ) {
2134 $this->mInPre
= true;
2136 if ( $closematch ) {
2137 $inBlockElem = false;
2139 $inBlockElem = true;
2141 } else if ( !$inBlockElem && !$this->mInPre
) {
2142 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2144 if ($this->mLastSection
!= 'pre') {
2145 $paragraphStack = false;
2146 $output .= $this->closeParagraph().'<pre>';
2147 $this->mLastSection
= 'pre';
2149 $t = substr( $t, 1 );
2152 if ( '' == trim($t) ) {
2153 if ( $paragraphStack ) {
2154 $output .= $paragraphStack.'<br />';
2155 $paragraphStack = false;
2156 $this->mLastSection
= 'p';
2158 if ($this->mLastSection
!= 'p' ) {
2159 $output .= $this->closeParagraph();
2160 $this->mLastSection
= '';
2161 $paragraphStack = '<p>';
2163 $paragraphStack = '</p><p>';
2167 if ( $paragraphStack ) {
2168 $output .= $paragraphStack;
2169 $paragraphStack = false;
2170 $this->mLastSection
= 'p';
2171 } else if ($this->mLastSection
!= 'p') {
2172 $output .= $this->closeParagraph().'<p>';
2173 $this->mLastSection
= 'p';
2178 wfProfileOut( "$fname-paragraph" );
2180 // somewhere above we forget to get out of pre block (bug 785)
2181 if($preCloseMatch && $this->mInPre
) {
2182 $this->mInPre
= false;
2184 if ($paragraphStack === false) {
2188 while ( $prefixLength ) {
2189 $output .= $this->closeList( $pref2{$prefixLength-1} );
2192 if ( '' != $this->mLastSection
) {
2193 $output .= '</' . $this->mLastSection
. '>';
2194 $this->mLastSection
= '';
2197 wfProfileOut( $fname );
2202 * Split up a string on ':', ignoring any occurences inside tags
2203 * to prevent illegal overlapping.
2204 * @param string $str the string to split
2205 * @param string &$before set to everything before the ':'
2206 * @param string &$after set to everything after the ':'
2207 * return string the position of the ':', or false if none found
2209 function findColonNoLinks($str, &$before, &$after) {
2210 $fname = 'Parser::findColonNoLinks';
2211 wfProfileIn( $fname );
2213 $pos = strpos( $str, ':' );
2214 if( $pos === false ) {
2216 wfProfileOut( $fname );
2220 $lt = strpos( $str, '<' );
2221 if( $lt === false ||
$lt > $pos ) {
2222 // Easy; no tag nesting to worry about
2223 $before = substr( $str, 0, $pos );
2224 $after = substr( $str, $pos+
1 );
2225 wfProfileOut( $fname );
2229 // Ugly state machine to walk through avoiding tags.
2230 $state = self
::COLON_STATE_TEXT
;
2232 $len = strlen( $str );
2233 for( $i = 0; $i < $len; $i++
) {
2237 // (Using the number is a performance hack for common cases)
2238 case 0: // self::COLON_STATE_TEXT:
2241 // Could be either a <start> tag or an </end> tag
2242 $state = self
::COLON_STATE_TAGSTART
;
2247 $before = substr( $str, 0, $i );
2248 $after = substr( $str, $i +
1 );
2249 wfProfileOut( $fname );
2252 // Embedded in a tag; don't break it.
2255 // Skip ahead looking for something interesting
2256 $colon = strpos( $str, ':', $i );
2257 if( $colon === false ) {
2258 // Nothing else interesting
2259 wfProfileOut( $fname );
2262 $lt = strpos( $str, '<', $i );
2263 if( $stack === 0 ) {
2264 if( $lt === false ||
$colon < $lt ) {
2266 $before = substr( $str, 0, $colon );
2267 $after = substr( $str, $colon +
1 );
2268 wfProfileOut( $fname );
2272 if( $lt === false ) {
2273 // Nothing else interesting to find; abort!
2274 // We're nested, but there's no close tags left. Abort!
2277 // Skip ahead to next tag start
2279 $state = self
::COLON_STATE_TAGSTART
;
2282 case 1: // self::COLON_STATE_TAG:
2287 $state = self
::COLON_STATE_TEXT
;
2290 // Slash may be followed by >?
2291 $state = self
::COLON_STATE_TAGSLASH
;
2297 case 2: // self::COLON_STATE_TAGSTART:
2300 $state = self
::COLON_STATE_CLOSETAG
;
2303 $state = self
::COLON_STATE_COMMENT
;
2306 // Illegal early close? This shouldn't happen D:
2307 $state = self
::COLON_STATE_TEXT
;
2310 $state = self
::COLON_STATE_TAG
;
2313 case 3: // self::COLON_STATE_CLOSETAG:
2318 wfDebug( "Invalid input in $fname; too many close tags\n" );
2319 wfProfileOut( $fname );
2322 $state = self
::COLON_STATE_TEXT
;
2325 case self
::COLON_STATE_TAGSLASH
:
2327 // Yes, a self-closed tag <blah/>
2328 $state = self
::COLON_STATE_TEXT
;
2330 // Probably we're jumping the gun, and this is an attribute
2331 $state = self
::COLON_STATE_TAG
;
2334 case 5: // self::COLON_STATE_COMMENT:
2336 $state = self
::COLON_STATE_COMMENTDASH
;
2339 case self
::COLON_STATE_COMMENTDASH
:
2341 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2343 $state = self
::COLON_STATE_COMMENT
;
2346 case self
::COLON_STATE_COMMENTDASHDASH
:
2348 $state = self
::COLON_STATE_TEXT
;
2350 $state = self
::COLON_STATE_COMMENT
;
2354 throw new MWException( "State machine error in $fname" );
2358 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2361 wfProfileOut( $fname );
2366 * Return value of a magic variable (like PAGENAME)
2370 function getVariableValue( $index ) {
2371 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2374 * Some of these require message or data lookups and can be
2375 * expensive to check many times.
2377 static $varCache = array();
2378 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2379 if ( isset( $varCache[$index] ) ) {
2380 return $varCache[$index];
2385 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2388 global $wgLocaltimezone;
2389 if ( isset( $wgLocaltimezone ) ) {
2390 $oldtz = getenv( 'TZ' );
2391 putenv( 'TZ='.$wgLocaltimezone );
2394 wfSuppressWarnings(); // E_STRICT system time bitching
2395 $localTimestamp = date( 'YmdHis', $ts );
2396 $localMonth = date( 'm', $ts );
2397 $localMonthName = date( 'n', $ts );
2398 $localDay = date( 'j', $ts );
2399 $localDay2 = date( 'd', $ts );
2400 $localDayOfWeek = date( 'w', $ts );
2401 $localWeek = date( 'W', $ts );
2402 $localYear = date( 'Y', $ts );
2403 $localHour = date( 'H', $ts );
2404 if ( isset( $wgLocaltimezone ) ) {
2405 putenv( 'TZ='.$oldtz );
2407 wfRestoreWarnings();
2410 case 'currentmonth':
2411 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2412 case 'currentmonthname':
2413 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2414 case 'currentmonthnamegen':
2415 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2416 case 'currentmonthabbrev':
2417 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2419 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2421 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2423 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2424 case 'localmonthname':
2425 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2426 case 'localmonthnamegen':
2427 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2428 case 'localmonthabbrev':
2429 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2431 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2433 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2435 return wfEscapeWikiText( $this->mTitle
->getText() );
2437 return $this->mTitle
->getPartialURL();
2438 case 'fullpagename':
2439 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2440 case 'fullpagenamee':
2441 return $this->mTitle
->getPrefixedURL();
2443 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2444 case 'subpagenamee':
2445 return $this->mTitle
->getSubpageUrlForm();
2446 case 'basepagename':
2447 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2448 case 'basepagenamee':
2449 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2450 case 'talkpagename':
2451 if( $this->mTitle
->canTalk() ) {
2452 $talkPage = $this->mTitle
->getTalkPage();
2453 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2457 case 'talkpagenamee':
2458 if( $this->mTitle
->canTalk() ) {
2459 $talkPage = $this->mTitle
->getTalkPage();
2460 return $talkPage->getPrefixedUrl();
2464 case 'subjectpagename':
2465 $subjPage = $this->mTitle
->getSubjectPage();
2466 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2467 case 'subjectpagenamee':
2468 $subjPage = $this->mTitle
->getSubjectPage();
2469 return $subjPage->getPrefixedUrl();
2471 return $this->mRevisionId
;
2473 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2474 case 'revisionday2':
2475 return substr( $this->getRevisionTimestamp(), 6, 2 );
2476 case 'revisionmonth':
2477 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2478 case 'revisionyear':
2479 return substr( $this->getRevisionTimestamp(), 0, 4 );
2480 case 'revisiontimestamp':
2481 return $this->getRevisionTimestamp();
2483 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2485 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2487 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2489 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2490 case 'subjectspace':
2491 return $this->mTitle
->getSubjectNsText();
2492 case 'subjectspacee':
2493 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2494 case 'currentdayname':
2495 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2497 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2499 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2501 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2503 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2504 // int to remove the padding
2505 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2507 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2508 case 'localdayname':
2509 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2511 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2513 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2515 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2517 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2518 // int to remove the padding
2519 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2521 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2522 case 'numberofarticles':
2523 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2524 case 'numberoffiles':
2525 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2526 case 'numberofusers':
2527 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2528 case 'numberofpages':
2529 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2530 case 'numberofadmins':
2531 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2532 case 'numberofedits':
2533 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2534 case 'currenttimestamp':
2535 return $varCache[$index] = wfTimestampNow();
2536 case 'localtimestamp':
2537 return $varCache[$index] = $localTimestamp;
2538 case 'currentversion':
2539 return $varCache[$index] = SpecialVersion
::getVersion();
2545 return $wgServerName;
2547 return $wgScriptPath;
2548 case 'directionmark':
2549 return $wgContLang->getDirMark();
2550 case 'contentlanguage':
2551 global $wgContLanguageCode;
2552 return $wgContLanguageCode;
2555 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2563 * initialise the magic variables (like CURRENTMONTHNAME)
2567 function initialiseVariables() {
2568 $fname = 'Parser::initialiseVariables';
2569 wfProfileIn( $fname );
2570 $variableIDs = MagicWord
::getVariableIDs();
2572 $this->mVariables
= array();
2573 foreach ( $variableIDs as $id ) {
2574 $mw =& MagicWord
::get( $id );
2575 $mw->addToArray( $this->mVariables
, $id );
2577 wfProfileOut( $fname );
2581 * parse any parentheses in format ((title|part|part))
2582 * and call callbacks to get a replacement text for any found piece
2584 * @param string $text The text to parse
2585 * @param array $callbacks rules in form:
2586 * '{' => array( # opening parentheses
2587 * 'end' => '}', # closing parentheses
2588 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2589 * 3 => callback # replacement callback to call if {{{..}}} is found
2592 * 'min' => 2, # Minimum parenthesis count in cb
2593 * 'max' => 3, # Maximum parenthesis count in cb
2596 function replace_callback ($text, $callbacks) {
2597 wfProfileIn( __METHOD__
);
2598 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2599 $lastOpeningBrace = -1; # last not closed parentheses
2601 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2604 while ( $i < strlen( $text ) ) {
2605 # Find next opening brace, closing brace or pipe
2606 if ( $lastOpeningBrace == -1 ) {
2607 $currentClosing = '';
2608 $search = $validOpeningBraces;
2610 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2611 $search = $validOpeningBraces . '|' . $currentClosing;
2614 $i +
= strcspn( $text, $search, $i );
2615 if ( $i < strlen( $text ) ) {
2616 if ( $text[$i] == '|' ) {
2618 } elseif ( $text[$i] == $currentClosing ) {
2620 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2622 $rule = $callbacks[$text[$i]];
2624 # Some versions of PHP have a strcspn which stops on null characters
2625 # Ignore and continue
2634 if ( $found == 'open' ) {
2635 # found opening brace, let's add it to parentheses stack
2636 $piece = array('brace' => $text[$i],
2637 'braceEnd' => $rule['end'],
2641 # count opening brace characters
2642 $piece['count'] = strspn( $text, $piece['brace'], $i );
2643 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2644 $i +
= $piece['count'];
2646 # we need to add to stack only if opening brace count is enough for one of the rules
2647 if ( $piece['count'] >= $rule['min'] ) {
2648 $lastOpeningBrace ++
;
2649 $openingBraceStack[$lastOpeningBrace] = $piece;
2651 } elseif ( $found == 'close' ) {
2652 # lets check if it is enough characters for closing brace
2653 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2654 $count = strspn( $text, $text[$i], $i, $maxCount );
2656 # check for maximum matching characters (if there are 5 closing
2657 # characters, we will probably need only 3 - depending on the rules)
2659 $matchingCallback = null;
2660 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2661 if ( $count > $cbType['max'] ) {
2662 # The specified maximum exists in the callback array, unless the caller
2664 $matchingCount = $cbType['max'];
2666 # Count is less than the maximum
2667 # Skip any gaps in the callback array to find the true largest match
2668 # Need to use array_key_exists not isset because the callback can be null
2669 $matchingCount = $count;
2670 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2675 if ($matchingCount <= 0) {
2679 $matchingCallback = $cbType['cb'][$matchingCount];
2681 # let's set a title or last part (if '|' was found)
2682 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2683 $openingBraceStack[$lastOpeningBrace]['title'] =
2684 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2685 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2687 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2688 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2689 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2692 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2693 $pieceEnd = $i +
$matchingCount;
2695 if( is_callable( $matchingCallback ) ) {
2697 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2698 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2699 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2700 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2702 # finally we can call a user callback and replace piece of text
2703 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2704 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2705 $i = $pieceStart +
strlen($replaceWith);
2707 # null value for callback means that parentheses should be parsed, but not replaced
2708 $i +
= $matchingCount;
2711 # reset last opening parentheses, but keep it in case there are unused characters
2712 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2713 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2714 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2717 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2718 $openingBraceStack[$lastOpeningBrace--] = null;
2720 if ($matchingCount < $piece['count']) {
2721 $piece['count'] -= $matchingCount;
2722 $piece['startAt'] -= $matchingCount;
2723 $piece['partStart'] = $piece['startAt'];
2724 # do we still qualify for any callback with remaining count?
2725 $currentCbList = $callbacks[$piece['brace']]['cb'];
2726 while ( $piece['count'] ) {
2727 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2728 $lastOpeningBrace++
;
2729 $openingBraceStack[$lastOpeningBrace] = $piece;
2735 } elseif ( $found == 'pipe' ) {
2736 # lets set a title if it is a first separator, or next part otherwise
2737 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2738 $openingBraceStack[$lastOpeningBrace]['title'] =
2739 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2740 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2741 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2743 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2744 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2745 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2751 wfProfileOut( __METHOD__
);
2756 * Replace magic variables, templates, and template arguments
2757 * with the appropriate text. Templates are substituted recursively,
2758 * taking care to avoid infinite loops.
2760 * Note that the substitution depends on value of $mOutputType:
2761 * OT_WIKI: only {{subst:}} templates
2762 * OT_MSG: only magic variables
2763 * OT_HTML: all templates and magic variables
2765 * @param string $tex The text to transform
2766 * @param array $args Key-value pairs representing template parameters to substitute
2767 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2770 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2771 # Prevent too big inclusions
2772 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2776 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2777 wfProfileIn( $fname );
2779 # This function is called recursively. To keep track of arguments we need a stack:
2780 array_push( $this->mArgStack
, $args );
2782 $braceCallbacks = array();
2784 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2786 if ( $this->mOutputType
!= OT_MSG
) {
2787 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2789 if ( $braceCallbacks ) {
2793 'cb' => $braceCallbacks,
2794 'min' => $argsOnly ?
3 : 2,
2795 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2799 'cb' => array(2=>null),
2804 $text = $this->replace_callback ($text, $callbacks);
2806 array_pop( $this->mArgStack
);
2808 wfProfileOut( $fname );
2813 * Replace magic variables
2816 function variableSubstitution( $matches ) {
2818 $fname = 'Parser::variableSubstitution';
2819 $varname = $wgContLang->lc($matches[1]);
2820 wfProfileIn( $fname );
2822 if ( $this->mOutputType
== OT_WIKI
) {
2823 # Do only magic variables prefixed by SUBST
2824 $mwSubst =& MagicWord
::get( 'subst' );
2825 if (!$mwSubst->matchStartAndRemove( $varname ))
2827 # Note that if we don't substitute the variable below,
2828 # we don't remove the {{subst:}} magic word, in case
2829 # it is a template rather than a magic variable.
2831 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2832 $id = $this->mVariables
[$varname];
2833 # Now check if we did really match, case sensitive or not
2834 $mw =& MagicWord
::get( $id );
2835 if ($mw->match($matches[1])) {
2836 $text = $this->getVariableValue( $id );
2837 if (MagicWord
::getCacheTTL($id)>-1)
2838 $this->mOutput
->mContainsOldMagic
= true;
2840 $text = $matches[0];
2843 $text = $matches[0];
2845 wfProfileOut( $fname );
2850 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2851 static function createAssocArgs( $args ) {
2852 $assocArgs = array();
2854 foreach( $args as $arg ) {
2855 $eqpos = strpos( $arg, '=' );
2856 if ( $eqpos === false ) {
2857 $assocArgs[$index++
] = $arg;
2859 $name = trim( substr( $arg, 0, $eqpos ) );
2860 $value = trim( substr( $arg, $eqpos+
1 ) );
2861 if ( $value === false ) {
2864 if ( $name !== false ) {
2865 $assocArgs[$name] = $value;
2874 * Return the text of a template, after recursively
2875 * replacing any variables or templates within the template.
2877 * @param array $piece The parts of the template
2878 * $piece['text']: matched text
2879 * $piece['title']: the title, i.e. the part before the |
2880 * $piece['parts']: the parameter array
2881 * @return string the text of the template
2884 function braceSubstitution( $piece ) {
2885 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2886 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2887 wfProfileIn( $fname );
2888 wfProfileIn( __METHOD__
.'-setup' );
2891 $found = false; # $text has been filled
2892 $nowiki = false; # wiki markup in $text should be escaped
2893 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2894 $noargs = false; # Don't replace triple-brace arguments in $text
2895 $replaceHeadings = false; # Make the edit section links go to the template not the article
2896 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2897 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2898 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2900 # Title object, where $text came from
2906 # $part1 is the bit before the first |, and must contain only title characters
2907 # $args is a list of arguments, starting from index 0, not including $part1
2909 $titleText = $part1 = $piece['title'];
2910 # If the third subpattern matched anything, it will start with |
2912 if (null == $piece['parts']) {
2913 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2914 if ($replaceWith != $piece['text']) {
2915 $text = $replaceWith;
2922 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2923 wfProfileOut( __METHOD__
.'-setup' );
2926 wfProfileIn( __METHOD__
.'-modifiers' );
2928 $mwSubst =& MagicWord
::get( 'subst' );
2929 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2930 # One of two possibilities is true:
2931 # 1) Found SUBST but not in the PST phase
2932 # 2) Didn't find SUBST and in the PST phase
2933 # In either case, return without further processing
2934 $text = $piece['text'];
2941 # MSG, MSGNW and RAW
2944 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2945 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2948 # Remove obsolete MSG:
2949 $mwMsg =& MagicWord
::get( 'msg' );
2950 $mwMsg->matchStartAndRemove( $part1 );
2954 $mwRaw =& MagicWord
::get( 'raw' );
2955 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2956 $forceRawInterwiki = true;
2959 wfProfileOut( __METHOD__
.'-modifiers' );
2961 //save path level before recursing into functions & templates.
2962 $lastPathLevel = $this->mTemplatePath
;
2966 wfProfileIn( __METHOD__
. '-pfunc' );
2968 $colonPos = strpos( $part1, ':' );
2969 if ( $colonPos !== false ) {
2970 # Case sensitive functions
2971 $function = substr( $part1, 0, $colonPos );
2972 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2973 $function = $this->mFunctionSynonyms
[1][$function];
2975 # Case insensitive functions
2976 $function = strtolower( $function );
2977 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2978 $function = $this->mFunctionSynonyms
[0][$function];
2984 $funcArgs = array_map( 'trim', $args );
2985 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2986 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2989 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2993 if ( is_array( $result ) ) {
2994 if ( isset( $result[0] ) ) {
2995 $text = $linestart . $result[0];
2996 unset( $result[0] );
2999 // Extract flags into the local scope
3000 // This allows callers to set flags such as nowiki, noparse, found, etc.
3003 $text = $linestart . $result;
3007 wfProfileOut( __METHOD__
. '-pfunc' );
3010 # Template table test
3012 # Did we encounter this template already? If yes, it is in the cache
3013 # and we need to check for loops.
3014 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3017 # Infinite loop test
3018 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3022 $text = $linestart .
3023 "[[$part1]]<!-- WARNING: template loop detected -->";
3024 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3026 # set $text to cached message.
3027 $text = $linestart . $this->mTemplates
[$piece['title']];
3028 #treat title for cached page the same as others
3031 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3032 if ($subpage !== '') {
3033 $ns = $this->mTitle
->getNamespace();
3035 $title = Title
::newFromText( $part1, $ns );
3036 //used by include size checking
3037 $titleText = $title->getPrefixedText();
3038 //used by edit section links
3039 $replaceHeadings = true;
3044 # Load from database
3046 wfProfileIn( __METHOD__
. '-loadtpl' );
3048 # declaring $subpage directly in the function call
3049 # does not work correctly with references and breaks
3050 # {{/subpage}}-style inclusions
3052 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3053 if ($subpage !== '') {
3054 $ns = $this->mTitle
->getNamespace();
3056 $title = Title
::newFromText( $part1, $ns );
3059 if ( !is_null( $title ) ) {
3060 $titleText = $title->getPrefixedText();
3061 # Check for language variants if the template is not found
3062 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3063 $wgContLang->findVariantLink($part1, $title);
3066 if ( !$title->isExternal() ) {
3067 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3068 $text = SpecialPage
::capturePath( $title );
3069 if ( is_string( $text ) ) {
3074 $this->disableCache();
3076 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3077 $found = false; //access denied
3078 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3080 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3081 if ( $articleContent !== false ) {
3083 $text = $articleContent;
3084 $replaceHeadings = true;
3088 # If the title is valid but undisplayable, make a link to it
3089 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3090 $text = "[[:$titleText]]";
3093 } elseif ( $title->isTrans() ) {
3094 // Interwiki transclusion
3095 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3096 $text = $this->interwikiTransclude( $title, 'render' );
3100 $text = $this->interwikiTransclude( $title, 'raw' );
3101 $replaceHeadings = true;
3106 # Template cache array insertion
3107 # Use the original $piece['title'] not the mangled $part1, so that
3108 # modifiers such as RAW: produce separate cache entries
3111 // A special page; don't store it in the template cache.
3113 $this->mTemplates
[$piece['title']] = $text;
3115 $text = $linestart . $text;
3118 wfProfileOut( __METHOD__
. '-loadtpl' );
3121 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3122 # Error, oversize inclusion
3123 $text = $linestart .
3124 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3129 # Recursive parsing, escaping and link table handling
3130 # Only for HTML output
3131 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3132 $text = wfEscapeWikiText( $text );
3133 } elseif ( !$this->ot
['msg'] && $found ) {
3135 $assocArgs = array();
3137 # Clean up argument array
3138 $assocArgs = self
::createAssocArgs($args);
3139 # Add a new element to the templace recursion path
3140 $this->mTemplatePath
[$part1] = 1;
3144 # If there are any <onlyinclude> tags, only include them
3145 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3146 $replacer = new OnlyIncludeReplacer
;
3147 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3148 array( &$replacer, 'replace' ), $text );
3149 $text = $replacer->output
;
3151 # Remove <noinclude> sections and <includeonly> tags
3152 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3153 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3155 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3156 # Strip <nowiki>, <pre>, etc.
3157 $text = $this->strip( $text, $this->mStripState
);
3158 if ( $this->ot
['html'] ) {
3159 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3160 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3161 $text = Sanitizer
::removeHTMLcomments( $text );
3164 $text = $this->replaceVariables( $text, $assocArgs );
3166 # If the template begins with a table or block-level
3167 # element, it should be treated as beginning a new line.
3168 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3169 $text = "\n" . $text;
3171 } elseif ( !$noargs ) {
3172 # $noparse and !$noargs
3173 # Just replace the arguments, not any double-brace items
3174 # This is used for rendered interwiki transclusion
3175 $text = $this->replaceVariables( $text, $assocArgs, true );
3178 # Prune lower levels off the recursion check path
3179 $this->mTemplatePath
= $lastPathLevel;
3181 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3182 # Error, oversize inclusion
3183 $text = $linestart .
3184 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3190 wfProfileOut( $fname );
3191 return $piece['text'];
3193 wfProfileIn( __METHOD__
. '-placeholders' );
3195 # Replace raw HTML by a placeholder
3196 # Add a blank line preceding, to prevent it from mucking up
3197 # immediately preceding headings
3198 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3200 # replace ==section headers==
3201 # XXX this needs to go away once we have a better parser.
3202 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3203 if( !is_null( $title ) )
3204 $encodedname = base64_encode($title->getPrefixedDBkey());
3206 $encodedname = base64_encode("");
3207 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3208 PREG_SPLIT_DELIM_CAPTURE
);
3210 $nsec = $headingOffset;
3212 for( $i = 0; $i < count($m); $i +
= 2 ) {
3214 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3216 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3221 preg_match('/^(={1,6})(.*?)(={1,6}\s*?)$/m', $hl, $m2);
3222 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3223 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3229 wfProfileOut( __METHOD__
. '-placeholders' );
3232 # Prune lower levels off the recursion check path
3233 $this->mTemplatePath
= $lastPathLevel;
3236 wfProfileOut( $fname );
3237 return $piece['text'];
3239 wfProfileOut( $fname );
3245 * Fetch the unparsed text of a template and register a reference to it.
3247 function fetchTemplateAndTitle( $title ) {
3248 $templateCb = $this->mOptions
->getTemplateCallback();
3249 $stuff = call_user_func( $templateCb, $title );
3250 $text = $stuff['text'];
3251 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3252 if ( isset( $stuff['deps'] ) ) {
3253 foreach ( $stuff['deps'] as $dep ) {
3254 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3257 return array($text,$finalTitle);
3260 function fetchTemplate( $title ) {
3261 $rv = $this->fetchTemplateAndtitle($title);
3266 * Static function to get a template
3267 * Can be overridden via ParserOptions::setTemplateCallback().
3269 * Returns an associative array:
3270 * text The unparsed template text
3271 * finalTitle (Optional) The title after following redirects
3272 * deps (Optional) An array of associative array dependencies:
3273 * title: The dependency title, to be registered in templatelinks
3274 * page_id: The page_id of the title
3275 * rev_id: The revision ID loaded
3277 static function statelessFetchTemplate( $title ) {
3278 $text = $skip = false;
3279 $finalTitle = $title;
3282 // Loop to fetch the article, with up to 1 redirect
3283 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3284 # Give extensions a chance to select the revision instead
3285 $id = false; // Assume current
3286 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3292 'page_id' => $title->getArticleID(),
3296 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3297 $rev_id = $rev ?
$rev->getId() : 0;
3301 'page_id' => $title->getArticleID(),
3302 'rev_id' => $rev_id );
3305 $text = $rev->getText();
3306 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3308 $message = $wgLang->lcfirst( $title->getText() );
3309 $text = wfMsgForContentNoTrans( $message );
3310 if( wfEmptyMsg( $message, $text ) ) {
3317 if ( $text === false ) {
3321 $finalTitle = $title;
3322 $title = Title
::newFromRedirect( $text );
3326 'finalTitle' => $finalTitle,
3331 * Transclude an interwiki link.
3333 function interwikiTransclude( $title, $action ) {
3334 global $wgEnableScaryTranscluding;
3336 if (!$wgEnableScaryTranscluding)
3337 return wfMsg('scarytranscludedisabled');
3339 $url = $title->getFullUrl( "action=$action" );
3341 if (strlen($url) > 255)
3342 return wfMsg('scarytranscludetoolong');
3343 return $this->fetchScaryTemplateMaybeFromCache($url);
3346 function fetchScaryTemplateMaybeFromCache($url) {
3347 global $wgTranscludeCacheExpiry;
3348 $dbr = wfGetDB(DB_SLAVE
);
3349 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3350 array('tc_url' => $url));
3352 $time = $obj->tc_time
;
3353 $text = $obj->tc_contents
;
3354 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3359 $text = Http
::get($url);
3361 return wfMsg('scarytranscludefailed', $url);
3363 $dbw = wfGetDB(DB_MASTER
);
3364 $dbw->replace('transcache', array('tc_url'), array(
3366 'tc_time' => time(),
3367 'tc_contents' => $text));
3373 * Triple brace replacement -- used for template arguments
3376 function argSubstitution( $matches ) {
3377 $arg = trim( $matches['title'] );
3378 $text = $matches['text'];
3379 $inputArgs = end( $this->mArgStack
);
3381 if ( array_key_exists( $arg, $inputArgs ) ) {
3382 $text = $inputArgs[$arg];
3383 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3384 null != $matches['parts'] && count($matches['parts']) > 0) {
3385 $text = $matches['parts'][0];
3387 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3388 $text = $matches['text'] .
3389 '<!-- WARNING: argument omitted, expansion size too large -->';
3396 * Increment an include size counter
3398 * @param string $type The type of expansion
3399 * @param integer $size The size of the text
3400 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3402 function incrementIncludeSize( $type, $size ) {
3403 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3406 $this->mIncludeSizes
[$type] +
= $size;
3412 * Detect __NOGALLERY__ magic word and set a placeholder
3414 function stripNoGallery( &$text ) {
3415 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3417 $mw = MagicWord
::get( 'nogallery' );
3418 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3422 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3423 * placeholder that will then be replaced by the real TOC in
3424 * ->formatHeadings, this works because at this points real
3425 * comments will have already been discarded by the sanitizer.
3427 * Any additional __TOC__ magic words left over will be discarded
3428 * as there can only be one TOC on the page.
3430 function stripToc( $text ) {
3431 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3433 $mw = MagicWord
::get( 'notoc' );
3434 if( $mw->matchAndRemove( $text ) ) {
3435 $this->mShowToc
= false;
3438 $mw = MagicWord
::get( 'toc' );
3439 if( $mw->match( $text ) ) {
3440 $this->mShowToc
= true;
3441 $this->mForceTocPosition
= true;
3443 // Set a placeholder. At the end we'll fill it in with the TOC.
3444 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3446 // Only keep the first one.
3447 $text = $mw->replace( '', $text );
3453 * This function accomplishes several tasks:
3454 * 1) Auto-number headings if that option is enabled
3455 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3456 * 3) Add a Table of contents on the top for users who have enabled the option
3457 * 4) Auto-anchor headings
3459 * It loops through all headlines, collects the necessary data, then splits up the
3460 * string and re-inserts the newly formatted headlines.
3462 * @param string $text
3463 * @param boolean $isMain
3466 function formatHeadings( $text, $isMain=true ) {
3467 global $wgMaxTocLevel, $wgContLang;
3469 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3470 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3473 $showEditLink = $this->mOptions
->getEditSection();
3476 # Inhibit editsection links if requested in the page
3477 $esw =& MagicWord
::get( 'noeditsection' );
3478 if( $esw->matchAndRemove( $text ) ) {
3482 # Get all headlines for numbering them and adding funky stuff like [edit]
3483 # links - this is for later, but we need the number of headlines right now
3485 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3487 # if there are fewer than 4 headlines in the article, do not show TOC
3488 # unless it's been explicitly enabled.
3489 $enoughToc = $this->mShowToc
&&
3490 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3492 # Allow user to stipulate that a page should have a "new section"
3493 # link added via __NEWSECTIONLINK__
3494 $mw =& MagicWord
::get( 'newsectionlink' );
3495 if( $mw->matchAndRemove( $text ) )
3496 $this->mOutput
->setNewSection( true );
3498 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3499 # override above conditions and always show TOC above first header
3500 $mw =& MagicWord
::get( 'forcetoc' );
3501 if ($mw->matchAndRemove( $text ) ) {
3502 $this->mShowToc
= true;
3506 # We need this to perform operations on the HTML
3507 $sk = $this->mOptions
->getSkin();
3511 $sectionCount = 0; # headlineCount excluding template sections
3514 # Ugh .. the TOC should have neat indentation levels which can be
3515 # passed to the skin functions. These are determined here
3519 $sublevelCount = array();
3520 $levelCount = array();
3528 foreach( $matches[3] as $headline ) {
3530 $templatetitle = '';
3531 $templatesection = 0;
3534 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3536 $templatetitle = base64_decode($mat[1]);
3537 $templatesection = 1 +
(int)base64_decode($mat[2]);
3538 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3542 $prevlevel = $level;
3543 $prevtoclevel = $toclevel;
3545 $level = $matches[1][$headlineCount];
3547 if( $doNumberHeadings ||
$enoughToc ) {
3549 if ( $level > $prevlevel ) {
3550 # Increase TOC level
3552 $sublevelCount[$toclevel] = 0;
3553 if( $toclevel<$wgMaxTocLevel ) {
3554 $prevtoclevel = $toclevel;
3555 $toc .= $sk->tocIndent();
3559 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3560 # Decrease TOC level, find level to jump to
3562 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3563 # Can only go down to level 1
3566 for ($i = $toclevel; $i > 0; $i--) {
3567 if ( $levelCount[$i] == $level ) {
3568 # Found last matching level
3572 elseif ( $levelCount[$i] < $level ) {
3573 # Found first matching level below current level
3579 if( $toclevel<$wgMaxTocLevel ) {
3580 if($prevtoclevel < $wgMaxTocLevel) {
3581 # Unindent only if the previous toc level was shown :p
3582 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3584 $toc .= $sk->tocLineEnd();
3589 # No change in level, end TOC line
3590 if( $toclevel<$wgMaxTocLevel ) {
3591 $toc .= $sk->tocLineEnd();
3595 $levelCount[$toclevel] = $level;
3597 # count number of headlines for each level
3598 @$sublevelCount[$toclevel]++
;
3600 for( $i = 1; $i <= $toclevel; $i++
) {
3601 if( !empty( $sublevelCount[$i] ) ) {
3605 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3611 # The canonized header is a version of the header text safe to use for links
3612 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3613 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3615 # Remove link placeholders by the link text.
3616 # <!--LINK number-->
3618 # link text with suffix
3619 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3620 "\$this->mLinkHolders['texts'][\$1]",
3621 $canonized_headline );
3622 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3623 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3624 $canonized_headline );
3626 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3627 $tocline = preg_replace(
3628 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3632 $tocline = trim( $tocline );
3634 # For the anchor, strip out HTML-y stuff period
3635 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3636 $canonized_headline = trim( $canonized_headline );
3638 # Save headline for section edit hint before it's escaped
3639 $headline_hint = $canonized_headline;
3640 $canonized_headline = Sanitizer
::escapeId( $canonized_headline );
3641 $refers[$headlineCount] = $canonized_headline;
3643 # count how many in assoc. array so we can track dupes in anchors
3644 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3645 $refcount[$headlineCount]=$refers[$canonized_headline];
3647 # Don't number the heading if it is the only one (looks silly)
3648 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3649 # the two are different if the line contains a link
3650 $headline=$numbering . ' ' . $headline;
3653 # Create the anchor for linking from the TOC to the section
3654 $anchor = $canonized_headline;
3655 if($refcount[$headlineCount] > 1 ) {
3656 $anchor .= '_' . $refcount[$headlineCount];
3658 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3659 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3660 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3662 # give headline the correct <h#> tag
3663 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3665 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3667 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3671 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3678 $this->mOutput
->setSections( $tocraw );
3680 # Never ever show TOC if no headers
3681 if( $numVisible < 1 ) {
3686 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3687 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3689 $toc = $sk->tocList( $toc );
3692 # split up and insert constructed headlines
3694 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3697 foreach( $blocks as $block ) {
3698 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3699 # This is the [edit] link that appears for the top block of text when
3700 # section editing is enabled
3702 # Disabled because it broke block formatting
3703 # For example, a bullet point in the top line
3704 # $full .= $sk->editSectionLink(0);
3707 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3708 # Top anchor now in skin
3712 if( !empty( $head[$i] ) ) {
3717 if( $this->mForceTocPosition
) {
3718 return str_replace( '<!--MWTOC-->', $toc, $full );
3725 * Transform wiki markup when saving a page by doing \r\n -> \n
3726 * conversion, substitting signatures, {{subst:}} templates, etc.
3728 * @param string $text the text to transform
3729 * @param Title &$title the Title object for the current article
3730 * @param User &$user the User object describing the current user
3731 * @param ParserOptions $options parsing options
3732 * @param bool $clearState whether to clear the parser state first
3733 * @return string the altered wiki markup
3736 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3737 $this->mOptions
= $options;
3738 $this->mTitle
=& $title;
3739 $this->setOutputType( OT_WIKI
);
3741 if ( $clearState ) {
3742 $this->clearState();
3745 $stripState = new StripState
;
3749 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3750 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3751 $text = $this->pstPass2( $text, $stripState, $user );
3752 $text = $stripState->unstripBoth( $text );
3757 * Pre-save transform helper function
3760 function pstPass2( $text, &$stripState, $user ) {
3761 global $wgContLang, $wgLocaltimezone;
3763 /* Note: This is the timestamp saved as hardcoded wikitext to
3764 * the database, we use $wgContLang here in order to give
3765 * everyone the same signature and use the default one rather
3766 * than the one selected in each user's preferences.
3768 if ( isset( $wgLocaltimezone ) ) {
3769 $oldtz = getenv( 'TZ' );
3770 putenv( 'TZ='.$wgLocaltimezone );
3772 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3773 ' (' . date( 'T' ) . ')';
3774 if ( isset( $wgLocaltimezone ) ) {
3775 putenv( 'TZ='.$oldtz );
3778 # Variable replacement
3779 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3780 $text = $this->replaceVariables( $text );
3782 # Strip out <nowiki> etc. added via replaceVariables
3783 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3786 $sigText = $this->getUserSig( $user );
3787 $text = strtr( $text, array(
3789 '~~~~' => "$sigText $d",
3793 # Context links: [[|name]] and [[name (context)|]]
3795 global $wgLegalTitleChars;
3796 $tc = "[$wgLegalTitleChars]";
3797 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3799 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3800 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3801 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3803 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3804 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3805 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3807 $t = $this->mTitle
->getText();
3809 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3810 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3811 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3812 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3814 # if there's no context, don't bother duplicating the title
3815 $text = preg_replace( $p2, '[[\\1]]', $text );
3818 # Trim trailing whitespace
3819 $text = rtrim( $text );
3825 * Fetch the user's signature text, if any, and normalize to
3826 * validated, ready-to-insert wikitext.
3832 function getUserSig( &$user ) {
3833 global $wgMaxSigChars;
3835 $username = $user->getName();
3836 $nickname = $user->getOption( 'nickname' );
3837 $nickname = $nickname === '' ?
$username : $nickname;
3839 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3840 $nickname = $username;
3841 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3842 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3843 # Sig. might contain markup; validate this
3844 if( $this->validateSig( $nickname ) !== false ) {
3845 # Validated; clean up (if needed) and return it
3846 return $this->cleanSig( $nickname, true );
3848 # Failed to validate; fall back to the default
3849 $nickname = $username;
3850 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3854 // Make sure nickname doesnt get a sig in a sig
3855 $nickname = $this->cleanSigInSig( $nickname );
3857 # If we're still here, make it a link to the user page
3858 $userText = wfEscapeWikiText( $username );
3859 $nickText = wfEscapeWikiText( $nickname );
3860 if ( $user->isAnon() ) {
3861 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3863 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3868 * Check that the user's signature contains no bad XML
3870 * @param string $text
3871 * @return mixed An expanded string, or false if invalid.
3873 function validateSig( $text ) {
3874 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3878 * Clean up signature text
3880 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3881 * 2) Substitute all transclusions
3883 * @param string $text
3884 * @param $parsing Whether we're cleaning (preferences save) or parsing
3885 * @return string Signature text
3887 function cleanSig( $text, $parsing = false ) {
3889 $this->startExternalParse( $this->mTitle
, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3891 $substWord = MagicWord
::get( 'subst' );
3892 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3893 $substText = '{{' . $substWord->getSynonym( 0 );
3895 $text = preg_replace( $substRegex, $substText, $text );
3896 $text = $this->cleanSigInSig( $text );
3897 $text = $this->replaceVariables( $text );
3899 $this->clearState();
3904 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3905 * @param string $text
3906 * @return string Signature text with /~{3,5}/ removed
3908 function cleanSigInSig( $text ) {
3909 $text = preg_replace( '/~{3,5}/', '', $text );
3914 * Set up some variables which are usually set up in parse()
3915 * so that an external function can call some class members with confidence
3918 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3919 $this->mTitle
=& $title;
3920 $this->mOptions
= $options;
3921 $this->setOutputType( $outputType );
3922 if ( $clearState ) {
3923 $this->clearState();
3928 * Transform a MediaWiki message by replacing magic variables.
3930 * @param string $text the text to transform
3931 * @param ParserOptions $options options
3932 * @return string the text with variables substituted
3935 function transformMsg( $text, $options ) {
3937 static $executing = false;
3939 $fname = "Parser::transformMsg";
3941 # Guard against infinite recursion
3947 wfProfileIn($fname);
3949 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3950 $this->mTitle
= $wgTitle;
3952 $this->mTitle
= Title
::newFromText('msg');
3954 $this->mOptions
= $options;
3955 $this->setOutputType( OT_MSG
);
3956 $this->clearState();
3957 $text = $this->replaceVariables( $text );
3960 wfProfileOut($fname);
3965 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3966 * The callback should have the following form:
3967 * function myParserHook( $text, $params, &$parser ) { ... }
3969 * Transform and return $text. Use $parser for any required context, e.g. use
3970 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3974 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3975 * @param mixed $callback The callback function (and object) to use for the tag
3977 * @return The old value of the mTagHooks array associated with the hook
3979 function setHook( $tag, $callback ) {
3980 $tag = strtolower( $tag );
3981 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3982 $this->mTagHooks
[$tag] = $callback;
3987 function setTransparentTagHook( $tag, $callback ) {
3988 $tag = strtolower( $tag );
3989 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3990 $this->mTransparentTagHooks
[$tag] = $callback;
3996 * Create a function, e.g. {{sum:1|2|3}}
3997 * The callback function should have the form:
3998 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4000 * The callback may either return the text result of the function, or an array with the text
4001 * in element 0, and a number of flags in the other elements. The names of the flags are
4002 * specified in the keys. Valid flags are:
4003 * found The text returned is valid, stop processing the template. This
4005 * nowiki Wiki markup in the return value should be escaped
4006 * noparse Unsafe HTML tags should not be stripped, etc.
4007 * noargs Don't replace triple-brace arguments in the return value
4008 * isHTML The returned text is HTML, armour it against wikitext transformation
4012 * @param string $id The magic word ID
4013 * @param mixed $callback The callback function (and object) to use
4014 * @param integer $flags a combination of the following flags:
4015 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4017 * @return The old callback function for this name, if any
4019 function setFunctionHook( $id, $callback, $flags = 0 ) {
4020 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4021 $this->mFunctionHooks
[$id] = $callback;
4023 # Add to function cache
4024 $mw = MagicWord
::get( $id );
4026 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4028 $synonyms = $mw->getSynonyms();
4029 $sensitive = intval( $mw->isCaseSensitive() );
4031 foreach ( $synonyms as $syn ) {
4033 if ( !$sensitive ) {
4034 $syn = strtolower( $syn );
4037 if ( !( $flags & SFH_NO_HASH
) ) {
4040 # Remove trailing colon
4041 if ( substr( $syn, -1, 1 ) == ':' ) {
4042 $syn = substr( $syn, 0, -1 );
4044 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4050 * Get all registered function hook identifiers
4054 function getFunctionHooks() {
4055 return array_keys( $this->mFunctionHooks
);
4059 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4060 * Placeholders created in Skin::makeLinkObj()
4061 * Returns an array of links found, indexed by PDBK:
4065 * $options is a bit field, RLH_FOR_UPDATE to select for update
4067 function replaceLinkHolders( &$text, $options = 0 ) {
4071 $fname = 'Parser::replaceLinkHolders';
4072 wfProfileIn( $fname );
4076 $sk = $this->mOptions
->getSkin();
4077 $linkCache =& LinkCache
::singleton();
4079 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4080 wfProfileIn( $fname.'-check' );
4081 $dbr = wfGetDB( DB_SLAVE
);
4082 $page = $dbr->tableName( 'page' );
4083 $threshold = $wgUser->getOption('stubthreshold');
4086 asort( $this->mLinkHolders
['namespaces'] );
4091 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4093 $title = $this->mLinkHolders
['titles'][$key];
4095 # Skip invalid entries.
4096 # Result will be ugly, but prevents crash.
4097 if ( is_null( $title ) ) {
4100 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4102 # Check if it's a static known link, e.g. interwiki
4103 if ( $title->isAlwaysKnown() ) {
4104 $colours[$pdbk] = 1;
4105 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4106 $colours[$pdbk] = 1;
4107 $this->mOutput
->addLink( $title, $id );
4108 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4109 $colours[$pdbk] = 0;
4110 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4111 $colours[$pdbk] = 0;
4113 # Not in the link cache, add it to the query
4114 if ( !isset( $current ) ) {
4116 $query = "SELECT page_id, page_namespace, page_title";
4117 if ( $threshold > 0 ) {
4118 $query .= ', page_len, page_is_redirect';
4120 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4121 } elseif ( $current != $ns ) {
4123 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4128 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4133 if ( $options & RLH_FOR_UPDATE
) {
4134 $query .= ' FOR UPDATE';
4137 $res = $dbr->query( $query, $fname );
4139 # Fetch data and form into an associative array
4140 # non-existent = broken
4143 while ( $s = $dbr->fetchObject($res) ) {
4144 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4145 $pdbk = $title->getPrefixedDBkey();
4146 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4147 $this->mOutput
->addLink( $title, $s->page_id
);
4149 $colours[$pdbk] = ( $threshold == 0 ||
(
4150 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4151 $s->page_is_redirect ||
4152 !Namespace::isContent( $s->page_namespace
) )
4156 wfProfileOut( $fname.'-check' );
4158 # Do a second query for different language variants of links and categories
4159 if($wgContLang->hasVariants()){
4160 $linkBatch = new LinkBatch();
4161 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4162 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4163 $varCategories = array(); // category replacements oldDBkey => newDBkey
4165 $categories = $this->mOutput
->getCategoryLinks();
4167 // Add variants of links to link batch
4168 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4169 $title = $this->mLinkHolders
['titles'][$key];
4170 if ( is_null( $title ) )
4173 $pdbk = $title->getPrefixedDBkey();
4174 $titleText = $title->getText();
4176 // generate all variants of the link title text
4177 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4179 // if link was not found (in first query), add all variants to query
4180 if ( !isset($colours[$pdbk]) ){
4181 foreach($allTextVariants as $textVariant){
4182 if($textVariant != $titleText){
4183 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4184 if(is_null($variantTitle)) continue;
4185 $linkBatch->addObj( $variantTitle );
4186 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4192 // process categories, check if a category exists in some variant
4193 foreach( $categories as $category ){
4194 $variants = $wgContLang->convertLinkToAllVariants($category);
4195 foreach($variants as $variant){
4196 if($variant != $category){
4197 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4198 if(is_null($variantTitle)) continue;
4199 $linkBatch->addObj( $variantTitle );
4200 $categoryMap[$variant] = $category;
4206 if(!$linkBatch->isEmpty()){
4208 $titleClause = $linkBatch->constructSet('page', $dbr);
4210 $variantQuery = "SELECT page_id, page_namespace, page_title";
4211 if ( $threshold > 0 ) {
4212 $variantQuery .= ', page_len, page_is_redirect';
4215 $variantQuery .= " FROM $page WHERE $titleClause";
4216 if ( $options & RLH_FOR_UPDATE
) {
4217 $variantQuery .= ' FOR UPDATE';
4220 $varRes = $dbr->query( $variantQuery, $fname );
4222 // for each found variants, figure out link holders and replace
4223 while ( $s = $dbr->fetchObject($varRes) ) {
4225 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4226 $varPdbk = $variantTitle->getPrefixedDBkey();
4227 $vardbk = $variantTitle->getDBkey();
4229 $holderKeys = array();
4230 if(isset($variantMap[$varPdbk])){
4231 $holderKeys = $variantMap[$varPdbk];
4232 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4233 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4236 // loop over link holders
4237 foreach($holderKeys as $key){
4238 $title = $this->mLinkHolders
['titles'][$key];
4239 if ( is_null( $title ) ) continue;
4241 $pdbk = $title->getPrefixedDBkey();
4243 if(!isset($colours[$pdbk])){
4244 // found link in some of the variants, replace the link holder data
4245 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4246 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4248 // set pdbk and colour
4249 $pdbks[$key] = $varPdbk;
4250 if ( $threshold > 0 ) {
4251 $size = $s->page_len
;
4252 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4253 $colours[$varPdbk] = 1;
4255 $colours[$varPdbk] = 2;
4259 $colours[$varPdbk] = 1;
4264 // check if the object is a variant of a category
4265 if(isset($categoryMap[$vardbk])){
4266 $oldkey = $categoryMap[$vardbk];
4267 if($oldkey != $vardbk)
4268 $varCategories[$oldkey]=$vardbk;
4272 // rebuild the categories in original order (if there are replacements)
4273 if(count($varCategories)>0){
4275 $originalCats = $this->mOutput
->getCategories();
4276 foreach($originalCats as $cat => $sortkey){
4277 // make the replacement
4278 if( array_key_exists($cat,$varCategories) )
4279 $newCats[$varCategories[$cat]] = $sortkey;
4280 else $newCats[$cat] = $sortkey;
4282 $this->mOutput
->setCategoryLinks($newCats);
4287 # Construct search and replace arrays
4288 wfProfileIn( $fname.'-construct' );
4289 $replacePairs = array();
4290 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4291 $pdbk = $pdbks[$key];
4292 $searchkey = "<!--LINK $key-->";
4293 $title = $this->mLinkHolders
['titles'][$key];
4294 if ( empty( $colours[$pdbk] ) ) {
4295 $linkCache->addBadLinkObj( $title );
4296 $colours[$pdbk] = 0;
4297 $this->mOutput
->addLink( $title, 0 );
4298 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4299 $this->mLinkHolders
['texts'][$key],
4300 $this->mLinkHolders
['queries'][$key] );
4301 } elseif ( $colours[$pdbk] == 1 ) {
4302 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4303 $this->mLinkHolders
['texts'][$key],
4304 $this->mLinkHolders
['queries'][$key] );
4305 } elseif ( $colours[$pdbk] == 2 ) {
4306 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4307 $this->mLinkHolders
['texts'][$key],
4308 $this->mLinkHolders
['queries'][$key] );
4311 $replacer = new HashtableReplacer( $replacePairs, 1 );
4312 wfProfileOut( $fname.'-construct' );
4315 wfProfileIn( $fname.'-replace' );
4316 $text = preg_replace_callback(
4317 '/(<!--LINK .*?-->)/',
4321 wfProfileOut( $fname.'-replace' );
4324 # Now process interwiki link holders
4325 # This is quite a bit simpler than internal links
4326 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4327 wfProfileIn( $fname.'-interwiki' );
4328 # Make interwiki link HTML
4329 $replacePairs = array();
4330 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4331 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4332 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4334 $replacer = new HashtableReplacer( $replacePairs, 1 );
4336 $text = preg_replace_callback(
4337 '/<!--IWLINK (.*?)-->/',
4340 wfProfileOut( $fname.'-interwiki' );
4343 wfProfileOut( $fname );
4348 * Replace <!--LINK--> link placeholders with plain text of links
4349 * (not HTML-formatted).
4350 * @param string $text
4353 function replaceLinkHoldersText( $text ) {
4354 $fname = 'Parser::replaceLinkHoldersText';
4355 wfProfileIn( $fname );
4357 $text = preg_replace_callback(
4358 '/<!--(LINK|IWLINK) (.*?)-->/',
4359 array( &$this, 'replaceLinkHoldersTextCallback' ),
4362 wfProfileOut( $fname );
4367 * @param array $matches
4371 function replaceLinkHoldersTextCallback( $matches ) {
4372 $type = $matches[1];
4374 if( $type == 'LINK' ) {
4375 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4376 return $this->mLinkHolders
['texts'][$key];
4378 } elseif( $type == 'IWLINK' ) {
4379 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4380 return $this->mInterwikiLinkHolders
['texts'][$key];
4387 * Tag hook handler for 'pre'.
4389 function renderPreTag( $text, $attribs ) {
4390 // Backwards-compatibility hack
4391 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4393 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4394 return wfOpenElement( 'pre', $attribs ) .
4395 Xml
::escapeTagsOnly( $content ) .
4400 * Renders an image gallery from a text with one line per image.
4401 * text labels may be given by using |-style alternative text. E.g.
4402 * Image:one.jpg|The number "1"
4403 * Image:tree.jpg|A tree
4404 * given as text will return the HTML of a gallery with two images,
4405 * labeled 'The number "1"' and
4408 function renderImageGallery( $text, $params ) {
4409 $ig = new ImageGallery();
4410 $ig->setContextTitle( $this->mTitle
);
4411 $ig->setShowBytes( false );
4412 $ig->setShowFilename( false );
4413 $ig->setParser( $this );
4414 $ig->setHideBadImages();
4415 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4416 $ig->useSkin( $this->mOptions
->getSkin() );
4417 $ig->mRevisionId
= $this->mRevisionId
;
4419 if( isset( $params['caption'] ) ) {
4420 $caption = $params['caption'];
4421 $caption = htmlspecialchars( $caption );
4422 $caption = $this->replaceInternalLinks( $caption );
4423 $ig->setCaptionHtml( $caption );
4425 if( isset( $params['perrow'] ) ) {
4426 $ig->setPerRow( $params['perrow'] );
4428 if( isset( $params['widths'] ) ) {
4429 $ig->setWidths( $params['widths'] );
4431 if( isset( $params['heights'] ) ) {
4432 $ig->setHeights( $params['heights'] );
4435 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4437 $lines = explode( "\n", $text );
4438 foreach ( $lines as $line ) {
4439 # match lines like these:
4440 # Image:someimage.jpg|This is some image
4442 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4444 if ( count( $matches ) == 0 ) {
4447 $tp = Title
::newFromText( $matches[1] );
4449 if( is_null( $nt ) ) {
4450 # Bogus title. Ignore these so we don't bomb out later.
4453 if ( isset( $matches[3] ) ) {
4454 $label = $matches[3];
4459 $pout = $this->parse( $label,
4462 false, // Strip whitespace...?
4463 false // Don't clear state!
4465 $html = $pout->getText();
4467 $ig->add( $nt, $html );
4469 # Only add real images (bug #5586)
4470 if ( $nt->getNamespace() == NS_IMAGE
) {
4471 $this->mOutput
->addImage( $nt->getDBkey() );
4474 return $ig->toHTML();
4477 function getImageParams( $handler ) {
4479 $handlerClass = get_class( $handler );
4483 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4484 // Initialise static lists
4485 static $internalParamNames = array(
4486 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4487 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4488 'bottom', 'text-bottom' ),
4489 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4490 'upright', 'border' ),
4492 static $internalParamMap;
4493 if ( !$internalParamMap ) {
4494 $internalParamMap = array();
4495 foreach ( $internalParamNames as $type => $names ) {
4496 foreach ( $names as $name ) {
4497 $magicName = str_replace( '-', '_', "img_$name" );
4498 $internalParamMap[$magicName] = array( $type, $name );
4503 // Add handler params
4504 $paramMap = $internalParamMap;
4506 $handlerParamMap = $handler->getParamMap();
4507 foreach ( $handlerParamMap as $magic => $paramName ) {
4508 $paramMap[$magic] = array( 'handler', $paramName );
4511 $this->mImageParams
[$handlerClass] = $paramMap;
4512 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4514 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4518 * Parse image options text and use it to make an image
4520 function makeImage( $title, $options ) {
4521 # @TODO: let the MediaHandler specify its transform parameters
4523 # Check if the options text is of the form "options|alt text"
4525 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4526 # * left no resizing, just left align. label is used for alt= only
4527 # * right same, but right aligned
4528 # * none same, but not aligned
4529 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4530 # * center center the image
4531 # * framed Keep original image size, no magnify-button.
4532 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4533 # * upright reduce width for upright images, rounded to full __0 px
4534 # * border draw a 1px border around the image
4535 # vertical-align values (no % or length right now):
4545 $parts = array_map( 'trim', explode( '|', $options) );
4546 $sk = $this->mOptions
->getSkin();
4548 # Give extensions a chance to select the file revision for us
4549 $skip = $time = false;
4550 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4553 return $sk->makeLinkObj( $title );
4557 $file = wfFindFile( $title, $time );
4558 $handler = $file ?
$file->getHandler() : false;
4560 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4562 # Process the input parameters
4564 $params = array( 'frame' => array(), 'handler' => array(),
4565 'horizAlign' => array(), 'vertAlign' => array() );
4566 foreach( $parts as $part ) {
4567 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4568 if ( isset( $paramMap[$magicName] ) ) {
4569 list( $type, $paramName ) = $paramMap[$magicName];
4570 $params[$type][$paramName] = $value;
4572 // Special case; width and height come in one variable together
4573 if( $type == 'handler' && $paramName == 'width' ) {
4575 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4576 $params[$type]['width'] = intval( $m[1] );
4577 $params[$type]['height'] = intval( $m[2] );
4579 $params[$type]['width'] = intval( $value );
4587 # Process alignment parameters
4588 if ( $params['horizAlign'] ) {
4589 $params['frame']['align'] = key( $params['horizAlign'] );
4591 if ( $params['vertAlign'] ) {
4592 $params['frame']['valign'] = key( $params['vertAlign'] );
4595 # Validate the handler parameters
4597 foreach ( $params['handler'] as $name => $value ) {
4598 if ( !$handler->validateParam( $name, $value ) ) {
4599 unset( $params['handler'][$name] );
4604 # Strip bad stuff out of the alt text
4605 $alt = $this->replaceLinkHoldersText( $caption );
4607 # make sure there are no placeholders in thumbnail attributes
4608 # that are later expanded to html- so expand them now and
4610 $alt = $this->mStripState
->unstripBoth( $alt );
4611 $alt = Sanitizer
::stripAllTags( $alt );
4613 $params['frame']['alt'] = $alt;
4614 $params['frame']['caption'] = $caption;
4616 # Linker does the rest
4617 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4619 # Give the handler a chance to modify the parser object
4621 $handler->parserTransformHook( $this, $file );
4628 * Set a flag in the output object indicating that the content is dynamic and
4629 * shouldn't be cached.
4631 function disableCache() {
4632 wfDebug( "Parser output marked as uncacheable.\n" );
4633 $this->mOutput
->mCacheTime
= -1;
4637 * Callback from the Sanitizer for expanding items found in HTML attribute
4638 * values, so they can be safely tested and escaped.
4639 * @param string $text
4640 * @param array $args
4644 function attributeStripCallback( &$text, $args ) {
4645 $text = $this->replaceVariables( $text, $args );
4646 $text = $this->mStripState
->unstripBoth( $text );
4655 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4656 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4657 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4663 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4668 * Break wikitext input into sections, and either pull or replace
4669 * some particular section's text.
4671 * External callers should use the getSection and replaceSection methods.
4673 * @param $text Page wikitext
4674 * @param $section Numbered section. 0 pulls the text before the first
4675 * heading; other numbers will pull the given section
4676 * along with its lower-level subsections.
4677 * @param $mode One of "get" or "replace"
4678 * @param $newtext Replacement text for section data.
4679 * @return string for "get", the extracted section text.
4680 * for "replace", the whole page with the section replaced.
4682 private function extractSections( $text, $section, $mode, $newtext='' ) {
4683 # I.... _hope_ this is right.
4684 # Otherwise, sometimes we don't have things initialized properly.
4685 $this->clearState();
4687 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4688 # comments to be stripped as well)
4689 $stripState = new StripState
;
4691 $oldOutputType = $this->mOutputType
;
4692 $oldOptions = $this->mOptions
;
4693 $this->mOptions
= new ParserOptions();
4694 $this->setOutputType( OT_WIKI
);
4696 $striptext = $this->strip( $text, $stripState, true );
4698 $this->setOutputType( $oldOutputType );
4699 $this->mOptions
= $oldOptions;
4701 # now that we can be sure that no pseudo-sections are in the source,
4702 # split it up by section
4703 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4704 $comment = "(?:$uniq-!--.*?QINU\x07)";
4709 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4710 (=+) # Should this be limited to 6?
4711 .+? # Section title...
4712 \\2 # Ending = count must match start
4713 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4722 PREG_SPLIT_DELIM_CAPTURE
);
4724 if( $mode == "get" ) {
4725 if( $section == 0 ) {
4726 // "Section 0" returns the content before any other section.
4729 //track missing section, will replace if found.
4732 } elseif( $mode == "replace" ) {
4733 if( $section == 0 ) {
4734 $rv = $newtext . "\n\n";
4743 for( $index = 1; $index < count( $secs ); ) {
4744 $headerLine = $secs[$index++
];
4745 if( $secs[$index] ) {
4747 $headerLevel = strlen( $secs[$index++
] );
4751 $headerLevel = intval( $secs[$index++
] );
4753 $content = $secs[$index++
];
4756 if( $mode == "get" ) {
4757 if( $count == $section ) {
4758 $rv = $headerLine . $content;
4759 $sectionLevel = $headerLevel;
4760 } elseif( $count > $section ) {
4761 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4762 $rv .= $headerLine . $content;
4764 // Broke out to a higher-level section
4768 } elseif( $mode == "replace" ) {
4769 if( $count < $section ) {
4770 $rv .= $headerLine . $content;
4771 } elseif( $count == $section ) {
4772 $rv .= $newtext . "\n\n";
4773 $sectionLevel = $headerLevel;
4774 } elseif( $count > $section ) {
4775 if( $headerLevel <= $sectionLevel ) {
4776 // Passed the section's sub-parts.
4780 $rv .= $headerLine . $content;
4786 # reinsert stripped tags
4787 $rv = trim( $stripState->unstripBoth( $rv ) );
4793 * This function returns the text of a section, specified by a number ($section).
4794 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4795 * the first section before any such heading (section 0).
4797 * If a section contains subsections, these are also returned.
4799 * @param $text String: text to look in
4800 * @param $section Integer: section number
4801 * @param $deftext: default to return if section is not found
4802 * @return string text of the requested section
4804 public function getSection( $text, $section, $deftext='' ) {
4805 return $this->extractSections( $text, $section, "get", $deftext );
4808 public function replaceSection( $oldtext, $section, $text ) {
4809 return $this->extractSections( $oldtext, $section, "replace", $text );
4813 * Get the timestamp associated with the current revision, adjusted for
4814 * the default server-local timestamp
4816 function getRevisionTimestamp() {
4817 if ( is_null( $this->mRevisionTimestamp
) ) {
4818 wfProfileIn( __METHOD__
);
4820 $dbr = wfGetDB( DB_SLAVE
);
4821 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4822 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4824 // Normalize timestamp to internal MW format for timezone processing.
4825 // This has the added side-effect of replacing a null value with
4826 // the current time, which gives us more sensible behavior for
4828 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4830 // The cryptic '' timezone parameter tells to use the site-default
4831 // timezone offset instead of the user settings.
4833 // Since this value will be saved into the parser cache, served
4834 // to other users, and potentially even used inside links and such,
4835 // it needs to be consistent for all visitors.
4836 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4838 wfProfileOut( __METHOD__
);
4840 return $this->mRevisionTimestamp
;
4844 * Mutator for $mDefaultSort
4846 * @param $sort New value
4848 public function setDefaultSort( $sort ) {
4849 $this->mDefaultSort
= $sort;
4853 * Accessor for $mDefaultSort
4854 * Will use the title/prefixed title if none is set
4858 public function getDefaultSort() {
4859 if( $this->mDefaultSort
!== false ) {
4860 return $this->mDefaultSort
;
4862 return $this->mTitle
->getNamespace() == NS_CATEGORY
4863 ?
$this->mTitle
->getText()
4864 : $this->mTitle
->getPrefixedText();
4869 * Try to guess the section anchor name based on a wikitext fragment
4870 * presumably extracted from a heading, for example "Header" from
4873 public function guessSectionNameFromWikiText( $text ) {
4874 # Strip out wikitext links(they break the anchor)
4875 $text = $this->stripSectionName( $text );
4876 $headline = Sanitizer
::decodeCharReferences( $text );
4878 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4879 $headline = trim( $headline );
4880 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4881 $replacearray = array(
4886 array_keys( $replacearray ),
4887 array_values( $replacearray ),
4892 * Strips a text string of wikitext for use in a section anchor
4894 * Accepts a text string and then removes all wikitext from the
4895 * string and leaves only the resultant text (i.e. the result of
4896 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4897 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4898 * to create valid section anchors by mimicing the output of the
4899 * parser when headings are parsed.
4901 * @param $text string Text string to be stripped of wikitext
4902 * for use in a Section anchor
4903 * @return Filtered text string
4905 public function stripSectionName( $text ) {
4906 # Strip internal link markup
4907 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4908 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4910 # Strip external link markup (FIXME: Not Tolerant to blank link text
4911 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4912 # on how many empty links there are on the page - need to figure that out.
4913 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4915 # Parse wikitext quotes (italics & bold)
4916 $text = $this->doQuotes($text);
4919 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4924 * strip/replaceVariables/unstrip for preprocessor regression testing
4926 function srvus( $text ) {
4927 $text = $this->strip( $text, $this->mStripState
);
4928 $text = Sanitizer
::removeHTMLtags( $text );
4929 $text = $this->replaceVariables( $text );
4930 $text = preg_replace( '/<!--MWTEMPLATESECTION.*?-->/', '', $text );
4931 $text = $this->mStripState
->unstripBoth( $text );