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.2';
14 # Flags for Parser::setFunctionHook
15 # Also available as global constants from Defines.php
16 const SFH_NO_HASH
= 1;
17 const SFH_OBJECT_ARGS
= 2;
19 # Constants needed for external link processing
20 # Everything except bracket, space, or control characters
21 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
22 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)\\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/S';
24 // State constants for the definition list colon extraction
25 const COLON_STATE_TEXT
= 0;
26 const COLON_STATE_TAG
= 1;
27 const COLON_STATE_TAGSTART
= 2;
28 const COLON_STATE_CLOSETAG
= 3;
29 const COLON_STATE_TAGSLASH
= 4;
30 const COLON_STATE_COMMENT
= 5;
31 const COLON_STATE_COMMENTDASH
= 6;
32 const COLON_STATE_COMMENTDASHDASH
= 7;
38 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
39 $mImageParams, $mImageParamsMagicArray, $mExtLinkBracketedRegex;
41 # Cleared with clearState():
42 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
43 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
44 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
45 var $mIncludeSizes, $mDefaultSort;
46 var $mTemplates, // cache of already loaded templates, avoids
47 // multiple SQL queries for the same string
48 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
49 // in this path. Used for loop detection.
52 # These are variables reset at least once per parse regardless of $clearState
53 var $mOptions, // ParserOptions object
54 $mTitle, // Title context, used for self-link rendering and similar things
55 $mOutputType, // Output type, one of the OT_xxx constants
56 $ot, // Shortcut alias, see setOutputType()
57 $mRevisionId, // ID to display in {{REVISIONID}} tags
58 $mRevisionTimestamp, // The timestamp of the specified revision ID
59 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
68 function __construct( $conf = array() ) {
69 $this->mTagHooks
= array();
70 $this->mTransparentTagHooks
= array();
71 $this->mFunctionHooks
= array();
72 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
73 $this->mFirstCall
= true;
74 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
75 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
79 * Do various kinds of initialisation on the first call of the parser
81 function firstCallInit() {
82 if ( !$this->mFirstCall
) {
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();
132 $this->mFirstCall
= false;
133 wfProfileOut( __METHOD__
);
141 function clearState() {
142 wfProfileIn( __METHOD__
);
143 if ( $this->mFirstCall
) {
144 $this->firstCallInit();
146 $this->mOutput
= new ParserOutput
;
147 $this->mAutonumber
= 0;
148 $this->mLastSection
= '';
149 $this->mDTopen
= false;
150 $this->mIncludeCount
= array();
151 $this->mStripState
= new StripState
;
152 $this->mArgStack
= array();
153 $this->mInPre
= false;
154 $this->mInterwikiLinkHolders
= array(
158 $this->mLinkHolders
= array(
159 'namespaces' => array(),
161 'queries' => array(),
165 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
168 * Prefix for temporary replacement strings for the multipass parser.
169 * \x07 should never appear in input as it's disallowed in XML.
170 * Using it at the front also gives us a little extra robustness
171 * since it shouldn't match when butted up against identifier-like
174 $this->mUniqPrefix
= "\x07UNIQ" . self
::getRandomString();
176 # Clear these on every parse, bug 4549
177 $this->mTemplates
= array();
178 $this->mTemplatePath
= array();
180 $this->mShowToc
= true;
181 $this->mForceTocPosition
= false;
182 $this->mIncludeSizes
= array(
187 $this->mDefaultSort
= false;
189 wfRunHooks( 'ParserClearState', array( &$this ) );
190 wfProfileOut( __METHOD__
);
193 function setOutputType( $ot ) {
194 $this->mOutputType
= $ot;
197 'html' => $ot == OT_HTML
,
198 'wiki' => $ot == OT_WIKI
,
199 'msg' => $ot == OT_MSG
,
200 'pre' => $ot == OT_PREPROCESS
,
205 * Accessor for mUniqPrefix.
209 function uniqPrefix() {
210 return $this->mUniqPrefix
;
214 * Convert wikitext to HTML
215 * Do not call this function recursively.
217 * @param string $text Text we want to parse
218 * @param Title &$title A title object
219 * @param array $options
220 * @param boolean $linestart
221 * @param boolean $clearState
222 * @param int $revid number to pass in {{REVISIONID}}
223 * @return ParserOutput a ParserOutput
225 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
227 * First pass--just handle <nowiki> sections, pass the rest off
228 * to internalParse() which does all the real work.
231 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
232 $fname = 'Parser::parse-' . wfGetCaller();
233 wfProfileIn( __METHOD__
);
234 wfProfileIn( $fname );
240 $this->mOptions
= $options;
241 $this->mTitle
=& $title;
242 $oldRevisionId = $this->mRevisionId
;
243 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
244 if( $revid !== null ) {
245 $this->mRevisionId
= $revid;
246 $this->mRevisionTimestamp
= null;
248 $this->setOutputType( OT_HTML
);
249 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
250 $text = $this->strip( $text, $this->mStripState
);
251 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
252 $text = $this->internalParse( $text );
253 $text = $this->mStripState
->unstripGeneral( $text );
255 # Clean up special characters, only run once, next-to-last before doBlockLevels
257 # french spaces, last one Guillemet-left
258 # only if there is something before the space
259 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
260 # french spaces, Guillemet-right
261 '/(\\302\\253) /' => '\\1 ',
263 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
266 $text = $this->doBlockLevels( $text, $linestart );
268 $this->replaceLinkHolders( $text );
270 # the position of the parserConvert() call should not be changed. it
271 # assumes that the links are all replaced and the only thing left
272 # is the <nowiki> mark.
273 # Side-effects: this calls $this->mOutput->setTitleText()
274 $text = $wgContLang->parserConvert( $text, $this );
276 $text = $this->mStripState
->unstripNoWiki( $text );
278 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
280 //!JF Move to its own function
282 $uniq_prefix = $this->mUniqPrefix
;
284 $elements = array_keys( $this->mTransparentTagHooks
);
285 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
287 foreach( $matches as $marker => $data ) {
288 list( $element, $content, $params, $tag ) = $data;
289 $tagName = strtolower( $element );
290 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
291 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
292 array( $content, $params, $this ) );
296 $this->mStripState
->general
->setPair( $marker, $output );
298 $text = $this->mStripState
->unstripGeneral( $text );
300 $text = Sanitizer
::normalizeCharReferences( $text );
302 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
303 $text = self
::tidy($text);
305 # attempt to sanitize at least some nesting problems
306 # (bug #2702 and quite a few others)
308 # ''Something [http://www.cool.com cool''] -->
309 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
310 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
311 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
312 # fix up an anchor inside another anchor, only
313 # at least for a single single nested link (bug 3695)
314 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
315 '\\1\\2</a>\\3</a>\\1\\4</a>',
316 # fix div inside inline elements- doBlockLevels won't wrap a line which
317 # contains a div, so fix it up here; replace
318 # div with escaped text
319 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
320 '\\1\\3<div\\5>\\6</div>\\8\\9',
321 # remove empty italic or bold tag pairs, some
322 # introduced by rules above
323 '/<([bi])><\/\\1>/' => '',
326 $text = preg_replace(
327 array_keys( $tidyregs ),
328 array_values( $tidyregs ),
332 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
334 # Information on include size limits, for the benefit of users who try to skirt them
335 if ( max( $this->mIncludeSizes
) > 1000 ) {
336 $max = $this->mOptions
->getMaxIncludeSize();
338 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
339 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
340 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
341 "Maximum: $max bytes\n" .
344 $this->mOutput
->setText( $text );
345 $this->mRevisionId
= $oldRevisionId;
346 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
347 wfProfileOut( $fname );
348 wfProfileOut( __METHOD__
);
350 return $this->mOutput
;
354 * Recursive parser entry point that can be called from an extension tag
357 function recursiveTagParse( $text ) {
358 wfProfileIn( __METHOD__
);
359 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
360 $text = $this->strip( $text, $this->mStripState
);
361 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
362 $text = $this->internalParse( $text );
363 wfProfileOut( __METHOD__
);
368 * Expand templates and variables in the text, producing valid, static wikitext.
369 * Also removes comments.
371 function preprocess( $text, $title, $options, $revid = null ) {
372 wfProfileIn( __METHOD__
);
374 $this->setOutputType( OT_PREPROCESS
);
375 $this->mOptions
= $options;
376 $this->mTitle
= $title;
377 if( $revid !== null ) {
378 $this->mRevisionId
= $revid;
380 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
381 $text = $this->strip( $text, $this->mStripState
);
382 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
383 if ( $this->mOptions
->getRemoveComments() ) {
384 $text = Sanitizer
::removeHTMLcomments( $text );
386 $text = $this->replaceVariables( $text );
387 $text = $this->mStripState
->unstripBoth( $text );
388 wfProfileOut( __METHOD__
);
393 * Get a random string
398 function getRandomString() {
399 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
402 function &getTitle() { return $this->mTitle
; }
403 function getOptions() { return $this->mOptions
; }
405 function getFunctionLang() {
406 global $wgLang, $wgContLang;
407 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
411 * Replaces all occurrences of HTML-style comments and the given tags
412 * in the text with a random marker and returns teh next text. The output
413 * parameter $matches will be an associative array filled with data in
415 * 'UNIQ-xxxxx' => array(
418 * array( 'param' => 'x' ),
419 * '<element param="x">tag content</element>' ) )
421 * @param $elements list of element names. Comments are always extracted.
422 * @param $text Source text string.
423 * @param $uniq_prefix
428 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
433 $taglist = implode( '|', $elements );
434 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
436 while ( '' != $text ) {
437 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
439 if( count( $p ) < 5 ) {
442 if( count( $p ) > 5 ) {
456 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
457 $stripped .= $marker;
459 if ( $close === '/>' ) {
460 // Empty element tag, <tag />
465 if( $element == '!--' ) {
468 $end = "/(<\\/$element\\s*>)/i";
470 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
472 if( count( $q ) < 3 ) {
473 # No end tag -- let it run out to the end of the text.
482 $matches[$marker] = array( $element,
484 Sanitizer
::decodeTagAttributes( $attributes ),
485 "<$element$attributes$close$content$tail" );
491 * Strips and renders nowiki, pre, math, hiero
492 * If $render is set, performs necessary rendering operations on plugins
493 * Returns the text, and fills an array with data needed in unstrip()
495 * @param StripState $state
497 * @param bool $stripcomments when set, HTML comments <!-- like this -->
498 * will be stripped in addition to other tags. This is important
499 * for section editing, where these comments cause confusion when
500 * counting the sections in the wikisource
502 * @param array dontstrip contains tags which should not be stripped;
503 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
507 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
509 wfProfileIn( __METHOD__
);
510 $render = ($this->mOutputType
== OT_HTML
);
512 $uniq_prefix = $this->mUniqPrefix
;
513 $commentState = new ReplacementArray
;
514 $nowikiItems = array();
515 $generalItems = array();
517 $elements = array_merge(
518 array( 'nowiki', 'gallery' ),
519 array_keys( $this->mTagHooks
) );
522 $elements[] = 'html';
524 if( $this->mOptions
->getUseTeX() ) {
525 $elements[] = 'math';
528 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
529 foreach ( $elements AS $k => $v ) {
530 if ( !in_array ( $v , $dontstrip ) ) continue;
531 unset ( $elements[$k] );
535 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
537 foreach( $matches as $marker => $data ) {
538 list( $element, $content, $params, $tag ) = $data;
540 $tagName = strtolower( $element );
541 wfProfileIn( __METHOD__
."-render-$tagName" );
545 if( substr( $tag, -3 ) == '-->' ) {
548 // Unclosed comment in input.
549 // Close it so later stripping can remove it
558 // Shouldn't happen otherwise. :)
560 $output = Xml
::escapeTagsOnly( $content );
563 $output = $wgContLang->armourMath(
564 MathRenderer
::renderMath( $content, $params ) );
567 $output = $this->renderImageGallery( $content, $params );
570 if( isset( $this->mTagHooks
[$tagName] ) ) {
571 $output = call_user_func_array( $this->mTagHooks
[$tagName],
572 array( $content, $params, $this ) );
574 throw new MWException( "Invalid call hook $element" );
577 wfProfileOut( __METHOD__
."-render-$tagName" );
579 // Just stripping tags; keep the source
583 // Unstrip the output, to support recursive strip() calls
584 $output = $state->unstripBoth( $output );
586 if( !$stripcomments && $element == '!--' ) {
587 $commentState->setPair( $marker, $output );
588 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
589 $nowikiItems[$marker] = $output;
591 $generalItems[$marker] = $output;
594 # Add the new items to the state
595 # We do this after the loop instead of during it to avoid slowing
596 # down the recursive unstrip
597 $state->nowiki
->mergeArray( $nowikiItems );
598 $state->general
->mergeArray( $generalItems );
600 # Unstrip comments unless explicitly told otherwise.
601 # (The comments are always stripped prior to this point, so as to
602 # not invoke any extension tags / parser hooks contained within
604 if ( !$stripcomments ) {
605 // Put them all back and forget them
606 $text = $commentState->replace( $text );
609 wfProfileOut( __METHOD__
);
614 * Restores pre, math, and other extensions removed by strip()
616 * always call unstripNoWiki() after this one
618 * @deprecated use $this->mStripState->unstrip()
620 function unstrip( $text, $state ) {
621 return $state->unstripGeneral( $text );
625 * Always call this after unstrip() to preserve the order
628 * @deprecated use $this->mStripState->unstrip()
630 function unstripNoWiki( $text, $state ) {
631 return $state->unstripNoWiki( $text );
635 * @deprecated use $this->mStripState->unstripBoth()
637 function unstripForHTML( $text ) {
638 return $this->mStripState
->unstripBoth( $text );
642 * Add an item to the strip state
643 * Returns the unique tag which must be inserted into the stripped text
644 * The tag will be replaced with the original text in unstrip()
648 function insertStripItem( $text, &$state ) {
649 $rnd = $this->mUniqPrefix
. '-item' . self
::getRandomString();
650 $state->general
->setPair( $rnd, $text );
655 * Interface with html tidy, used if $wgUseTidy = true.
656 * If tidy isn't able to correct the markup, the original will be
657 * returned in all its glory with a warning comment appended.
659 * Either the external tidy program or the in-process tidy extension
660 * will be used depending on availability. Override the default
661 * $wgTidyInternal setting to disable the internal if it's not working.
663 * @param string $text Hideous HTML input
664 * @return string Corrected HTML output
668 function tidy( $text ) {
669 global $wgTidyInternal;
670 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
671 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
672 '<head><title>test</title></head><body>'.$text.'</body></html>';
673 if( $wgTidyInternal ) {
674 $correctedtext = self
::internalTidy( $wrappedtext );
676 $correctedtext = self
::externalTidy( $wrappedtext );
678 if( is_null( $correctedtext ) ) {
679 wfDebug( "Tidy error detected!\n" );
680 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
682 return $correctedtext;
686 * Spawn an external HTML tidy process and get corrected markup back from it.
691 function externalTidy( $text ) {
692 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
693 $fname = 'Parser::externalTidy';
694 wfProfileIn( $fname );
699 $descriptorspec = array(
700 0 => array('pipe', 'r'),
701 1 => array('pipe', 'w'),
702 2 => array('file', wfGetNull(), 'a')
705 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
706 if (is_resource($process)) {
707 // Theoretically, this style of communication could cause a deadlock
708 // here. If the stdout buffer fills up, then writes to stdin could
709 // block. This doesn't appear to happen with tidy, because tidy only
710 // writes to stdout after it's finished reading from stdin. Search
711 // for tidyParseStdin and tidySaveStdout in console/tidy.c
712 fwrite($pipes[0], $text);
714 while (!feof($pipes[1])) {
715 $cleansource .= fgets($pipes[1], 1024);
718 proc_close($process);
721 wfProfileOut( $fname );
723 if( $cleansource == '' && $text != '') {
724 // Some kind of error happened, so we couldn't get the corrected text.
725 // Just give up; we'll use the source text and append a warning.
733 * Use the HTML tidy PECL extension to use the tidy library in-process,
734 * saving the overhead of spawning a new process.
736 * 'pear install tidy' should be able to compile the extension module.
741 function internalTidy( $text ) {
742 global $wgTidyConf, $IP;
743 $fname = 'Parser::internalTidy';
744 wfProfileIn( $fname );
747 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
748 $tidy->cleanRepair();
749 if( $tidy->getStatus() == 2 ) {
750 // 2 is magic number for fatal error
751 // http://www.php.net/manual/en/function.tidy-get-status.php
754 $cleansource = tidy_get_output( $tidy );
756 wfProfileOut( $fname );
761 * parse the wiki syntax used to render tables
765 function doTableStuff ( $text ) {
766 $fname = 'Parser::doTableStuff';
767 wfProfileIn( $fname );
769 $lines = explode ( "\n" , $text );
770 $td_history = array (); // Is currently a td tag open?
771 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
772 $tr_history = array (); // Is currently a tr tag open?
773 $tr_attributes = array (); // history of tr attributes
774 $has_opened_tr = array(); // Did this table open a <tr> element?
775 $indent_level = 0; // indent level of the table
776 foreach ( $lines as $key => $line )
778 $line = trim ( $line );
780 if( $line == '' ) { // empty line, go to next line
783 $first_character = $line{0};
786 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
787 // First check if we are starting a new table
788 $indent_level = strlen( $matches[1] );
790 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
791 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
793 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
794 array_push ( $td_history , false );
795 array_push ( $last_tag_history , '' );
796 array_push ( $tr_history , false );
797 array_push ( $tr_attributes , '' );
798 array_push ( $has_opened_tr , false );
799 } else if ( count ( $td_history ) == 0 ) {
800 // Don't do any of the following
802 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
803 // We are ending a table
804 $line = '</table>' . substr ( $line , 2 );
805 $last_tag = array_pop ( $last_tag_history );
807 if ( !array_pop ( $has_opened_tr ) ) {
808 $line = "<tr><td></td></tr>{$line}";
811 if ( array_pop ( $tr_history ) ) {
812 $line = "</tr>{$line}";
815 if ( array_pop ( $td_history ) ) {
816 $line = "</{$last_tag}>{$line}";
818 array_pop ( $tr_attributes );
819 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
820 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
821 // Now we have a table row
822 $line = preg_replace( '#^\|-+#', '', $line );
824 // Whats after the tag is now only attributes
825 $attributes = $this->mStripState
->unstripBoth( $line );
826 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
827 array_pop ( $tr_attributes );
828 array_push ( $tr_attributes , $attributes );
831 $last_tag = array_pop ( $last_tag_history );
832 array_pop ( $has_opened_tr );
833 array_push ( $has_opened_tr , true );
835 if ( array_pop ( $tr_history ) ) {
839 if ( array_pop ( $td_history ) ) {
840 $line = "</{$last_tag}>{$line}";
843 $lines[$key] = $line;
844 array_push ( $tr_history , false );
845 array_push ( $td_history , false );
846 array_push ( $last_tag_history , '' );
848 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
849 // This might be cell elements, td, th or captions
850 if ( substr ( $line , 0 , 2 ) == '|+' ) {
851 $first_character = '+';
852 $line = substr ( $line , 1 );
855 $line = substr ( $line , 1 );
857 if ( $first_character == '!' ) {
858 $line = str_replace ( '!!' , '||' , $line );
861 // Split up multiple cells on the same line.
862 // FIXME : This can result in improper nesting of tags processed
863 // by earlier parser steps, but should avoid splitting up eg
864 // attribute values containing literal "||".
865 $cells = StringUtils
::explodeMarkup( '||' , $line );
869 // Loop through each table cell
870 foreach ( $cells as $cell )
873 if ( $first_character != '+' )
875 $tr_after = array_pop ( $tr_attributes );
876 if ( !array_pop ( $tr_history ) ) {
877 $previous = "<tr{$tr_after}>\n";
879 array_push ( $tr_history , true );
880 array_push ( $tr_attributes , '' );
881 array_pop ( $has_opened_tr );
882 array_push ( $has_opened_tr , true );
885 $last_tag = array_pop ( $last_tag_history );
887 if ( array_pop ( $td_history ) ) {
888 $previous = "</{$last_tag}>{$previous}";
891 if ( $first_character == '|' ) {
893 } else if ( $first_character == '!' ) {
895 } else if ( $first_character == '+' ) {
896 $last_tag = 'caption';
901 array_push ( $last_tag_history , $last_tag );
903 // A cell could contain both parameters and data
904 $cell_data = explode ( '|' , $cell , 2 );
906 // Bug 553: Note that a '|' inside an invalid link should not
907 // be mistaken as delimiting cell parameters
908 if ( strpos( $cell_data[0], '[[' ) !== false ) {
909 $cell = "{$previous}<{$last_tag}>{$cell}";
910 } else if ( count ( $cell_data ) == 1 )
911 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
913 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
914 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
915 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
918 $lines[$key] .= $cell;
919 array_push ( $td_history , true );
924 // Closing open td, tr && table
925 while ( count ( $td_history ) > 0 )
927 if ( array_pop ( $td_history ) ) {
930 if ( array_pop ( $tr_history ) ) {
933 if ( !array_pop ( $has_opened_tr ) ) {
934 $lines[] = "<tr><td></td></tr>" ;
937 $lines[] = '</table>' ;
940 $output = implode ( "\n" , $lines ) ;
942 // special case: don't return empty table
943 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
947 wfProfileOut( $fname );
953 * Helper function for parse() that transforms wiki markup into
954 * HTML. Only called for $mOutputType == OT_HTML.
958 function internalParse( $text ) {
961 $fname = 'Parser::internalParse';
962 wfProfileIn( $fname );
964 # Hook to suspend the parser in this state
965 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
966 wfProfileOut( $fname );
970 # Remove <noinclude> tags and <includeonly> sections
971 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
972 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
973 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
975 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
977 $text = $this->replaceVariables( $text, $args );
978 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
980 // Tables need to come after variable replacement for things to work
981 // properly; putting them before other transformations should keep
982 // exciting things like link expansions from showing up in surprising
984 $text = $this->doTableStuff( $text );
986 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
988 $text = $this->stripToc( $text );
989 $this->stripNoGallery( $text );
990 $text = $this->doHeadings( $text );
991 if($this->mOptions
->getUseDynamicDates()) {
992 $df =& DateFormatter
::getInstance();
993 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
995 $text = $this->doAllQuotes( $text );
996 $text = $this->replaceInternalLinks( $text );
997 $text = $this->replaceExternalLinks( $text );
999 # replaceInternalLinks may sometimes leave behind
1000 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1001 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1003 $text = $this->doMagicLinks( $text );
1004 $text = $this->formatHeadings( $text, $isMain );
1006 wfProfileOut( $fname );
1011 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1012 * magic external links.
1016 function &doMagicLinks( &$text ) {
1017 wfProfileIn( __METHOD__
);
1018 $text = preg_replace_callback(
1020 <a.*?</a> | # Skip link text
1021 <.*?> | # Skip stuff inside HTML elements
1022 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1023 ISBN\s+(\b # ISBN, capture number as m[2]
1024 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1025 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1026 [0-9Xx] # check digit
1028 )!x', array( &$this, 'magicLinkCallback' ), $text );
1029 wfProfileOut( __METHOD__
);
1033 function magicLinkCallback( $m ) {
1034 if ( substr( $m[0], 0, 1 ) == '<' ) {
1037 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1039 $num = strtr( $isbn, array(
1044 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1045 $text = '<a href="' .
1046 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1047 "\" class=\"internal\">ISBN $isbn</a>";
1049 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1053 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1055 $urlmsg = 'pubmedurl';
1058 throw new MWException( __METHOD__
.': unrecognised match type "' .
1059 substr($m[0], 0, 20 ) . '"' );
1062 $url = wfMsg( $urlmsg, $id);
1063 $sk = $this->mOptions
->getSkin();
1064 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1065 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1071 * Parse headers and return html
1075 function doHeadings( $text ) {
1076 $fname = 'Parser::doHeadings';
1077 wfProfileIn( $fname );
1078 for ( $i = 6; $i >= 1; --$i ) {
1079 $h = str_repeat( '=', $i );
1080 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1081 "<h{$i}>\\1</h{$i}>\\2", $text );
1083 wfProfileOut( $fname );
1088 * Replace single quotes with HTML markup
1090 * @return string the altered text
1092 function doAllQuotes( $text ) {
1093 $fname = 'Parser::doAllQuotes';
1094 wfProfileIn( $fname );
1096 $lines = explode( "\n", $text );
1097 foreach ( $lines as $line ) {
1098 $outtext .= $this->doQuotes ( $line ) . "\n";
1100 $outtext = substr($outtext, 0,-1);
1101 wfProfileOut( $fname );
1106 * Helper function for doAllQuotes()
1108 public function doQuotes( $text ) {
1109 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1110 if ( count( $arr ) == 1 )
1114 # First, do some preliminary work. This may shift some apostrophes from
1115 # being mark-up to being text. It also counts the number of occurrences
1116 # of bold and italics mark-ups.
1120 foreach ( $arr as $r )
1122 if ( ( $i %
2 ) == 1 )
1124 # If there are ever four apostrophes, assume the first is supposed to
1125 # be text, and the remaining three constitute mark-up for bold text.
1126 if ( strlen( $arr[$i] ) == 4 )
1131 # If there are more than 5 apostrophes in a row, assume they're all
1132 # text except for the last 5.
1133 else if ( strlen( $arr[$i] ) > 5 )
1135 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1138 # Count the number of occurrences of bold and italics mark-ups.
1139 # We are not counting sequences of five apostrophes.
1140 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1141 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1142 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1147 # If there is an odd number of both bold and italics, it is likely
1148 # that one of the bold ones was meant to be an apostrophe followed
1149 # by italics. Which one we cannot know for certain, but it is more
1150 # likely to be one that has a single-letter word before it.
1151 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1154 $firstsingleletterword = -1;
1155 $firstmultiletterword = -1;
1157 foreach ( $arr as $r )
1159 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1161 $x1 = substr ($arr[$i-1], -1);
1162 $x2 = substr ($arr[$i-1], -2, 1);
1164 if ($firstspace == -1) $firstspace = $i;
1165 } else if ($x2 == ' ') {
1166 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1168 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1174 # If there is a single-letter word, use it!
1175 if ($firstsingleletterword > -1)
1177 $arr [ $firstsingleletterword ] = "''";
1178 $arr [ $firstsingleletterword-1 ] .= "'";
1180 # If not, but there's a multi-letter word, use that one.
1181 else if ($firstmultiletterword > -1)
1183 $arr [ $firstmultiletterword ] = "''";
1184 $arr [ $firstmultiletterword-1 ] .= "'";
1186 # ... otherwise use the first one that has neither.
1187 # (notice that it is possible for all three to be -1 if, for example,
1188 # there is only one pentuple-apostrophe in the line)
1189 else if ($firstspace > -1)
1191 $arr [ $firstspace ] = "''";
1192 $arr [ $firstspace-1 ] .= "'";
1196 # Now let's actually convert our apostrophic mush to HTML!
1201 foreach ($arr as $r)
1205 if ($state == 'both')
1212 if (strlen ($r) == 2)
1215 { $output .= '</i>'; $state = ''; }
1216 else if ($state == 'bi')
1217 { $output .= '</i>'; $state = 'b'; }
1218 else if ($state == 'ib')
1219 { $output .= '</b></i><b>'; $state = 'b'; }
1220 else if ($state == 'both')
1221 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1222 else # $state can be 'b' or ''
1223 { $output .= '<i>'; $state .= 'i'; }
1225 else if (strlen ($r) == 3)
1228 { $output .= '</b>'; $state = ''; }
1229 else if ($state == 'bi')
1230 { $output .= '</i></b><i>'; $state = 'i'; }
1231 else if ($state == 'ib')
1232 { $output .= '</b>'; $state = 'i'; }
1233 else if ($state == 'both')
1234 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1235 else # $state can be 'i' or ''
1236 { $output .= '<b>'; $state .= 'b'; }
1238 else if (strlen ($r) == 5)
1241 { $output .= '</b><i>'; $state = 'i'; }
1242 else if ($state == 'i')
1243 { $output .= '</i><b>'; $state = 'b'; }
1244 else if ($state == 'bi')
1245 { $output .= '</i></b>'; $state = ''; }
1246 else if ($state == 'ib')
1247 { $output .= '</b></i>'; $state = ''; }
1248 else if ($state == 'both')
1249 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1250 else # ($state == '')
1251 { $buffer = ''; $state = 'both'; }
1256 # Now close all remaining tags. Notice that the order is important.
1257 if ($state == 'b' ||
$state == 'ib')
1259 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1263 # There might be lonely ''''', so make sure we have a buffer
1264 if ($state == 'both' && $buffer)
1265 $output .= '<b><i>'.$buffer.'</i></b>';
1271 * Replace external links
1273 * Note: this is all very hackish and the order of execution matters a lot.
1274 * Make sure to run maintenance/parserTests.php if you change this code.
1278 function replaceExternalLinks( $text ) {
1280 $fname = 'Parser::replaceExternalLinks';
1281 wfProfileIn( $fname );
1283 $sk = $this->mOptions
->getSkin();
1285 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1287 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1290 while ( $i<count( $bits ) ) {
1292 $protocol = $bits[$i++
];
1293 $text = $bits[$i++
];
1294 $trail = $bits[$i++
];
1296 # The characters '<' and '>' (which were escaped by
1297 # removeHTMLtags()) should not be included in
1298 # URLs, per RFC 2396.
1300 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1301 $text = substr($url, $m2[0][1]) . ' ' . $text;
1302 $url = substr($url, 0, $m2[0][1]);
1305 # If the link text is an image URL, replace it with an <img> tag
1306 # This happened by accident in the original parser, but some people used it extensively
1307 $img = $this->maybeMakeExternalImage( $text );
1308 if ( $img !== false ) {
1314 # Set linktype for CSS - if URL==text, link is essentially free
1315 $linktype = ($text == $url) ?
'free' : 'text';
1317 # No link text, e.g. [http://domain.tld/some.link]
1318 if ( $text == '' ) {
1319 # Autonumber if allowed. See bug #5918
1320 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1321 $text = '[' . ++
$this->mAutonumber
. ']';
1322 $linktype = 'autonumber';
1324 # Otherwise just use the URL
1325 $text = htmlspecialchars( $url );
1329 # Have link text, e.g. [http://domain.tld/some.link text]s
1331 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1334 $text = $wgContLang->markNoConversion($text);
1336 $url = Sanitizer
::cleanUrl( $url );
1338 # Process the trail (i.e. everything after this link up until start of the next link),
1339 # replacing any non-bracketed links
1340 $trail = $this->replaceFreeExternalLinks( $trail );
1342 # Use the encoded URL
1343 # This means that users can paste URLs directly into the text
1344 # Funny characters like ö aren't valid in URLs anyway
1345 # This was changed in August 2004
1346 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1348 # Register link in the output object.
1349 # Replace unnecessary URL escape codes with the referenced character
1350 # This prevents spammers from hiding links from the filters
1351 $pasteurized = self
::replaceUnusualEscapes( $url );
1352 $this->mOutput
->addExternalLink( $pasteurized );
1355 wfProfileOut( $fname );
1360 * Replace anything that looks like a URL with a link
1363 function replaceFreeExternalLinks( $text ) {
1365 $fname = 'Parser::replaceFreeExternalLinks';
1366 wfProfileIn( $fname );
1368 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1369 $s = array_shift( $bits );
1372 $sk = $this->mOptions
->getSkin();
1374 while ( $i < count( $bits ) ){
1375 $protocol = $bits[$i++
];
1376 $remainder = $bits[$i++
];
1379 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1380 # Found some characters after the protocol that look promising
1381 $url = $protocol . $m[1];
1384 # special case: handle urls as url args:
1385 # http://www.example.com/foo?=http://www.example.com/bar
1386 if(strlen($trail) == 0 &&
1388 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1389 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1392 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1397 # The characters '<' and '>' (which were escaped by
1398 # removeHTMLtags()) should not be included in
1399 # URLs, per RFC 2396.
1401 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1402 $trail = substr($url, $m2[0][1]) . $trail;
1403 $url = substr($url, 0, $m2[0][1]);
1406 # Move trailing punctuation to $trail
1408 # If there is no left bracket, then consider right brackets fair game too
1409 if ( strpos( $url, '(' ) === false ) {
1413 $numSepChars = strspn( strrev( $url ), $sep );
1414 if ( $numSepChars ) {
1415 $trail = substr( $url, -$numSepChars ) . $trail;
1416 $url = substr( $url, 0, -$numSepChars );
1419 $url = Sanitizer
::cleanUrl( $url );
1421 # Is this an external image?
1422 $text = $this->maybeMakeExternalImage( $url );
1423 if ( $text === false ) {
1424 # Not an image, make a link
1425 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1426 # Register it in the output object...
1427 # Replace unnecessary URL escape codes with their equivalent characters
1428 $pasteurized = self
::replaceUnusualEscapes( $url );
1429 $this->mOutput
->addExternalLink( $pasteurized );
1431 $s .= $text . $trail;
1433 $s .= $protocol . $remainder;
1436 wfProfileOut( $fname );
1441 * Replace unusual URL escape codes with their equivalent characters
1445 * @todo This can merge genuinely required bits in the path or query string,
1446 * breaking legit URLs. A proper fix would treat the various parts of
1447 * the URL differently; as a workaround, just use the output for
1448 * statistical records, not for actual linking/output.
1450 static function replaceUnusualEscapes( $url ) {
1451 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1452 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1456 * Callback function used in replaceUnusualEscapes().
1457 * Replaces unusual URL escape codes with their equivalent character
1461 private static function replaceUnusualEscapesCallback( $matches ) {
1462 $char = urldecode( $matches[0] );
1463 $ord = ord( $char );
1464 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1465 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1466 // No, shouldn't be escaped
1469 // Yes, leave it escaped
1475 * make an image if it's allowed, either through the global
1476 * option or through the exception
1479 function maybeMakeExternalImage( $url ) {
1480 $sk = $this->mOptions
->getSkin();
1481 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1482 $imagesexception = !empty($imagesfrom);
1484 if ( $this->mOptions
->getAllowExternalImages()
1485 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1486 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1488 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1495 * Process [[ ]] wikilinks
1499 function replaceInternalLinks( $s ) {
1501 static $fname = 'Parser::replaceInternalLinks' ;
1503 wfProfileIn( $fname );
1505 wfProfileIn( $fname.'-setup' );
1507 # the % is needed to support urlencoded titles as well
1508 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1510 $sk = $this->mOptions
->getSkin();
1512 #split the entire text string on occurences of [[
1513 $a = explode( '[[', ' ' . $s );
1514 #get the first element (all text up to first [[), and remove the space we added
1515 $s = array_shift( $a );
1516 $s = substr( $s, 1 );
1518 # Match a link having the form [[namespace:link|alternate]]trail
1520 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1521 # Match cases where there is no "]]", which might still be images
1522 static $e1_img = FALSE;
1523 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1524 # Match the end of a line for a word that's not followed by whitespace,
1525 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1526 $e2 = wfMsgForContent( 'linkprefix' );
1528 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1529 if( is_null( $this->mTitle
) ) {
1530 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1532 $nottalk = !$this->mTitle
->isTalkPage();
1534 if ( $useLinkPrefixExtension ) {
1536 if ( preg_match( $e2, $s, $m ) ) {
1537 $first_prefix = $m[2];
1539 $first_prefix = false;
1545 if($wgContLang->hasVariants()) {
1546 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1548 $selflink = array($this->mTitle
->getPrefixedText());
1550 $useSubpages = $this->areSubpagesAllowed();
1551 wfProfileOut( $fname.'-setup' );
1553 # Loop for each link
1554 for ($k = 0; isset( $a[$k] ); $k++
) {
1556 if ( $useLinkPrefixExtension ) {
1557 wfProfileIn( $fname.'-prefixhandling' );
1558 if ( preg_match( $e2, $s, $m ) ) {
1566 $prefix = $first_prefix;
1567 $first_prefix = false;
1569 wfProfileOut( $fname.'-prefixhandling' );
1572 $might_be_img = false;
1574 wfProfileIn( "$fname-e1" );
1575 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1577 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1578 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1579 # the real problem is with the $e1 regex
1582 # Still some problems for cases where the ] is meant to be outside punctuation,
1583 # and no image is in sight. See bug 2095.
1586 substr( $m[3], 0, 1 ) === ']' &&
1587 strpos($text, '[') !== false
1590 $text .= ']'; # so that replaceExternalLinks($text) works later
1591 $m[3] = substr( $m[3], 1 );
1593 # fix up urlencoded title texts
1594 if( strpos( $m[1], '%' ) !== false ) {
1595 # Should anchors '#' also be rejected?
1596 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1599 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1600 $might_be_img = true;
1602 if ( strpos( $m[1], '%' ) !== false ) {
1603 $m[1] = urldecode($m[1]);
1606 } else { # Invalid form; output directly
1607 $s .= $prefix . '[[' . $line ;
1608 wfProfileOut( "$fname-e1" );
1611 wfProfileOut( "$fname-e1" );
1612 wfProfileIn( "$fname-misc" );
1614 # Don't allow internal links to pages containing
1615 # PROTO: where PROTO is a valid URL protocol; these
1616 # should be external links.
1617 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1618 $s .= $prefix . '[[' . $line ;
1622 # Make subpage if necessary
1623 if( $useSubpages ) {
1624 $link = $this->maybeDoSubpageLink( $m[1], $text );
1629 $noforce = (substr($m[1], 0, 1) != ':');
1631 # Strip off leading ':'
1632 $link = substr($link, 1);
1635 wfProfileOut( "$fname-misc" );
1636 wfProfileIn( "$fname-title" );
1637 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1639 $s .= $prefix . '[[' . $line;
1640 wfProfileOut( "$fname-title" );
1644 $ns = $nt->getNamespace();
1645 $iw = $nt->getInterWiki();
1646 wfProfileOut( "$fname-title" );
1648 if ($might_be_img) { # if this is actually an invalid link
1649 wfProfileIn( "$fname-might_be_img" );
1650 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1652 while (isset ($a[$k+
1]) ) {
1653 #look at the next 'line' to see if we can close it there
1654 $spliced = array_splice( $a, $k +
1, 1 );
1655 $next_line = array_shift( $spliced );
1656 $m = explode( ']]', $next_line, 3 );
1657 if ( count( $m ) == 3 ) {
1658 # the first ]] closes the inner link, the second the image
1660 $text .= "[[{$m[0]}]]{$m[1]}";
1663 } elseif ( count( $m ) == 2 ) {
1664 #if there's exactly one ]] that's fine, we'll keep looking
1665 $text .= "[[{$m[0]}]]{$m[1]}";
1667 #if $next_line is invalid too, we need look no further
1668 $text .= '[[' . $next_line;
1673 # we couldn't find the end of this imageLink, so output it raw
1674 #but don't ignore what might be perfectly normal links in the text we've examined
1675 $text = $this->replaceInternalLinks($text);
1676 $s .= "{$prefix}[[$link|$text";
1677 # note: no $trail, because without an end, there *is* no trail
1678 wfProfileOut( "$fname-might_be_img" );
1681 } else { #it's not an image, so output it raw
1682 $s .= "{$prefix}[[$link|$text";
1683 # note: no $trail, because without an end, there *is* no trail
1684 wfProfileOut( "$fname-might_be_img" );
1687 wfProfileOut( "$fname-might_be_img" );
1690 $wasblank = ( '' == $text );
1691 if( $wasblank ) $text = $link;
1693 # Link not escaped by : , create the various objects
1697 wfProfileIn( "$fname-interwiki" );
1698 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1699 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1700 $s = rtrim($s . $prefix);
1701 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1702 wfProfileOut( "$fname-interwiki" );
1705 wfProfileOut( "$fname-interwiki" );
1707 if ( $ns == NS_IMAGE
) {
1708 wfProfileIn( "$fname-image" );
1709 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1710 # recursively parse links inside the image caption
1711 # actually, this will parse them in any other parameters, too,
1712 # but it might be hard to fix that, and it doesn't matter ATM
1713 $text = $this->replaceExternalLinks($text);
1714 $text = $this->replaceInternalLinks($text);
1716 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1717 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1718 $this->mOutput
->addImage( $nt->getDBkey() );
1720 wfProfileOut( "$fname-image" );
1723 # We still need to record the image's presence on the page
1724 $this->mOutput
->addImage( $nt->getDBkey() );
1726 wfProfileOut( "$fname-image" );
1730 if ( $ns == NS_CATEGORY
) {
1731 wfProfileIn( "$fname-category" );
1732 $s = rtrim($s . "\n"); # bug 87
1735 $sortkey = $this->getDefaultSort();
1739 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1740 $sortkey = str_replace( "\n", '', $sortkey );
1741 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1742 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1745 * Strip the whitespace Category links produce, see bug 87
1746 * @todo We might want to use trim($tmp, "\n") here.
1748 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1750 wfProfileOut( "$fname-category" );
1755 # Self-link checking
1756 if( $nt->getFragment() === '' ) {
1757 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1758 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1763 # Special and Media are pseudo-namespaces; no pages actually exist in them
1764 if( $ns == NS_MEDIA
) {
1765 $link = $sk->makeMediaLinkObj( $nt, $text );
1766 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1767 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1768 $this->mOutput
->addImage( $nt->getDBkey() );
1770 } elseif( $ns == NS_SPECIAL
) {
1771 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1772 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1774 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1777 } elseif( $ns == NS_IMAGE
) {
1778 $img = wfFindFile( $nt );
1780 // Force a blue link if the file exists; may be a remote
1781 // upload on the shared repository, and we want to see its
1782 // auto-generated page.
1783 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1784 $this->mOutput
->addLink( $nt );
1788 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1790 wfProfileOut( $fname );
1795 * Make a link placeholder. The text returned can be later resolved to a real link with
1796 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1797 * parsing of interwiki links, and secondly to allow all existence checks and
1798 * article length checks (for stub links) to be bundled into a single query.
1801 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1802 wfProfileIn( __METHOD__
);
1803 if ( ! is_object($nt) ) {
1805 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1807 # Separate the link trail from the rest of the link
1808 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1810 if ( $nt->isExternal() ) {
1811 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1812 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1813 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1815 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1816 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1817 $this->mLinkHolders
['queries'][] = $query;
1818 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1819 $this->mLinkHolders
['titles'][] = $nt;
1821 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1824 wfProfileOut( __METHOD__
);
1829 * Render a forced-blue link inline; protect against double expansion of
1830 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1831 * Since this little disaster has to split off the trail text to avoid
1832 * breaking URLs in the following text without breaking trails on the
1833 * wiki links, it's been made into a horrible function.
1836 * @param string $text
1837 * @param string $query
1838 * @param string $trail
1839 * @param string $prefix
1840 * @return string HTML-wikitext mix oh yuck
1842 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1843 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1844 $sk = $this->mOptions
->getSkin();
1845 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1846 return $this->armorLinks( $link ) . $trail;
1850 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1851 * going to go through further parsing steps before inline URL expansion.
1853 * In particular this is important when using action=render, which causes
1854 * full URLs to be included.
1856 * Oh man I hate our multi-layer parser!
1858 * @param string more-or-less HTML
1859 * @return string less-or-more HTML with NOPARSE bits
1861 function armorLinks( $text ) {
1862 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1863 "{$this->mUniqPrefix}NOPARSE$1", $text );
1867 * Return true if subpage links should be expanded on this page.
1870 function areSubpagesAllowed() {
1871 # Some namespaces don't allow subpages
1872 global $wgNamespacesWithSubpages;
1873 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1877 * Handle link to subpage if necessary
1878 * @param string $target the source of the link
1879 * @param string &$text the link text, modified as necessary
1880 * @return string the full name of the link
1883 function maybeDoSubpageLink($target, &$text) {
1886 # :Foobar -- override special treatment of prefix (images, language links)
1887 # /Foobar -- convert to CurrentPage/Foobar
1888 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1889 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1890 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1892 $fname = 'Parser::maybeDoSubpageLink';
1893 wfProfileIn( $fname );
1894 $ret = $target; # default return value is no change
1896 # Some namespaces don't allow subpages,
1897 # so only perform processing if subpages are allowed
1898 if( $this->areSubpagesAllowed() ) {
1899 $hash = strpos( $target, '#' );
1900 if( $hash !== false ) {
1901 $suffix = substr( $target, $hash );
1902 $target = substr( $target, 0, $hash );
1907 $target = trim( $target );
1908 # Look at the first character
1909 if( $target != '' && $target{0} == '/' ) {
1910 # / at end means we don't want the slash to be shown
1912 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1913 if( $trailingSlashes ) {
1914 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1916 $noslash = substr( $target, 1 );
1919 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1920 if( '' === $text ) {
1921 $text = $target . $suffix;
1922 } # this might be changed for ugliness reasons
1924 # check for .. subpage backlinks
1926 $nodotdot = $target;
1927 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1929 $nodotdot = substr( $nodotdot, 3 );
1931 if($dotdotcount > 0) {
1932 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1933 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1934 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1935 # / at the end means don't show full path
1936 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1937 $nodotdot = substr( $nodotdot, 0, -1 );
1938 if( '' === $text ) {
1939 $text = $nodotdot . $suffix;
1942 $nodotdot = trim( $nodotdot );
1943 if( $nodotdot != '' ) {
1944 $ret .= '/' . $nodotdot;
1952 wfProfileOut( $fname );
1957 * Used by doBlockLevels()
1960 /* private */ function closeParagraph() {
1962 if ( '' != $this->mLastSection
) {
1963 $result = '</' . $this->mLastSection
. ">\n";
1965 $this->mInPre
= false;
1966 $this->mLastSection
= '';
1969 # getCommon() returns the length of the longest common substring
1970 # of both arguments, starting at the beginning of both.
1972 /* private */ function getCommon( $st1, $st2 ) {
1973 $fl = strlen( $st1 );
1974 $shorter = strlen( $st2 );
1975 if ( $fl < $shorter ) { $shorter = $fl; }
1977 for ( $i = 0; $i < $shorter; ++
$i ) {
1978 if ( $st1{$i} != $st2{$i} ) { break; }
1982 # These next three functions open, continue, and close the list
1983 # element appropriate to the prefix character passed into them.
1985 /* private */ function openList( $char ) {
1986 $result = $this->closeParagraph();
1988 if ( '*' == $char ) { $result .= '<ul><li>'; }
1989 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1990 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1991 else if ( ';' == $char ) {
1992 $result .= '<dl><dt>';
1993 $this->mDTopen
= true;
1995 else { $result = '<!-- ERR 1 -->'; }
2000 /* private */ function nextItem( $char ) {
2001 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2002 else if ( ':' == $char ||
';' == $char ) {
2004 if ( $this->mDTopen
) { $close = '</dt>'; }
2005 if ( ';' == $char ) {
2006 $this->mDTopen
= true;
2007 return $close . '<dt>';
2009 $this->mDTopen
= false;
2010 return $close . '<dd>';
2013 return '<!-- ERR 2 -->';
2016 /* private */ function closeList( $char ) {
2017 if ( '*' == $char ) { $text = '</li></ul>'; }
2018 else if ( '#' == $char ) { $text = '</li></ol>'; }
2019 else if ( ':' == $char ) {
2020 if ( $this->mDTopen
) {
2021 $this->mDTopen
= false;
2022 $text = '</dt></dl>';
2024 $text = '</dd></dl>';
2027 else { return '<!-- ERR 3 -->'; }
2033 * Make lists from lines starting with ':', '*', '#', etc.
2036 * @return string the lists rendered as HTML
2038 function doBlockLevels( $text, $linestart ) {
2039 $fname = 'Parser::doBlockLevels';
2040 wfProfileIn( $fname );
2042 # Parsing through the text line by line. The main thing
2043 # happening here is handling of block-level elements p, pre,
2044 # and making lists from lines starting with * # : etc.
2046 $textLines = explode( "\n", $text );
2048 $lastPrefix = $output = '';
2049 $this->mDTopen
= $inBlockElem = false;
2051 $paragraphStack = false;
2053 if ( !$linestart ) {
2054 $output .= array_shift( $textLines );
2056 foreach ( $textLines as $oLine ) {
2057 $lastPrefixLength = strlen( $lastPrefix );
2058 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2059 $preOpenMatch = preg_match('/<pre/i', $oLine );
2060 if ( !$this->mInPre
) {
2061 # Multiple prefixes may abut each other for nested lists.
2062 $prefixLength = strspn( $oLine, '*#:;' );
2063 $pref = substr( $oLine, 0, $prefixLength );
2066 $pref2 = str_replace( ';', ':', $pref );
2067 $t = substr( $oLine, $prefixLength );
2068 $this->mInPre
= !empty($preOpenMatch);
2070 # Don't interpret any other prefixes in preformatted text
2072 $pref = $pref2 = '';
2077 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2078 # Same as the last item, so no need to deal with nesting or opening stuff
2079 $output .= $this->nextItem( substr( $pref, -1 ) );
2080 $paragraphStack = false;
2082 if ( substr( $pref, -1 ) == ';') {
2083 # The one nasty exception: definition lists work like this:
2084 # ; title : definition text
2085 # So we check for : in the remainder text to split up the
2086 # title and definition, without b0rking links.
2088 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2090 $output .= $term . $this->nextItem( ':' );
2093 } elseif( $prefixLength ||
$lastPrefixLength ) {
2094 # Either open or close a level...
2095 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2096 $paragraphStack = false;
2098 while( $commonPrefixLength < $lastPrefixLength ) {
2099 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2100 --$lastPrefixLength;
2102 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2103 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2105 while ( $prefixLength > $commonPrefixLength ) {
2106 $char = substr( $pref, $commonPrefixLength, 1 );
2107 $output .= $this->openList( $char );
2109 if ( ';' == $char ) {
2110 # FIXME: This is dupe of code above
2111 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2113 $output .= $term . $this->nextItem( ':' );
2116 ++
$commonPrefixLength;
2118 $lastPrefix = $pref2;
2120 if( 0 == $prefixLength ) {
2121 wfProfileIn( "$fname-paragraph" );
2122 # No prefix (not in list)--go to paragraph mode
2123 // XXX: use a stack for nestable elements like span, table and div
2124 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2125 $closematch = preg_match(
2126 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2127 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2128 if ( $openmatch or $closematch ) {
2129 $paragraphStack = false;
2130 #Â TODO bug 5718: paragraph closed
2131 $output .= $this->closeParagraph();
2132 if ( $preOpenMatch and !$preCloseMatch ) {
2133 $this->mInPre
= true;
2135 if ( $closematch ) {
2136 $inBlockElem = false;
2138 $inBlockElem = true;
2140 } else if ( !$inBlockElem && !$this->mInPre
) {
2141 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2143 if ($this->mLastSection
!= 'pre') {
2144 $paragraphStack = false;
2145 $output .= $this->closeParagraph().'<pre>';
2146 $this->mLastSection
= 'pre';
2148 $t = substr( $t, 1 );
2151 if ( '' == trim($t) ) {
2152 if ( $paragraphStack ) {
2153 $output .= $paragraphStack.'<br />';
2154 $paragraphStack = false;
2155 $this->mLastSection
= 'p';
2157 if ($this->mLastSection
!= 'p' ) {
2158 $output .= $this->closeParagraph();
2159 $this->mLastSection
= '';
2160 $paragraphStack = '<p>';
2162 $paragraphStack = '</p><p>';
2166 if ( $paragraphStack ) {
2167 $output .= $paragraphStack;
2168 $paragraphStack = false;
2169 $this->mLastSection
= 'p';
2170 } else if ($this->mLastSection
!= 'p') {
2171 $output .= $this->closeParagraph().'<p>';
2172 $this->mLastSection
= 'p';
2177 wfProfileOut( "$fname-paragraph" );
2179 // somewhere above we forget to get out of pre block (bug 785)
2180 if($preCloseMatch && $this->mInPre
) {
2181 $this->mInPre
= false;
2183 if ($paragraphStack === false) {
2187 while ( $prefixLength ) {
2188 $output .= $this->closeList( $pref2{$prefixLength-1} );
2191 if ( '' != $this->mLastSection
) {
2192 $output .= '</' . $this->mLastSection
. '>';
2193 $this->mLastSection
= '';
2196 wfProfileOut( $fname );
2201 * Split up a string on ':', ignoring any occurences inside tags
2202 * to prevent illegal overlapping.
2203 * @param string $str the string to split
2204 * @param string &$before set to everything before the ':'
2205 * @param string &$after set to everything after the ':'
2206 * return string the position of the ':', or false if none found
2208 function findColonNoLinks($str, &$before, &$after) {
2209 $fname = 'Parser::findColonNoLinks';
2210 wfProfileIn( $fname );
2212 $pos = strpos( $str, ':' );
2213 if( $pos === false ) {
2215 wfProfileOut( $fname );
2219 $lt = strpos( $str, '<' );
2220 if( $lt === false ||
$lt > $pos ) {
2221 // Easy; no tag nesting to worry about
2222 $before = substr( $str, 0, $pos );
2223 $after = substr( $str, $pos+
1 );
2224 wfProfileOut( $fname );
2228 // Ugly state machine to walk through avoiding tags.
2229 $state = self
::COLON_STATE_TEXT
;
2231 $len = strlen( $str );
2232 for( $i = 0; $i < $len; $i++
) {
2236 // (Using the number is a performance hack for common cases)
2237 case 0: // self::COLON_STATE_TEXT:
2240 // Could be either a <start> tag or an </end> tag
2241 $state = self
::COLON_STATE_TAGSTART
;
2246 $before = substr( $str, 0, $i );
2247 $after = substr( $str, $i +
1 );
2248 wfProfileOut( $fname );
2251 // Embedded in a tag; don't break it.
2254 // Skip ahead looking for something interesting
2255 $colon = strpos( $str, ':', $i );
2256 if( $colon === false ) {
2257 // Nothing else interesting
2258 wfProfileOut( $fname );
2261 $lt = strpos( $str, '<', $i );
2262 if( $stack === 0 ) {
2263 if( $lt === false ||
$colon < $lt ) {
2265 $before = substr( $str, 0, $colon );
2266 $after = substr( $str, $colon +
1 );
2267 wfProfileOut( $fname );
2271 if( $lt === false ) {
2272 // Nothing else interesting to find; abort!
2273 // We're nested, but there's no close tags left. Abort!
2276 // Skip ahead to next tag start
2278 $state = self
::COLON_STATE_TAGSTART
;
2281 case 1: // self::COLON_STATE_TAG:
2286 $state = self
::COLON_STATE_TEXT
;
2289 // Slash may be followed by >?
2290 $state = self
::COLON_STATE_TAGSLASH
;
2296 case 2: // self::COLON_STATE_TAGSTART:
2299 $state = self
::COLON_STATE_CLOSETAG
;
2302 $state = self
::COLON_STATE_COMMENT
;
2305 // Illegal early close? This shouldn't happen D:
2306 $state = self
::COLON_STATE_TEXT
;
2309 $state = self
::COLON_STATE_TAG
;
2312 case 3: // self::COLON_STATE_CLOSETAG:
2317 wfDebug( "Invalid input in $fname; too many close tags\n" );
2318 wfProfileOut( $fname );
2321 $state = self
::COLON_STATE_TEXT
;
2324 case self
::COLON_STATE_TAGSLASH
:
2326 // Yes, a self-closed tag <blah/>
2327 $state = self
::COLON_STATE_TEXT
;
2329 // Probably we're jumping the gun, and this is an attribute
2330 $state = self
::COLON_STATE_TAG
;
2333 case 5: // self::COLON_STATE_COMMENT:
2335 $state = self
::COLON_STATE_COMMENTDASH
;
2338 case self
::COLON_STATE_COMMENTDASH
:
2340 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2342 $state = self
::COLON_STATE_COMMENT
;
2345 case self
::COLON_STATE_COMMENTDASHDASH
:
2347 $state = self
::COLON_STATE_TEXT
;
2349 $state = self
::COLON_STATE_COMMENT
;
2353 throw new MWException( "State machine error in $fname" );
2357 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2360 wfProfileOut( $fname );
2365 * Return value of a magic variable (like PAGENAME)
2369 function getVariableValue( $index ) {
2370 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2373 * Some of these require message or data lookups and can be
2374 * expensive to check many times.
2376 static $varCache = array();
2377 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2378 if ( isset( $varCache[$index] ) ) {
2379 return $varCache[$index];
2384 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2387 global $wgLocaltimezone;
2388 if ( isset( $wgLocaltimezone ) ) {
2389 $oldtz = getenv( 'TZ' );
2390 putenv( 'TZ='.$wgLocaltimezone );
2393 wfSuppressWarnings(); // E_STRICT system time bitching
2394 $localTimestamp = date( 'YmdHis', $ts );
2395 $localMonth = date( 'm', $ts );
2396 $localMonthName = date( 'n', $ts );
2397 $localDay = date( 'j', $ts );
2398 $localDay2 = date( 'd', $ts );
2399 $localDayOfWeek = date( 'w', $ts );
2400 $localWeek = date( 'W', $ts );
2401 $localYear = date( 'Y', $ts );
2402 $localHour = date( 'H', $ts );
2403 if ( isset( $wgLocaltimezone ) ) {
2404 putenv( 'TZ='.$oldtz );
2406 wfRestoreWarnings();
2409 case 'currentmonth':
2410 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2411 case 'currentmonthname':
2412 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2413 case 'currentmonthnamegen':
2414 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2415 case 'currentmonthabbrev':
2416 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2418 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2420 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2422 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2423 case 'localmonthname':
2424 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2425 case 'localmonthnamegen':
2426 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2427 case 'localmonthabbrev':
2428 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2430 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2432 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2434 return wfEscapeWikiText( $this->mTitle
->getText() );
2436 return $this->mTitle
->getPartialURL();
2437 case 'fullpagename':
2438 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2439 case 'fullpagenamee':
2440 return $this->mTitle
->getPrefixedURL();
2442 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2443 case 'subpagenamee':
2444 return $this->mTitle
->getSubpageUrlForm();
2445 case 'basepagename':
2446 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2447 case 'basepagenamee':
2448 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2449 case 'talkpagename':
2450 if( $this->mTitle
->canTalk() ) {
2451 $talkPage = $this->mTitle
->getTalkPage();
2452 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2456 case 'talkpagenamee':
2457 if( $this->mTitle
->canTalk() ) {
2458 $talkPage = $this->mTitle
->getTalkPage();
2459 return $talkPage->getPrefixedUrl();
2463 case 'subjectpagename':
2464 $subjPage = $this->mTitle
->getSubjectPage();
2465 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2466 case 'subjectpagenamee':
2467 $subjPage = $this->mTitle
->getSubjectPage();
2468 return $subjPage->getPrefixedUrl();
2470 return $this->mRevisionId
;
2472 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2473 case 'revisionday2':
2474 return substr( $this->getRevisionTimestamp(), 6, 2 );
2475 case 'revisionmonth':
2476 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2477 case 'revisionyear':
2478 return substr( $this->getRevisionTimestamp(), 0, 4 );
2479 case 'revisiontimestamp':
2480 return $this->getRevisionTimestamp();
2482 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2484 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2486 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2488 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2489 case 'subjectspace':
2490 return $this->mTitle
->getSubjectNsText();
2491 case 'subjectspacee':
2492 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2493 case 'currentdayname':
2494 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2496 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2498 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2500 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2502 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2503 // int to remove the padding
2504 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2506 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2507 case 'localdayname':
2508 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2510 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2512 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2514 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2516 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2517 // int to remove the padding
2518 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2520 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2521 case 'numberofarticles':
2522 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2523 case 'numberoffiles':
2524 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2525 case 'numberofusers':
2526 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2527 case 'numberofpages':
2528 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2529 case 'numberofadmins':
2530 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2531 case 'numberofedits':
2532 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2533 case 'currenttimestamp':
2534 return $varCache[$index] = wfTimestampNow();
2535 case 'localtimestamp':
2536 return $varCache[$index] = $localTimestamp;
2537 case 'currentversion':
2538 return $varCache[$index] = SpecialVersion
::getVersion();
2544 return $wgServerName;
2546 return $wgScriptPath;
2547 case 'directionmark':
2548 return $wgContLang->getDirMark();
2549 case 'contentlanguage':
2550 global $wgContLanguageCode;
2551 return $wgContLanguageCode;
2554 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2562 * initialise the magic variables (like CURRENTMONTHNAME)
2566 function initialiseVariables() {
2567 $fname = 'Parser::initialiseVariables';
2568 wfProfileIn( $fname );
2569 $variableIDs = MagicWord
::getVariableIDs();
2571 $this->mVariables
= array();
2572 foreach ( $variableIDs as $id ) {
2573 $mw =& MagicWord
::get( $id );
2574 $mw->addToArray( $this->mVariables
, $id );
2576 wfProfileOut( $fname );
2580 * parse any parentheses in format ((title|part|part))
2581 * and call callbacks to get a replacement text for any found piece
2583 * @param string $text The text to parse
2584 * @param array $callbacks rules in form:
2585 * '{' => array( # opening parentheses
2586 * 'end' => '}', # closing parentheses
2587 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2588 * 3 => callback # replacement callback to call if {{{..}}} is found
2591 * 'min' => 2, # Minimum parenthesis count in cb
2592 * 'max' => 3, # Maximum parenthesis count in cb
2595 function replace_callback ($text, $callbacks) {
2596 wfProfileIn( __METHOD__
);
2597 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2598 $lastOpeningBrace = -1; # last not closed parentheses
2600 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2603 while ( $i < strlen( $text ) ) {
2604 # Find next opening brace, closing brace or pipe
2605 if ( $lastOpeningBrace == -1 ) {
2606 $currentClosing = '';
2607 $search = $validOpeningBraces;
2609 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2610 $search = $validOpeningBraces . '|' . $currentClosing;
2613 $i +
= strcspn( $text, $search, $i );
2614 if ( $i < strlen( $text ) ) {
2615 if ( $text[$i] == '|' ) {
2617 } elseif ( $text[$i] == $currentClosing ) {
2619 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2621 $rule = $callbacks[$text[$i]];
2623 # Some versions of PHP have a strcspn which stops on null characters
2624 # Ignore and continue
2633 if ( $found == 'open' ) {
2634 # found opening brace, let's add it to parentheses stack
2635 $piece = array('brace' => $text[$i],
2636 'braceEnd' => $rule['end'],
2640 # count opening brace characters
2641 $piece['count'] = strspn( $text, $piece['brace'], $i );
2642 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2643 $i +
= $piece['count'];
2645 # we need to add to stack only if opening brace count is enough for one of the rules
2646 if ( $piece['count'] >= $rule['min'] ) {
2647 $lastOpeningBrace ++
;
2648 $openingBraceStack[$lastOpeningBrace] = $piece;
2650 } elseif ( $found == 'close' ) {
2651 # lets check if it is enough characters for closing brace
2652 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2653 $count = strspn( $text, $text[$i], $i, $maxCount );
2655 # check for maximum matching characters (if there are 5 closing
2656 # characters, we will probably need only 3 - depending on the rules)
2658 $matchingCallback = null;
2659 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2660 if ( $count > $cbType['max'] ) {
2661 # The specified maximum exists in the callback array, unless the caller
2663 $matchingCount = $cbType['max'];
2665 # Count is less than the maximum
2666 # Skip any gaps in the callback array to find the true largest match
2667 # Need to use array_key_exists not isset because the callback can be null
2668 $matchingCount = $count;
2669 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2674 if ($matchingCount <= 0) {
2678 $matchingCallback = $cbType['cb'][$matchingCount];
2680 # let's set a title or last part (if '|' was found)
2681 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2682 $openingBraceStack[$lastOpeningBrace]['title'] =
2683 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2684 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2686 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2687 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2688 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2691 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2692 $pieceEnd = $i +
$matchingCount;
2694 if( is_callable( $matchingCallback ) ) {
2696 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2697 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2698 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2699 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2701 # finally we can call a user callback and replace piece of text
2702 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2703 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2704 $i = $pieceStart +
strlen($replaceWith);
2706 # null value for callback means that parentheses should be parsed, but not replaced
2707 $i +
= $matchingCount;
2710 # reset last opening parentheses, but keep it in case there are unused characters
2711 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2712 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2713 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2716 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2717 $openingBraceStack[$lastOpeningBrace--] = null;
2719 if ($matchingCount < $piece['count']) {
2720 $piece['count'] -= $matchingCount;
2721 $piece['startAt'] -= $matchingCount;
2722 $piece['partStart'] = $piece['startAt'];
2723 # do we still qualify for any callback with remaining count?
2724 $currentCbList = $callbacks[$piece['brace']]['cb'];
2725 while ( $piece['count'] ) {
2726 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2727 $lastOpeningBrace++
;
2728 $openingBraceStack[$lastOpeningBrace] = $piece;
2734 } elseif ( $found == 'pipe' ) {
2735 # lets set a title if it is a first separator, or next part otherwise
2736 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2737 $openingBraceStack[$lastOpeningBrace]['title'] =
2738 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2739 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2740 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2742 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2743 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2744 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2746 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2750 wfProfileOut( __METHOD__
);
2755 * Replace magic variables, templates, and template arguments
2756 * with the appropriate text. Templates are substituted recursively,
2757 * taking care to avoid infinite loops.
2759 * Note that the substitution depends on value of $mOutputType:
2760 * OT_WIKI: only {{subst:}} templates
2761 * OT_MSG: only magic variables
2762 * OT_HTML: all templates and magic variables
2764 * @param string $tex The text to transform
2765 * @param array $args Key-value pairs representing template parameters to substitute
2766 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2769 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2770 # Prevent too big inclusions
2771 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2775 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2776 wfProfileIn( $fname );
2778 # This function is called recursively. To keep track of arguments we need a stack:
2779 array_push( $this->mArgStack
, $args );
2781 $braceCallbacks = array();
2783 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2785 if ( $this->mOutputType
!= OT_MSG
) {
2786 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2788 if ( $braceCallbacks ) {
2792 'cb' => $braceCallbacks,
2793 'min' => $argsOnly ?
3 : 2,
2794 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2798 'cb' => array(2=>null),
2803 $text = $this->replace_callback ($text, $callbacks);
2805 array_pop( $this->mArgStack
);
2807 wfProfileOut( $fname );
2812 * Replace magic variables
2815 function variableSubstitution( $matches ) {
2817 $fname = 'Parser::variableSubstitution';
2818 $varname = $wgContLang->lc($matches[1]);
2819 wfProfileIn( $fname );
2821 if ( $this->mOutputType
== OT_WIKI
) {
2822 # Do only magic variables prefixed by SUBST
2823 $mwSubst =& MagicWord
::get( 'subst' );
2824 if (!$mwSubst->matchStartAndRemove( $varname ))
2826 # Note that if we don't substitute the variable below,
2827 # we don't remove the {{subst:}} magic word, in case
2828 # it is a template rather than a magic variable.
2830 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2831 $id = $this->mVariables
[$varname];
2832 # Now check if we did really match, case sensitive or not
2833 $mw =& MagicWord
::get( $id );
2834 if ($mw->match($matches[1])) {
2835 $text = $this->getVariableValue( $id );
2836 $this->mOutput
->mContainsOldMagic
= true;
2838 $text = $matches[0];
2841 $text = $matches[0];
2843 wfProfileOut( $fname );
2848 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2849 static function createAssocArgs( $args ) {
2850 $assocArgs = array();
2852 foreach( $args as $arg ) {
2853 $eqpos = strpos( $arg, '=' );
2854 if ( $eqpos === false ) {
2855 $assocArgs[$index++
] = $arg;
2857 $name = trim( substr( $arg, 0, $eqpos ) );
2858 $value = trim( substr( $arg, $eqpos+
1 ) );
2859 if ( $value === false ) {
2862 if ( $name !== false ) {
2863 $assocArgs[$name] = $value;
2872 * Return the text of a template, after recursively
2873 * replacing any variables or templates within the template.
2875 * @param array $piece The parts of the template
2876 * $piece['text']: matched text
2877 * $piece['title']: the title, i.e. the part before the |
2878 * $piece['parts']: the parameter array
2879 * @return string the text of the template
2882 function braceSubstitution( $piece ) {
2883 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2884 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2885 wfProfileIn( $fname );
2886 wfProfileIn( __METHOD__
.'-setup' );
2889 $found = false; # $text has been filled
2890 $nowiki = false; # wiki markup in $text should be escaped
2891 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2892 $noargs = false; # Don't replace triple-brace arguments in $text
2893 $replaceHeadings = false; # Make the edit section links go to the template not the article
2894 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2895 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2896 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2898 # Title object, where $text came from
2904 # $part1 is the bit before the first |, and must contain only title characters
2905 # $args is a list of arguments, starting from index 0, not including $part1
2907 $titleText = $part1 = $piece['title'];
2908 # If the third subpattern matched anything, it will start with |
2910 if (null == $piece['parts']) {
2911 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2912 if ($replaceWith != $piece['text']) {
2913 $text = $replaceWith;
2920 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2921 wfProfileOut( __METHOD__
.'-setup' );
2924 wfProfileIn( __METHOD__
.'-modifiers' );
2926 $mwSubst =& MagicWord
::get( 'subst' );
2927 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2928 # One of two possibilities is true:
2929 # 1) Found SUBST but not in the PST phase
2930 # 2) Didn't find SUBST and in the PST phase
2931 # In either case, return without further processing
2932 $text = $piece['text'];
2939 # MSG, MSGNW and RAW
2942 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2943 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2946 # Remove obsolete MSG:
2947 $mwMsg =& MagicWord
::get( 'msg' );
2948 $mwMsg->matchStartAndRemove( $part1 );
2952 $mwRaw =& MagicWord
::get( 'raw' );
2953 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2954 $forceRawInterwiki = true;
2957 wfProfileOut( __METHOD__
.'-modifiers' );
2959 //save path level before recursing into functions & templates.
2960 $lastPathLevel = $this->mTemplatePath
;
2964 wfProfileIn( __METHOD__
. '-pfunc' );
2966 $colonPos = strpos( $part1, ':' );
2967 if ( $colonPos !== false ) {
2968 # Case sensitive functions
2969 $function = substr( $part1, 0, $colonPos );
2970 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2971 $function = $this->mFunctionSynonyms
[1][$function];
2973 # Case insensitive functions
2974 $function = strtolower( $function );
2975 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2976 $function = $this->mFunctionSynonyms
[0][$function];
2982 $funcArgs = array_map( 'trim', $args );
2983 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2984 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2987 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2991 if ( is_array( $result ) ) {
2992 if ( isset( $result[0] ) ) {
2993 $text = $linestart . $result[0];
2994 unset( $result[0] );
2997 // Extract flags into the local scope
2998 // This allows callers to set flags such as nowiki, noparse, found, etc.
3001 $text = $linestart . $result;
3005 wfProfileOut( __METHOD__
. '-pfunc' );
3008 # Template table test
3010 # Did we encounter this template already? If yes, it is in the cache
3011 # and we need to check for loops.
3012 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3015 # Infinite loop test
3016 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3020 $text = $linestart .
3021 "[[$part1]]<!-- WARNING: template loop detected -->";
3022 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3024 # set $text to cached message.
3025 $text = $linestart . $this->mTemplates
[$piece['title']];
3026 #treat title for cached page the same as others
3029 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3030 if ($subpage !== '') {
3031 $ns = $this->mTitle
->getNamespace();
3033 $title = Title
::newFromText( $part1, $ns );
3034 //used by include size checking
3035 $titleText = $title->getPrefixedText();
3036 //used by edit section links
3037 $replaceHeadings = true;
3042 # Load from database
3044 wfProfileIn( __METHOD__
. '-loadtpl' );
3046 # declaring $subpage directly in the function call
3047 # does not work correctly with references and breaks
3048 # {{/subpage}}-style inclusions
3050 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3051 if ($subpage !== '') {
3052 $ns = $this->mTitle
->getNamespace();
3054 $title = Title
::newFromText( $part1, $ns );
3057 if ( !is_null( $title ) ) {
3058 $titleText = $title->getPrefixedText();
3059 # Check for language variants if the template is not found
3060 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3061 $wgContLang->findVariantLink($part1, $title);
3064 if ( !$title->isExternal() ) {
3065 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3066 $text = SpecialPage
::capturePath( $title );
3067 if ( is_string( $text ) ) {
3072 $this->disableCache();
3074 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3075 $found = false; //access denied
3076 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3078 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3079 if ( $articleContent !== false ) {
3081 $text = $articleContent;
3082 $replaceHeadings = true;
3086 # If the title is valid but undisplayable, make a link to it
3087 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3088 $text = "[[:$titleText]]";
3091 } elseif ( $title->isTrans() ) {
3092 // Interwiki transclusion
3093 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3094 $text = $this->interwikiTransclude( $title, 'render' );
3098 $text = $this->interwikiTransclude( $title, 'raw' );
3099 $replaceHeadings = true;
3104 # Template cache array insertion
3105 # Use the original $piece['title'] not the mangled $part1, so that
3106 # modifiers such as RAW: produce separate cache entries
3109 // A special page; don't store it in the template cache.
3111 $this->mTemplates
[$piece['title']] = $text;
3113 $text = $linestart . $text;
3116 wfProfileOut( __METHOD__
. '-loadtpl' );
3119 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3120 # Error, oversize inclusion
3121 $text = $linestart .
3122 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3127 # Recursive parsing, escaping and link table handling
3128 # Only for HTML output
3129 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3130 $text = wfEscapeWikiText( $text );
3131 } elseif ( !$this->ot
['msg'] && $found ) {
3133 $assocArgs = array();
3135 # Clean up argument array
3136 $assocArgs = self
::createAssocArgs($args);
3137 # Add a new element to the templace recursion path
3138 $this->mTemplatePath
[$part1] = 1;
3142 # If there are any <onlyinclude> tags, only include them
3143 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3144 $replacer = new OnlyIncludeReplacer
;
3145 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3146 array( &$replacer, 'replace' ), $text );
3147 $text = $replacer->output
;
3149 # Remove <noinclude> sections and <includeonly> tags
3150 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3151 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3153 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3154 # Strip <nowiki>, <pre>, etc.
3155 $text = $this->strip( $text, $this->mStripState
);
3156 if ( $this->ot
['html'] ) {
3157 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3158 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3159 $text = Sanitizer
::removeHTMLcomments( $text );
3162 $text = $this->replaceVariables( $text, $assocArgs );
3164 # If the template begins with a table or block-level
3165 # element, it should be treated as beginning a new line.
3166 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3167 $text = "\n" . $text;
3169 } elseif ( !$noargs ) {
3170 # $noparse and !$noargs
3171 # Just replace the arguments, not any double-brace items
3172 # This is used for rendered interwiki transclusion
3173 $text = $this->replaceVariables( $text, $assocArgs, true );
3176 # Prune lower levels off the recursion check path
3177 $this->mTemplatePath
= $lastPathLevel;
3179 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3180 # Error, oversize inclusion
3181 $text = $linestart .
3182 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3188 wfProfileOut( $fname );
3189 return $piece['text'];
3191 wfProfileIn( __METHOD__
. '-placeholders' );
3193 # Replace raw HTML by a placeholder
3194 # Add a blank line preceding, to prevent it from mucking up
3195 # immediately preceding headings
3196 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3198 # replace ==section headers==
3199 # XXX this needs to go away once we have a better parser.
3200 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3201 if( !is_null( $title ) )
3202 $encodedname = base64_encode($title->getPrefixedDBkey());
3204 $encodedname = base64_encode("");
3205 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3206 PREG_SPLIT_DELIM_CAPTURE
);
3208 $nsec = $headingOffset;
3210 for( $i = 0; $i < count($m); $i +
= 2 ) {
3212 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3214 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3219 preg_match('/^(={1,6})(.*?)(={1,6}\s*?)$/m', $hl, $m2);
3220 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3221 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3227 wfProfileOut( __METHOD__
. '-placeholders' );
3230 # Prune lower levels off the recursion check path
3231 $this->mTemplatePath
= $lastPathLevel;
3234 wfProfileOut( $fname );
3235 return $piece['text'];
3237 wfProfileOut( $fname );
3243 * Fetch the unparsed text of a template and register a reference to it.
3245 function fetchTemplateAndTitle( $title ) {
3246 $templateCb = $this->mOptions
->getTemplateCallback();
3247 $stuff = call_user_func( $templateCb, $title );
3248 $text = $stuff['text'];
3249 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3250 if ( isset( $stuff['deps'] ) ) {
3251 foreach ( $stuff['deps'] as $dep ) {
3252 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3255 return array($text,$finalTitle);
3258 function fetchTemplate( $title ) {
3259 $rv = $this->fetchTemplateAndtitle($title);
3264 * Static function to get a template
3265 * Can be overridden via ParserOptions::setTemplateCallback().
3267 * Returns an associative array:
3268 * text The unparsed template text
3269 * finalTitle (Optional) The title after following redirects
3270 * deps (Optional) An array of associative array dependencies:
3271 * title: The dependency title, to be registered in templatelinks
3272 * page_id: The page_id of the title
3273 * rev_id: The revision ID loaded
3275 static function statelessFetchTemplate( $title ) {
3276 $text = $skip = false;
3277 $finalTitle = $title;
3280 // Loop to fetch the article, with up to 1 redirect
3281 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3282 # Give extensions a chance to select the revision instead
3283 $id = false; // Assume current
3284 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3290 'page_id' => $title->getArticleID(),
3294 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3295 $rev_id = $rev ?
$rev->getId() : 0;
3299 'page_id' => $title->getArticleID(),
3300 'rev_id' => $rev_id );
3303 $text = $rev->getText();
3304 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3306 $message = $wgLang->lcfirst( $title->getText() );
3307 $text = wfMsgForContentNoTrans( $message );
3308 if( wfEmptyMsg( $message, $text ) ) {
3315 if ( $text === false ) {
3319 $finalTitle = $title;
3320 $title = Title
::newFromRedirect( $text );
3324 'finalTitle' => $finalTitle,
3329 * Transclude an interwiki link.
3331 function interwikiTransclude( $title, $action ) {
3332 global $wgEnableScaryTranscluding;
3334 if (!$wgEnableScaryTranscluding)
3335 return wfMsg('scarytranscludedisabled');
3337 $url = $title->getFullUrl( "action=$action" );
3339 if (strlen($url) > 255)
3340 return wfMsg('scarytranscludetoolong');
3341 return $this->fetchScaryTemplateMaybeFromCache($url);
3344 function fetchScaryTemplateMaybeFromCache($url) {
3345 global $wgTranscludeCacheExpiry;
3346 $dbr = wfGetDB(DB_SLAVE
);
3347 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3348 array('tc_url' => $url));
3350 $time = $obj->tc_time
;
3351 $text = $obj->tc_contents
;
3352 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3357 $text = Http
::get($url);
3359 return wfMsg('scarytranscludefailed', $url);
3361 $dbw = wfGetDB(DB_MASTER
);
3362 $dbw->replace('transcache', array('tc_url'), array(
3364 'tc_time' => time(),
3365 'tc_contents' => $text));
3371 * Triple brace replacement -- used for template arguments
3374 function argSubstitution( $matches ) {
3375 $arg = trim( $matches['title'] );
3376 $text = $matches['text'];
3377 $inputArgs = end( $this->mArgStack
);
3379 if ( array_key_exists( $arg, $inputArgs ) ) {
3380 $text = $inputArgs[$arg];
3381 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3382 null != $matches['parts'] && count($matches['parts']) > 0) {
3383 $text = $matches['parts'][0];
3385 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3386 $text = $matches['text'] .
3387 '<!-- WARNING: argument omitted, expansion size too large -->';
3394 * Increment an include size counter
3396 * @param string $type The type of expansion
3397 * @param integer $size The size of the text
3398 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3400 function incrementIncludeSize( $type, $size ) {
3401 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3404 $this->mIncludeSizes
[$type] +
= $size;
3410 * Detect __NOGALLERY__ magic word and set a placeholder
3412 function stripNoGallery( &$text ) {
3413 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3415 $mw = MagicWord
::get( 'nogallery' );
3416 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3420 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3421 * placeholder that will then be replaced by the real TOC in
3422 * ->formatHeadings, this works because at this points real
3423 * comments will have already been discarded by the sanitizer.
3425 * Any additional __TOC__ magic words left over will be discarded
3426 * as there can only be one TOC on the page.
3428 function stripToc( $text ) {
3429 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3431 $mw = MagicWord
::get( 'notoc' );
3432 if( $mw->matchAndRemove( $text ) ) {
3433 $this->mShowToc
= false;
3436 $mw = MagicWord
::get( 'toc' );
3437 if( $mw->match( $text ) ) {
3438 $this->mShowToc
= true;
3439 $this->mForceTocPosition
= true;
3441 // Set a placeholder. At the end we'll fill it in with the TOC.
3442 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3444 // Only keep the first one.
3445 $text = $mw->replace( '', $text );
3451 * This function accomplishes several tasks:
3452 * 1) Auto-number headings if that option is enabled
3453 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3454 * 3) Add a Table of contents on the top for users who have enabled the option
3455 * 4) Auto-anchor headings
3457 * It loops through all headlines, collects the necessary data, then splits up the
3458 * string and re-inserts the newly formatted headlines.
3460 * @param string $text
3461 * @param boolean $isMain
3464 function formatHeadings( $text, $isMain=true ) {
3465 global $wgMaxTocLevel, $wgContLang;
3467 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3468 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3471 $showEditLink = $this->mOptions
->getEditSection();
3474 # Inhibit editsection links if requested in the page
3475 $esw =& MagicWord
::get( 'noeditsection' );
3476 if( $esw->matchAndRemove( $text ) ) {
3480 # Get all headlines for numbering them and adding funky stuff like [edit]
3481 # links - this is for later, but we need the number of headlines right now
3483 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3485 # if there are fewer than 4 headlines in the article, do not show TOC
3486 # unless it's been explicitly enabled.
3487 $enoughToc = $this->mShowToc
&&
3488 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3490 # Allow user to stipulate that a page should have a "new section"
3491 # link added via __NEWSECTIONLINK__
3492 $mw =& MagicWord
::get( 'newsectionlink' );
3493 if( $mw->matchAndRemove( $text ) )
3494 $this->mOutput
->setNewSection( true );
3496 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3497 # override above conditions and always show TOC above first header
3498 $mw =& MagicWord
::get( 'forcetoc' );
3499 if ($mw->matchAndRemove( $text ) ) {
3500 $this->mShowToc
= true;
3504 # We need this to perform operations on the HTML
3505 $sk = $this->mOptions
->getSkin();
3509 $sectionCount = 0; # headlineCount excluding template sections
3512 # Ugh .. the TOC should have neat indentation levels which can be
3513 # passed to the skin functions. These are determined here
3517 $sublevelCount = array();
3518 $levelCount = array();
3525 foreach( $matches[3] as $headline ) {
3527 $templatetitle = '';
3528 $templatesection = 0;
3531 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3533 $templatetitle = base64_decode($mat[1]);
3534 $templatesection = 1 +
(int)base64_decode($mat[2]);
3535 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3539 $prevlevel = $level;
3540 $prevtoclevel = $toclevel;
3542 $level = $matches[1][$headlineCount];
3544 if( $doNumberHeadings ||
$enoughToc ) {
3546 if ( $level > $prevlevel ) {
3547 # Increase TOC level
3549 $sublevelCount[$toclevel] = 0;
3550 if( $toclevel<$wgMaxTocLevel ) {
3551 $prevtoclevel = $toclevel;
3552 $toc .= $sk->tocIndent();
3556 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3557 # Decrease TOC level, find level to jump to
3559 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3560 # Can only go down to level 1
3563 for ($i = $toclevel; $i > 0; $i--) {
3564 if ( $levelCount[$i] == $level ) {
3565 # Found last matching level
3569 elseif ( $levelCount[$i] < $level ) {
3570 # Found first matching level below current level
3576 if( $toclevel<$wgMaxTocLevel ) {
3577 if($prevtoclevel < $wgMaxTocLevel) {
3578 # Unindent only if the previous toc level was shown :p
3579 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3581 $toc .= $sk->tocLineEnd();
3586 # No change in level, end TOC line
3587 if( $toclevel<$wgMaxTocLevel ) {
3588 $toc .= $sk->tocLineEnd();
3592 $levelCount[$toclevel] = $level;
3594 # count number of headlines for each level
3595 @$sublevelCount[$toclevel]++
;
3597 for( $i = 1; $i <= $toclevel; $i++
) {
3598 if( !empty( $sublevelCount[$i] ) ) {
3602 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3608 # The canonized header is a version of the header text safe to use for links
3609 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3610 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3612 # Remove link placeholders by the link text.
3613 # <!--LINK number-->
3615 # link text with suffix
3616 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3617 "\$this->mLinkHolders['texts'][\$1]",
3618 $canonized_headline );
3619 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3620 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3621 $canonized_headline );
3623 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3624 $tocline = preg_replace(
3625 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3629 $tocline = trim( $tocline );
3631 # For the anchor, strip out HTML-y stuff period
3632 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3633 $canonized_headline = trim( $canonized_headline );
3635 # Save headline for section edit hint before it's escaped
3636 $headline_hint = $canonized_headline;
3637 $canonized_headline = Sanitizer
::escapeId( $canonized_headline );
3638 $refers[$headlineCount] = $canonized_headline;
3640 # count how many in assoc. array so we can track dupes in anchors
3641 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3642 $refcount[$headlineCount]=$refers[$canonized_headline];
3644 # Don't number the heading if it is the only one (looks silly)
3645 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3646 # the two are different if the line contains a link
3647 $headline=$numbering . ' ' . $headline;
3650 # Create the anchor for linking from the TOC to the section
3651 $anchor = $canonized_headline;
3652 if($refcount[$headlineCount] > 1 ) {
3653 $anchor .= '_' . $refcount[$headlineCount];
3655 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3656 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3658 # give headline the correct <h#> tag
3659 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3661 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3663 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3667 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3674 # Never ever show TOC if no headers
3675 if( $numVisible < 1 ) {
3680 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3681 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3683 $toc = $sk->tocList( $toc );
3686 # split up and insert constructed headlines
3688 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3691 foreach( $blocks as $block ) {
3692 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3693 # This is the [edit] link that appears for the top block of text when
3694 # section editing is enabled
3696 # Disabled because it broke block formatting
3697 # For example, a bullet point in the top line
3698 # $full .= $sk->editSectionLink(0);
3701 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3702 # Top anchor now in skin
3706 if( !empty( $head[$i] ) ) {
3711 if( $this->mForceTocPosition
) {
3712 return str_replace( '<!--MWTOC-->', $toc, $full );
3719 * Transform wiki markup when saving a page by doing \r\n -> \n
3720 * conversion, substitting signatures, {{subst:}} templates, etc.
3722 * @param string $text the text to transform
3723 * @param Title &$title the Title object for the current article
3724 * @param User &$user the User object describing the current user
3725 * @param ParserOptions $options parsing options
3726 * @param bool $clearState whether to clear the parser state first
3727 * @return string the altered wiki markup
3730 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3731 $this->mOptions
= $options;
3732 $this->mTitle
=& $title;
3733 $this->setOutputType( OT_WIKI
);
3735 if ( $clearState ) {
3736 $this->clearState();
3739 $stripState = new StripState
;
3743 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3744 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3745 $text = $this->pstPass2( $text, $stripState, $user );
3746 $text = $stripState->unstripBoth( $text );
3751 * Pre-save transform helper function
3754 function pstPass2( $text, &$stripState, $user ) {
3755 global $wgContLang, $wgLocaltimezone;
3757 /* Note: This is the timestamp saved as hardcoded wikitext to
3758 * the database, we use $wgContLang here in order to give
3759 * everyone the same signature and use the default one rather
3760 * than the one selected in each user's preferences.
3762 if ( isset( $wgLocaltimezone ) ) {
3763 $oldtz = getenv( 'TZ' );
3764 putenv( 'TZ='.$wgLocaltimezone );
3766 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3767 ' (' . date( 'T' ) . ')';
3768 if ( isset( $wgLocaltimezone ) ) {
3769 putenv( 'TZ='.$oldtz );
3772 # Variable replacement
3773 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3774 $text = $this->replaceVariables( $text );
3776 # Strip out <nowiki> etc. added via replaceVariables
3777 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3780 $sigText = $this->getUserSig( $user );
3781 $text = strtr( $text, array(
3783 '~~~~' => "$sigText $d",
3787 # Context links: [[|name]] and [[name (context)|]]
3789 global $wgLegalTitleChars;
3790 $tc = "[$wgLegalTitleChars]";
3791 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3793 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3794 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3795 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3797 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3798 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3799 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3801 $t = $this->mTitle
->getText();
3803 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3804 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3805 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3806 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3808 # if there's no context, don't bother duplicating the title
3809 $text = preg_replace( $p2, '[[\\1]]', $text );
3812 # Trim trailing whitespace
3813 $text = rtrim( $text );
3819 * Fetch the user's signature text, if any, and normalize to
3820 * validated, ready-to-insert wikitext.
3826 function getUserSig( &$user ) {
3827 global $wgMaxSigChars;
3829 $username = $user->getName();
3830 $nickname = $user->getOption( 'nickname' );
3831 $nickname = $nickname === '' ?
$username : $nickname;
3833 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3834 $nickname = $username;
3835 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3836 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3837 # Sig. might contain markup; validate this
3838 if( $this->validateSig( $nickname ) !== false ) {
3839 # Validated; clean up (if needed) and return it
3840 return $this->cleanSig( $nickname, true );
3842 # Failed to validate; fall back to the default
3843 $nickname = $username;
3844 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3848 // Make sure nickname doesnt get a sig in a sig
3849 $nickname = $this->cleanSigInSig( $nickname );
3851 # If we're still here, make it a link to the user page
3852 $userpage = $user->getUserPage();
3853 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3857 * Check that the user's signature contains no bad XML
3859 * @param string $text
3860 * @return mixed An expanded string, or false if invalid.
3862 function validateSig( $text ) {
3863 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3867 * Clean up signature text
3869 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3870 * 2) Substitute all transclusions
3872 * @param string $text
3873 * @param $parsing Whether we're cleaning (preferences save) or parsing
3874 * @return string Signature text
3876 function cleanSig( $text, $parsing = false ) {
3878 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3880 $substWord = MagicWord
::get( 'subst' );
3881 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3882 $substText = '{{' . $substWord->getSynonym( 0 );
3884 $text = preg_replace( $substRegex, $substText, $text );
3885 $text = $this->cleanSigInSig( $text );
3886 $text = $this->replaceVariables( $text );
3888 $this->clearState();
3893 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3894 * @param string $text
3895 * @return string Signature text with /~{3,5}/ removed
3897 function cleanSigInSig( $text ) {
3898 $text = preg_replace( '/~{3,5}/', '', $text );
3903 * Set up some variables which are usually set up in parse()
3904 * so that an external function can call some class members with confidence
3907 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3908 $this->mTitle
=& $title;
3909 $this->mOptions
= $options;
3910 $this->setOutputType( $outputType );
3911 if ( $clearState ) {
3912 $this->clearState();
3917 * Transform a MediaWiki message by replacing magic variables.
3919 * @param string $text the text to transform
3920 * @param ParserOptions $options options
3921 * @return string the text with variables substituted
3924 function transformMsg( $text, $options ) {
3926 static $executing = false;
3928 $fname = "Parser::transformMsg";
3930 # Guard against infinite recursion
3936 wfProfileIn($fname);
3938 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3939 $this->mTitle
= $wgTitle;
3941 $this->mTitle
= Title
::newFromText('msg');
3943 $this->mOptions
= $options;
3944 $this->setOutputType( OT_MSG
);
3945 $this->clearState();
3946 $text = $this->replaceVariables( $text );
3949 wfProfileOut($fname);
3954 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3955 * The callback should have the following form:
3956 * function myParserHook( $text, $params, &$parser ) { ... }
3958 * Transform and return $text. Use $parser for any required context, e.g. use
3959 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3963 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3964 * @param mixed $callback The callback function (and object) to use for the tag
3966 * @return The old value of the mTagHooks array associated with the hook
3968 function setHook( $tag, $callback ) {
3969 $tag = strtolower( $tag );
3970 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3971 $this->mTagHooks
[$tag] = $callback;
3976 function setTransparentTagHook( $tag, $callback ) {
3977 $tag = strtolower( $tag );
3978 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3979 $this->mTransparentTagHooks
[$tag] = $callback;
3985 * Create a function, e.g. {{sum:1|2|3}}
3986 * The callback function should have the form:
3987 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3989 * The callback may either return the text result of the function, or an array with the text
3990 * in element 0, and a number of flags in the other elements. The names of the flags are
3991 * specified in the keys. Valid flags are:
3992 * found The text returned is valid, stop processing the template. This
3994 * nowiki Wiki markup in the return value should be escaped
3995 * noparse Unsafe HTML tags should not be stripped, etc.
3996 * noargs Don't replace triple-brace arguments in the return value
3997 * isHTML The returned text is HTML, armour it against wikitext transformation
4001 * @param string $id The magic word ID
4002 * @param mixed $callback The callback function (and object) to use
4003 * @param integer $flags a combination of the following flags:
4004 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4006 * @return The old callback function for this name, if any
4008 function setFunctionHook( $id, $callback, $flags = 0 ) {
4009 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4010 $this->mFunctionHooks
[$id] = $callback;
4012 # Add to function cache
4013 $mw = MagicWord
::get( $id );
4015 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4017 $synonyms = $mw->getSynonyms();
4018 $sensitive = intval( $mw->isCaseSensitive() );
4020 foreach ( $synonyms as $syn ) {
4022 if ( !$sensitive ) {
4023 $syn = strtolower( $syn );
4026 if ( !( $flags & SFH_NO_HASH
) ) {
4029 # Remove trailing colon
4030 if ( substr( $syn, -1, 1 ) == ':' ) {
4031 $syn = substr( $syn, 0, -1 );
4033 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4039 * Get all registered function hook identifiers
4043 function getFunctionHooks() {
4044 return array_keys( $this->mFunctionHooks
);
4048 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4049 * Placeholders created in Skin::makeLinkObj()
4050 * Returns an array of links found, indexed by PDBK:
4054 * $options is a bit field, RLH_FOR_UPDATE to select for update
4056 function replaceLinkHolders( &$text, $options = 0 ) {
4060 $fname = 'Parser::replaceLinkHolders';
4061 wfProfileIn( $fname );
4065 $sk = $this->mOptions
->getSkin();
4066 $linkCache =& LinkCache
::singleton();
4068 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4069 wfProfileIn( $fname.'-check' );
4070 $dbr = wfGetDB( DB_SLAVE
);
4071 $page = $dbr->tableName( 'page' );
4072 $threshold = $wgUser->getOption('stubthreshold');
4075 asort( $this->mLinkHolders
['namespaces'] );
4080 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4082 $title = $this->mLinkHolders
['titles'][$key];
4084 # Skip invalid entries.
4085 # Result will be ugly, but prevents crash.
4086 if ( is_null( $title ) ) {
4089 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4091 # Check if it's a static known link, e.g. interwiki
4092 if ( $title->isAlwaysKnown() ) {
4093 $colours[$pdbk] = 1;
4094 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4095 $colours[$pdbk] = 1;
4096 $this->mOutput
->addLink( $title, $id );
4097 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4098 $colours[$pdbk] = 0;
4099 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4100 $colours[$pdbk] = 0;
4102 # Not in the link cache, add it to the query
4103 if ( !isset( $current ) ) {
4105 $query = "SELECT page_id, page_namespace, page_title";
4106 if ( $threshold > 0 ) {
4107 $query .= ', page_len, page_is_redirect';
4109 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4110 } elseif ( $current != $ns ) {
4112 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4117 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4122 if ( $options & RLH_FOR_UPDATE
) {
4123 $query .= ' FOR UPDATE';
4126 $res = $dbr->query( $query, $fname );
4128 # Fetch data and form into an associative array
4129 # non-existent = broken
4132 while ( $s = $dbr->fetchObject($res) ) {
4133 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4134 $pdbk = $title->getPrefixedDBkey();
4135 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4136 $this->mOutput
->addLink( $title, $s->page_id
);
4138 $colours[$pdbk] = ( $threshold == 0 ||
(
4139 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4140 $s->page_is_redirect ||
4141 !Namespace::isContent( $s->page_namespace
) )
4145 wfProfileOut( $fname.'-check' );
4147 # Do a second query for different language variants of links and categories
4148 if($wgContLang->hasVariants()){
4149 $linkBatch = new LinkBatch();
4150 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4151 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4152 $varCategories = array(); // category replacements oldDBkey => newDBkey
4154 $categories = $this->mOutput
->getCategoryLinks();
4156 // Add variants of links to link batch
4157 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4158 $title = $this->mLinkHolders
['titles'][$key];
4159 if ( is_null( $title ) )
4162 $pdbk = $title->getPrefixedDBkey();
4163 $titleText = $title->getText();
4165 // generate all variants of the link title text
4166 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4168 // if link was not found (in first query), add all variants to query
4169 if ( !isset($colours[$pdbk]) ){
4170 foreach($allTextVariants as $textVariant){
4171 if($textVariant != $titleText){
4172 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4173 if(is_null($variantTitle)) continue;
4174 $linkBatch->addObj( $variantTitle );
4175 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4181 // process categories, check if a category exists in some variant
4182 foreach( $categories as $category ){
4183 $variants = $wgContLang->convertLinkToAllVariants($category);
4184 foreach($variants as $variant){
4185 if($variant != $category){
4186 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4187 if(is_null($variantTitle)) continue;
4188 $linkBatch->addObj( $variantTitle );
4189 $categoryMap[$variant] = $category;
4195 if(!$linkBatch->isEmpty()){
4197 $titleClause = $linkBatch->constructSet('page', $dbr);
4199 $variantQuery = "SELECT page_id, page_namespace, page_title";
4200 if ( $threshold > 0 ) {
4201 $variantQuery .= ', page_len, page_is_redirect';
4204 $variantQuery .= " FROM $page WHERE $titleClause";
4205 if ( $options & RLH_FOR_UPDATE
) {
4206 $variantQuery .= ' FOR UPDATE';
4209 $varRes = $dbr->query( $variantQuery, $fname );
4211 // for each found variants, figure out link holders and replace
4212 while ( $s = $dbr->fetchObject($varRes) ) {
4214 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4215 $varPdbk = $variantTitle->getPrefixedDBkey();
4216 $vardbk = $variantTitle->getDBkey();
4218 $holderKeys = array();
4219 if(isset($variantMap[$varPdbk])){
4220 $holderKeys = $variantMap[$varPdbk];
4221 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4222 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4225 // loop over link holders
4226 foreach($holderKeys as $key){
4227 $title = $this->mLinkHolders
['titles'][$key];
4228 if ( is_null( $title ) ) continue;
4230 $pdbk = $title->getPrefixedDBkey();
4232 if(!isset($colours[$pdbk])){
4233 // found link in some of the variants, replace the link holder data
4234 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4235 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4237 // set pdbk and colour
4238 $pdbks[$key] = $varPdbk;
4239 if ( $threshold > 0 ) {
4240 $size = $s->page_len
;
4241 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4242 $colours[$varPdbk] = 1;
4244 $colours[$varPdbk] = 2;
4248 $colours[$varPdbk] = 1;
4253 // check if the object is a variant of a category
4254 if(isset($categoryMap[$vardbk])){
4255 $oldkey = $categoryMap[$vardbk];
4256 if($oldkey != $vardbk)
4257 $varCategories[$oldkey]=$vardbk;
4261 // rebuild the categories in original order (if there are replacements)
4262 if(count($varCategories)>0){
4264 $originalCats = $this->mOutput
->getCategories();
4265 foreach($originalCats as $cat => $sortkey){
4266 // make the replacement
4267 if( array_key_exists($cat,$varCategories) )
4268 $newCats[$varCategories[$cat]] = $sortkey;
4269 else $newCats[$cat] = $sortkey;
4271 $this->mOutput
->setCategoryLinks($newCats);
4276 # Construct search and replace arrays
4277 wfProfileIn( $fname.'-construct' );
4278 $replacePairs = array();
4279 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4280 $pdbk = $pdbks[$key];
4281 $searchkey = "<!--LINK $key-->";
4282 $title = $this->mLinkHolders
['titles'][$key];
4283 if ( empty( $colours[$pdbk] ) ) {
4284 $linkCache->addBadLinkObj( $title );
4285 $colours[$pdbk] = 0;
4286 $this->mOutput
->addLink( $title, 0 );
4287 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4288 $this->mLinkHolders
['texts'][$key],
4289 $this->mLinkHolders
['queries'][$key] );
4290 } elseif ( $colours[$pdbk] == 1 ) {
4291 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4292 $this->mLinkHolders
['texts'][$key],
4293 $this->mLinkHolders
['queries'][$key] );
4294 } elseif ( $colours[$pdbk] == 2 ) {
4295 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4296 $this->mLinkHolders
['texts'][$key],
4297 $this->mLinkHolders
['queries'][$key] );
4300 $replacer = new HashtableReplacer( $replacePairs, 1 );
4301 wfProfileOut( $fname.'-construct' );
4304 wfProfileIn( $fname.'-replace' );
4305 $text = preg_replace_callback(
4306 '/(<!--LINK .*?-->)/',
4310 wfProfileOut( $fname.'-replace' );
4313 # Now process interwiki link holders
4314 # This is quite a bit simpler than internal links
4315 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4316 wfProfileIn( $fname.'-interwiki' );
4317 # Make interwiki link HTML
4318 $replacePairs = array();
4319 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4320 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4321 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4323 $replacer = new HashtableReplacer( $replacePairs, 1 );
4325 $text = preg_replace_callback(
4326 '/<!--IWLINK (.*?)-->/',
4329 wfProfileOut( $fname.'-interwiki' );
4332 wfProfileOut( $fname );
4337 * Replace <!--LINK--> link placeholders with plain text of links
4338 * (not HTML-formatted).
4339 * @param string $text
4342 function replaceLinkHoldersText( $text ) {
4343 $fname = 'Parser::replaceLinkHoldersText';
4344 wfProfileIn( $fname );
4346 $text = preg_replace_callback(
4347 '/<!--(LINK|IWLINK) (.*?)-->/',
4348 array( &$this, 'replaceLinkHoldersTextCallback' ),
4351 wfProfileOut( $fname );
4356 * @param array $matches
4360 function replaceLinkHoldersTextCallback( $matches ) {
4361 $type = $matches[1];
4363 if( $type == 'LINK' ) {
4364 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4365 return $this->mLinkHolders
['texts'][$key];
4367 } elseif( $type == 'IWLINK' ) {
4368 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4369 return $this->mInterwikiLinkHolders
['texts'][$key];
4376 * Tag hook handler for 'pre'.
4378 function renderPreTag( $text, $attribs ) {
4379 // Backwards-compatibility hack
4380 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4382 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4383 return wfOpenElement( 'pre', $attribs ) .
4384 Xml
::escapeTagsOnly( $content ) .
4389 * Renders an image gallery from a text with one line per image.
4390 * text labels may be given by using |-style alternative text. E.g.
4391 * Image:one.jpg|The number "1"
4392 * Image:tree.jpg|A tree
4393 * given as text will return the HTML of a gallery with two images,
4394 * labeled 'The number "1"' and
4397 function renderImageGallery( $text, $params ) {
4398 $ig = new ImageGallery();
4399 $ig->setContextTitle( $this->mTitle
);
4400 $ig->setShowBytes( false );
4401 $ig->setShowFilename( false );
4402 $ig->setParser( $this );
4403 $ig->setHideBadImages();
4404 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4405 $ig->useSkin( $this->mOptions
->getSkin() );
4406 $ig->mRevisionId
= $this->mRevisionId
;
4408 if( isset( $params['caption'] ) ) {
4409 $caption = $params['caption'];
4410 $caption = htmlspecialchars( $caption );
4411 $caption = $this->replaceInternalLinks( $caption );
4412 $ig->setCaptionHtml( $caption );
4414 if( isset( $params['perrow'] ) ) {
4415 $ig->setPerRow( $params['perrow'] );
4417 if( isset( $params['widths'] ) ) {
4418 $ig->setWidths( $params['widths'] );
4420 if( isset( $params['heights'] ) ) {
4421 $ig->setHeights( $params['heights'] );
4424 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4426 $lines = explode( "\n", $text );
4427 foreach ( $lines as $line ) {
4428 # match lines like these:
4429 # Image:someimage.jpg|This is some image
4431 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4433 if ( count( $matches ) == 0 ) {
4436 $tp = Title
::newFromText( $matches[1] );
4438 if( is_null( $nt ) ) {
4439 # Bogus title. Ignore these so we don't bomb out later.
4442 if ( isset( $matches[3] ) ) {
4443 $label = $matches[3];
4448 $pout = $this->parse( $label,
4451 false, // Strip whitespace...?
4452 false // Don't clear state!
4454 $html = $pout->getText();
4456 $ig->add( $nt, $html );
4458 # Only add real images (bug #5586)
4459 if ( $nt->getNamespace() == NS_IMAGE
) {
4460 $this->mOutput
->addImage( $nt->getDBkey() );
4463 return $ig->toHTML();
4466 function getImageParams( $handler ) {
4468 $handlerClass = get_class( $handler );
4472 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4473 // Initialise static lists
4474 static $internalParamNames = array(
4475 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4476 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4477 'bottom', 'text-bottom' ),
4478 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4479 'upright', 'border' ),
4481 static $internalParamMap;
4482 if ( !$internalParamMap ) {
4483 $internalParamMap = array();
4484 foreach ( $internalParamNames as $type => $names ) {
4485 foreach ( $names as $name ) {
4486 $magicName = str_replace( '-', '_', "img_$name" );
4487 $internalParamMap[$magicName] = array( $type, $name );
4492 // Add handler params
4493 $paramMap = $internalParamMap;
4495 $handlerParamMap = $handler->getParamMap();
4496 foreach ( $handlerParamMap as $magic => $paramName ) {
4497 $paramMap[$magic] = array( 'handler', $paramName );
4500 $this->mImageParams
[$handlerClass] = $paramMap;
4501 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4503 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4507 * Parse image options text and use it to make an image
4509 function makeImage( $title, $options ) {
4510 # @TODO: let the MediaHandler specify its transform parameters
4512 # Check if the options text is of the form "options|alt text"
4514 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4515 # * left no resizing, just left align. label is used for alt= only
4516 # * right same, but right aligned
4517 # * none same, but not aligned
4518 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4519 # * center center the image
4520 # * framed Keep original image size, no magnify-button.
4521 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4522 # * upright reduce width for upright images, rounded to full __0 px
4523 # * border draw a 1px border around the image
4524 # vertical-align values (no % or length right now):
4534 $parts = array_map( 'trim', explode( '|', $options) );
4535 $sk = $this->mOptions
->getSkin();
4537 # Give extensions a chance to select the file revision for us
4538 $skip = $time = false;
4539 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4542 return $sk->makeLinkObj( $title );
4546 $file = wfFindFile( $title, $time );
4547 $handler = $file ?
$file->getHandler() : false;
4549 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4551 # Process the input parameters
4553 $params = array( 'frame' => array(), 'handler' => array(),
4554 'horizAlign' => array(), 'vertAlign' => array() );
4555 foreach( $parts as $part ) {
4556 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4557 if ( isset( $paramMap[$magicName] ) ) {
4558 list( $type, $paramName ) = $paramMap[$magicName];
4559 $params[$type][$paramName] = $value;
4561 // Special case; width and height come in one variable together
4562 if( $type == 'handler' && $paramName == 'width' ) {
4564 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4565 $params[$type]['width'] = intval( $m[1] );
4566 $params[$type]['height'] = intval( $m[2] );
4568 $params[$type]['width'] = intval( $value );
4576 # Process alignment parameters
4577 if ( $params['horizAlign'] ) {
4578 $params['frame']['align'] = key( $params['horizAlign'] );
4580 if ( $params['vertAlign'] ) {
4581 $params['frame']['valign'] = key( $params['vertAlign'] );
4584 # Validate the handler parameters
4586 foreach ( $params['handler'] as $name => $value ) {
4587 if ( !$handler->validateParam( $name, $value ) ) {
4588 unset( $params['handler'][$name] );
4593 # Strip bad stuff out of the alt text
4594 $alt = $this->replaceLinkHoldersText( $caption );
4596 # make sure there are no placeholders in thumbnail attributes
4597 # that are later expanded to html- so expand them now and
4599 $alt = $this->mStripState
->unstripBoth( $alt );
4600 $alt = Sanitizer
::stripAllTags( $alt );
4602 $params['frame']['alt'] = $alt;
4603 $params['frame']['caption'] = $caption;
4605 # Linker does the rest
4606 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4608 # Give the handler a chance to modify the parser object
4610 $handler->parserTransformHook( $this, $file );
4617 * Set a flag in the output object indicating that the content is dynamic and
4618 * shouldn't be cached.
4620 function disableCache() {
4621 wfDebug( "Parser output marked as uncacheable.\n" );
4622 $this->mOutput
->mCacheTime
= -1;
4626 * Callback from the Sanitizer for expanding items found in HTML attribute
4627 * values, so they can be safely tested and escaped.
4628 * @param string $text
4629 * @param array $args
4633 function attributeStripCallback( &$text, $args ) {
4634 $text = $this->replaceVariables( $text, $args );
4635 $text = $this->mStripState
->unstripBoth( $text );
4644 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4645 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4646 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4652 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4657 * Break wikitext input into sections, and either pull or replace
4658 * some particular section's text.
4660 * External callers should use the getSection and replaceSection methods.
4662 * @param $text Page wikitext
4663 * @param $section Numbered section. 0 pulls the text before the first
4664 * heading; other numbers will pull the given section
4665 * along with its lower-level subsections.
4666 * @param $mode One of "get" or "replace"
4667 * @param $newtext Replacement text for section data.
4668 * @return string for "get", the extracted section text.
4669 * for "replace", the whole page with the section replaced.
4671 private function extractSections( $text, $section, $mode, $newtext='' ) {
4672 # I.... _hope_ this is right.
4673 # Otherwise, sometimes we don't have things initialized properly.
4674 $this->clearState();
4676 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4677 # comments to be stripped as well)
4678 $stripState = new StripState
;
4680 $oldOutputType = $this->mOutputType
;
4681 $oldOptions = $this->mOptions
;
4682 $this->mOptions
= new ParserOptions();
4683 $this->setOutputType( OT_WIKI
);
4685 $striptext = $this->strip( $text, $stripState, true );
4687 $this->setOutputType( $oldOutputType );
4688 $this->mOptions
= $oldOptions;
4690 # now that we can be sure that no pseudo-sections are in the source,
4691 # split it up by section
4692 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4693 $comment = "(?:$uniq-!--.*?QINU\x07)";
4698 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4699 (=+) # Should this be limited to 6?
4700 .+? # Section title...
4701 \\2 # Ending = count must match start
4702 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4711 PREG_SPLIT_DELIM_CAPTURE
);
4713 if( $mode == "get" ) {
4714 if( $section == 0 ) {
4715 // "Section 0" returns the content before any other section.
4718 //track missing section, will replace if found.
4721 } elseif( $mode == "replace" ) {
4722 if( $section == 0 ) {
4723 $rv = $newtext . "\n\n";
4732 for( $index = 1; $index < count( $secs ); ) {
4733 $headerLine = $secs[$index++
];
4734 if( $secs[$index] ) {
4736 $headerLevel = strlen( $secs[$index++
] );
4740 $headerLevel = intval( $secs[$index++
] );
4742 $content = $secs[$index++
];
4745 if( $mode == "get" ) {
4746 if( $count == $section ) {
4747 $rv = $headerLine . $content;
4748 $sectionLevel = $headerLevel;
4749 } elseif( $count > $section ) {
4750 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4751 $rv .= $headerLine . $content;
4753 // Broke out to a higher-level section
4757 } elseif( $mode == "replace" ) {
4758 if( $count < $section ) {
4759 $rv .= $headerLine . $content;
4760 } elseif( $count == $section ) {
4761 $rv .= $newtext . "\n\n";
4762 $sectionLevel = $headerLevel;
4763 } elseif( $count > $section ) {
4764 if( $headerLevel <= $sectionLevel ) {
4765 // Passed the section's sub-parts.
4769 $rv .= $headerLine . $content;
4775 # reinsert stripped tags
4776 $rv = trim( $stripState->unstripBoth( $rv ) );
4782 * This function returns the text of a section, specified by a number ($section).
4783 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4784 * the first section before any such heading (section 0).
4786 * If a section contains subsections, these are also returned.
4788 * @param $text String: text to look in
4789 * @param $section Integer: section number
4790 * @param $deftext: default to return if section is not found
4791 * @return string text of the requested section
4793 public function getSection( $text, $section, $deftext='' ) {
4794 return $this->extractSections( $text, $section, "get", $deftext );
4797 public function replaceSection( $oldtext, $section, $text ) {
4798 return $this->extractSections( $oldtext, $section, "replace", $text );
4802 * Get the timestamp associated with the current revision, adjusted for
4803 * the default server-local timestamp
4805 function getRevisionTimestamp() {
4806 if ( is_null( $this->mRevisionTimestamp
) ) {
4807 wfProfileIn( __METHOD__
);
4809 $dbr = wfGetDB( DB_SLAVE
);
4810 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4811 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4813 // Normalize timestamp to internal MW format for timezone processing.
4814 // This has the added side-effect of replacing a null value with
4815 // the current time, which gives us more sensible behavior for
4817 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4819 // The cryptic '' timezone parameter tells to use the site-default
4820 // timezone offset instead of the user settings.
4822 // Since this value will be saved into the parser cache, served
4823 // to other users, and potentially even used inside links and such,
4824 // it needs to be consistent for all visitors.
4825 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4827 wfProfileOut( __METHOD__
);
4829 return $this->mRevisionTimestamp
;
4833 * Mutator for $mDefaultSort
4835 * @param $sort New value
4837 public function setDefaultSort( $sort ) {
4838 $this->mDefaultSort
= $sort;
4842 * Accessor for $mDefaultSort
4843 * Will use the title/prefixed title if none is set
4847 public function getDefaultSort() {
4848 if( $this->mDefaultSort
!== false ) {
4849 return $this->mDefaultSort
;
4851 return $this->mTitle
->getNamespace() == NS_CATEGORY
4852 ?
$this->mTitle
->getText()
4853 : $this->mTitle
->getPrefixedText();
4858 * Try to guess the section anchor name based on a wikitext fragment
4859 * presumably extracted from a heading, for example "Header" from
4862 public function guessSectionNameFromWikiText( $text ) {
4863 # Strip out wikitext links(they break the anchor)
4864 $text = $this->stripSectionName( $text );
4865 $headline = Sanitizer
::decodeCharReferences( $text );
4867 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4868 $headline = trim( $headline );
4869 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4870 $replacearray = array(
4875 array_keys( $replacearray ),
4876 array_values( $replacearray ),
4881 * Strips a text string of wikitext for use in a section anchor
4883 * Accepts a text string and then removes all wikitext from the
4884 * string and leaves only the resultant text (i.e. the result of
4885 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4886 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4887 * to create valid section anchors by mimicing the output of the
4888 * parser when headings are parsed.
4890 * @param $text string Text string to be stripped of wikitext
4891 * for use in a Section anchor
4892 * @return Filtered text string
4894 public function stripSectionName( $text ) {
4895 # Strip internal link markup
4896 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4897 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4899 # Strip external link markup (FIXME: Not Tolerant to blank link text
4900 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4901 # on how many empty links there are on the page - need to figure that out.
4902 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4904 # Parse wikitext quotes (italics & bold)
4905 $text = $this->doQuotes($text);
4908 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4913 * strip/replaceVariables/unstrip for preprocessor regression testing
4915 function srvus( $text ) {
4916 $text = $this->strip( $text, $this->mStripState
);
4917 $text = $this->replaceVariables( $text );
4918 $text = preg_replace( '/<!--MWTEMPLATESECTION.*?-->/', '', $text );
4919 $text = $this->mStripState
->unstripBoth( $text );