5 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
90 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
91 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
92 $mExtLinkBracketedRegex, $mPreprocessor, $mDefaultStripList, $mVarCache, $mConf;
95 # Cleared with clearState():
96 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
97 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
98 var $mInterwikiLinkHolders, $mLinkHolders;
99 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
100 var $mTplExpandCache; // empty-frame expansion cache
101 var $mTplRedirCache, $mTplDomCache, $mHeadings;
104 # These are variables reset at least once per parse regardless of $clearState
105 var $mOptions, // ParserOptions object
106 $mTitle, // Title context, used for self-link rendering and similar things
107 $mOutputType, // Output type, one of the OT_xxx constants
108 $ot, // Shortcut alias, see setOutputType()
109 $mRevisionId, // ID to display in {{REVISIONID}} tags
110 $mRevisionTimestamp, // The timestamp of the specified revision ID
111 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
120 function __construct( $conf = array() ) {
121 $this->mConf
= $conf;
122 $this->mTagHooks
= array();
123 $this->mTransparentTagHooks
= array();
124 $this->mFunctionHooks
= array();
125 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
126 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
127 $this->mMarkerSuffix
= "-QINU\x7f";
128 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
129 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
130 $this->mVarCache
= array();
131 if ( isset( $conf['preprocessorClass'] ) ) {
132 $this->mPreprocessorClass
= $conf['preprocessorClass'];
134 $this->mPreprocessorClass
= 'Preprocessor_DOM';
136 $this->mFirstCall
= true;
140 * Do various kinds of initialisation on the first call of the parser
142 function firstCallInit() {
143 if ( !$this->mFirstCall
) {
146 $this->mFirstCall
= false;
148 wfProfileIn( __METHOD__
);
149 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
151 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
153 # Syntax for arguments (see self::setFunctionHook):
154 # "name for lookup in localized magic words array",
156 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
157 # instead of {{#int:...}})
158 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
174 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
175 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
176 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
177 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
178 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
179 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
180 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
181 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
182 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
183 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
184 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
185 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS
);
187 if ( $wgAllowDisplayTitle ) {
188 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
190 if ( $wgAllowSlowParserFunctions ) {
191 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
194 $this->initialiseVariables();
196 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
197 wfProfileOut( __METHOD__
);
205 function clearState() {
206 wfProfileIn( __METHOD__
);
207 if ( $this->mFirstCall
) {
208 $this->firstCallInit();
210 $this->mOutput
= new ParserOutput
;
211 $this->mAutonumber
= 0;
212 $this->mLastSection
= '';
213 $this->mDTopen
= false;
214 $this->mIncludeCount
= array();
215 $this->mStripState
= new StripState
;
216 $this->mArgStack
= false;
217 $this->mInPre
= false;
218 $this->mInterwikiLinkHolders
= array(
222 $this->mLinkHolders
= array(
223 'namespaces' => array(),
225 'queries' => array(),
229 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
232 * Prefix for temporary replacement strings for the multipass parser.
233 * \x07 should never appear in input as it's disallowed in XML.
234 * Using it at the front also gives us a little extra robustness
235 * since it shouldn't match when butted up against identifier-like
238 * Must not consist of all title characters, or else it will change
239 * the behaviour of <nowiki> in a link.
241 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
242 # Changed to \x7f to allow XML double-parsing -- TS
243 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
245 # Clear these on every parse, bug 4549
246 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
248 $this->mShowToc
= true;
249 $this->mForceTocPosition
= false;
250 $this->mIncludeSizes
= array(
254 $this->mPPNodeCount
= 0;
255 $this->mDefaultSort
= false;
256 $this->mHeadings
= array();
259 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
260 $this->mPreprocessor
= null;
263 wfRunHooks( 'ParserClearState', array( &$this ) );
264 wfProfileOut( __METHOD__
);
267 function setOutputType( $ot ) {
268 $this->mOutputType
= $ot;
271 'html' => $ot == self
::OT_HTML
,
272 'wiki' => $ot == self
::OT_WIKI
,
273 'pre' => $ot == self
::OT_PREPROCESS
,
278 * Set the context title
280 function setTitle( $t ) {
281 if ( !$t ||
$t instanceof FakeTitle
) {
282 $t = Title
::newFromText( 'NO TITLE' );
284 if ( strval( $t->getFragment() ) !== '' ) {
285 # Strip the fragment to avoid various odd effects
286 $this->mTitle
= clone $t;
287 $this->mTitle
->setFragment( '' );
294 * Accessor for mUniqPrefix.
298 function uniqPrefix() {
299 if( !isset( $this->mUniqPrefix
) ) {
300 // @fixme this is probably *horribly wrong*
301 // LanguageConverter seems to want $wgParser's uniqPrefix, however
302 // if this is called for a parser cache hit, the parser may not
303 // have ever been initialized in the first place.
304 // Not really sure what the heck is supposed to be going on here.
306 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
308 return $this->mUniqPrefix
;
312 * Convert wikitext to HTML
313 * Do not call this function recursively.
315 * @param string $text Text we want to parse
316 * @param Title &$title A title object
317 * @param array $options
318 * @param boolean $linestart
319 * @param boolean $clearState
320 * @param int $revid number to pass in {{REVISIONID}}
321 * @return ParserOutput a ParserOutput
323 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
325 * First pass--just handle <nowiki> sections, pass the rest off
326 * to internalParse() which does all the real work.
329 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
330 $fname = 'Parser::parse-' . wfGetCaller();
331 wfProfileIn( __METHOD__
);
332 wfProfileIn( $fname );
338 $this->mOptions
= $options;
339 $this->setTitle( $title );
340 $oldRevisionId = $this->mRevisionId
;
341 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
342 if( $revid !== null ) {
343 $this->mRevisionId
= $revid;
344 $this->mRevisionTimestamp
= null;
346 $this->setOutputType( self
::OT_HTML
);
347 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
349 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
350 $text = $this->internalParse( $text );
351 $text = $this->mStripState
->unstripGeneral( $text );
353 # Clean up special characters, only run once, next-to-last before doBlockLevels
355 # french spaces, last one Guillemet-left
356 # only if there is something before the space
357 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
358 # french spaces, Guillemet-right
359 '/(\\302\\253) /' => '\\1 ',
361 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
364 $text = $this->doBlockLevels( $text, $linestart );
366 $this->replaceLinkHolders( $text );
368 # the position of the parserConvert() call should not be changed. it
369 # assumes that the links are all replaced and the only thing left
370 # is the <nowiki> mark.
371 # Side-effects: this calls $this->mOutput->setTitleText()
372 $text = $wgContLang->parserConvert( $text, $this );
374 $text = $this->mStripState
->unstripNoWiki( $text );
376 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
378 //!JF Move to its own function
380 $uniq_prefix = $this->mUniqPrefix
;
382 $elements = array_keys( $this->mTransparentTagHooks
);
383 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
385 foreach( $matches as $marker => $data ) {
386 list( $element, $content, $params, $tag ) = $data;
387 $tagName = strtolower( $element );
388 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
389 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
390 array( $content, $params, $this ) );
394 $this->mStripState
->general
->setPair( $marker, $output );
396 $text = $this->mStripState
->unstripGeneral( $text );
398 $text = Sanitizer
::normalizeCharReferences( $text );
400 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
401 $text = Parser
::tidy($text);
403 # attempt to sanitize at least some nesting problems
404 # (bug #2702 and quite a few others)
406 # ''Something [http://www.cool.com cool''] -->
407 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
408 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
409 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
410 # fix up an anchor inside another anchor, only
411 # at least for a single single nested link (bug 3695)
412 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
413 '\\1\\2</a>\\3</a>\\1\\4</a>',
414 # fix div inside inline elements- doBlockLevels won't wrap a line which
415 # contains a div, so fix it up here; replace
416 # div with escaped text
417 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
418 '\\1\\3<div\\5>\\6</div>\\8\\9',
419 # remove empty italic or bold tag pairs, some
420 # introduced by rules above
421 '/<([bi])><\/\\1>/' => '',
424 $text = preg_replace(
425 array_keys( $tidyregs ),
426 array_values( $tidyregs ),
430 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
432 # Information on include size limits, for the benefit of users who try to skirt them
433 if ( $this->mOptions
->getEnableLimitReport() ) {
434 $max = $this->mOptions
->getMaxIncludeSize();
436 "NewPP limit report\n" .
437 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
438 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
439 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
440 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
441 $text .= "\n<!-- \n$limitReport-->\n";
443 $this->mOutput
->setText( $text );
444 $this->mRevisionId
= $oldRevisionId;
445 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
446 wfProfileOut( $fname );
447 wfProfileOut( __METHOD__
);
449 return $this->mOutput
;
453 * Recursive parser entry point that can be called from an extension tag
456 function recursiveTagParse( $text ) {
457 wfProfileIn( __METHOD__
);
458 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
459 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
460 $text = $this->internalParse( $text );
461 wfProfileOut( __METHOD__
);
466 * Expand templates and variables in the text, producing valid, static wikitext.
467 * Also removes comments.
469 function preprocess( $text, $title, $options, $revid = null ) {
470 wfProfileIn( __METHOD__
);
472 $this->setOutputType( self
::OT_PREPROCESS
);
473 $this->mOptions
= $options;
474 $this->setTitle( $title );
475 if( $revid !== null ) {
476 $this->mRevisionId
= $revid;
478 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
479 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
480 $text = $this->replaceVariables( $text );
481 $text = $this->mStripState
->unstripBoth( $text );
482 wfProfileOut( __METHOD__
);
487 * Get a random string
492 function getRandomString() {
493 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
496 function &getTitle() { return $this->mTitle
; }
497 function getOptions() { return $this->mOptions
; }
499 function getFunctionLang() {
500 global $wgLang, $wgContLang;
501 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
505 * Get a preprocessor object
507 function getPreprocessor() {
508 if ( !isset( $this->mPreprocessor
) ) {
509 $class = $this->mPreprocessorClass
;
510 $this->mPreprocessor
= new $class( $this );
512 return $this->mPreprocessor
;
516 * Replaces all occurrences of HTML-style comments and the given tags
517 * in the text with a random marker and returns teh next text. The output
518 * parameter $matches will be an associative array filled with data in
520 * 'UNIQ-xxxxx' => array(
523 * array( 'param' => 'x' ),
524 * '<element param="x">tag content</element>' ) )
526 * @param $elements list of element names. Comments are always extracted.
527 * @param $text Source text string.
528 * @param $uniq_prefix
533 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
538 $taglist = implode( '|', $elements );
539 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
541 while ( '' != $text ) {
542 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
544 if( count( $p ) < 5 ) {
547 if( count( $p ) > 5 ) {
561 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
562 $stripped .= $marker;
564 if ( $close === '/>' ) {
565 // Empty element tag, <tag />
570 if( $element == '!--' ) {
573 $end = "/(<\\/$element\\s*>)/i";
575 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
577 if( count( $q ) < 3 ) {
578 # No end tag -- let it run out to the end of the text.
587 $matches[$marker] = array( $element,
589 Sanitizer
::decodeTagAttributes( $attributes ),
590 "<$element$attributes$close$content$tail" );
596 * Get a list of strippable XML-like elements
598 function getStripList() {
600 $elements = $this->mStripList
;
602 $elements[] = 'html';
604 if( $this->mOptions
->getUseTeX() ) {
605 $elements[] = 'math';
611 * @deprecated use replaceVariables
613 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
618 * Restores pre, math, and other extensions removed by strip()
620 * always call unstripNoWiki() after this one
622 * @deprecated use $this->mStripState->unstrip()
624 function unstrip( $text, $state ) {
625 return $state->unstripGeneral( $text );
629 * Always call this after unstrip() to preserve the order
632 * @deprecated use $this->mStripState->unstrip()
634 function unstripNoWiki( $text, $state ) {
635 return $state->unstripNoWiki( $text );
639 * @deprecated use $this->mStripState->unstripBoth()
641 function unstripForHTML( $text ) {
642 return $this->mStripState
->unstripBoth( $text );
646 * Add an item to the strip state
647 * Returns the unique tag which must be inserted into the stripped text
648 * The tag will be replaced with the original text in unstrip()
652 function insertStripItem( $text ) {
654 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
656 $this->mStripState
->general
->setPair( $rnd, $text );
661 * Interface with html tidy, used if $wgUseTidy = true.
662 * If tidy isn't able to correct the markup, the original will be
663 * returned in all its glory with a warning comment appended.
665 * Either the external tidy program or the in-process tidy extension
666 * will be used depending on availability. Override the default
667 * $wgTidyInternal setting to disable the internal if it's not working.
669 * @param string $text Hideous HTML input
670 * @return string Corrected HTML output
674 function tidy( $text ) {
675 global $wgTidyInternal;
676 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
677 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
678 '<head><title>test</title></head><body>'.$text.'</body></html>';
679 if( $wgTidyInternal ) {
680 $correctedtext = Parser
::internalTidy( $wrappedtext );
682 $correctedtext = Parser
::externalTidy( $wrappedtext );
684 if( is_null( $correctedtext ) ) {
685 wfDebug( "Tidy error detected!\n" );
686 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
688 return $correctedtext;
692 * Spawn an external HTML tidy process and get corrected markup back from it.
697 function externalTidy( $text ) {
698 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
699 $fname = 'Parser::externalTidy';
700 wfProfileIn( $fname );
705 $descriptorspec = array(
706 0 => array('pipe', 'r'),
707 1 => array('pipe', 'w'),
708 2 => array('file', wfGetNull(), 'a')
711 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
712 if (is_resource($process)) {
713 // Theoretically, this style of communication could cause a deadlock
714 // here. If the stdout buffer fills up, then writes to stdin could
715 // block. This doesn't appear to happen with tidy, because tidy only
716 // writes to stdout after it's finished reading from stdin. Search
717 // for tidyParseStdin and tidySaveStdout in console/tidy.c
718 fwrite($pipes[0], $text);
720 while (!feof($pipes[1])) {
721 $cleansource .= fgets($pipes[1], 1024);
724 proc_close($process);
727 wfProfileOut( $fname );
729 if( $cleansource == '' && $text != '') {
730 // Some kind of error happened, so we couldn't get the corrected text.
731 // Just give up; we'll use the source text and append a warning.
739 * Use the HTML tidy PECL extension to use the tidy library in-process,
740 * saving the overhead of spawning a new process.
742 * 'pear install tidy' should be able to compile the extension module.
747 function internalTidy( $text ) {
748 global $wgTidyConf, $IP, $wgDebugTidy;
749 $fname = 'Parser::internalTidy';
750 wfProfileIn( $fname );
753 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
754 $tidy->cleanRepair();
755 if( $tidy->getStatus() == 2 ) {
756 // 2 is magic number for fatal error
757 // http://www.php.net/manual/en/function.tidy-get-status.php
760 $cleansource = tidy_get_output( $tidy );
762 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
763 $cleansource .= "<!--\nTidy reports:\n" .
764 str_replace( '-->', '-->', $tidy->errorBuffer
) .
768 wfProfileOut( $fname );
773 * parse the wiki syntax used to render tables
777 function doTableStuff ( $text ) {
778 $fname = 'Parser::doTableStuff';
779 wfProfileIn( $fname );
781 $lines = explode ( "\n" , $text );
782 $td_history = array (); // Is currently a td tag open?
783 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
784 $tr_history = array (); // Is currently a tr tag open?
785 $tr_attributes = array (); // history of tr attributes
786 $has_opened_tr = array(); // Did this table open a <tr> element?
787 $indent_level = 0; // indent level of the table
788 foreach ( $lines as $key => $line )
790 $line = trim ( $line );
792 if( $line == '' ) { // empty line, go to next line
795 $first_character = $line{0};
798 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
799 // First check if we are starting a new table
800 $indent_level = strlen( $matches[1] );
802 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
803 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
805 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
806 array_push ( $td_history , false );
807 array_push ( $last_tag_history , '' );
808 array_push ( $tr_history , false );
809 array_push ( $tr_attributes , '' );
810 array_push ( $has_opened_tr , false );
811 } else if ( count ( $td_history ) == 0 ) {
812 // Don't do any of the following
814 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
815 // We are ending a table
816 $line = '</table>' . substr ( $line , 2 );
817 $last_tag = array_pop ( $last_tag_history );
819 if ( !array_pop ( $has_opened_tr ) ) {
820 $line = "<tr><td></td></tr>{$line}";
823 if ( array_pop ( $tr_history ) ) {
824 $line = "</tr>{$line}";
827 if ( array_pop ( $td_history ) ) {
828 $line = "</{$last_tag}>{$line}";
830 array_pop ( $tr_attributes );
831 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
832 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
833 // Now we have a table row
834 $line = preg_replace( '#^\|-+#', '', $line );
836 // Whats after the tag is now only attributes
837 $attributes = $this->mStripState
->unstripBoth( $line );
838 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
839 array_pop ( $tr_attributes );
840 array_push ( $tr_attributes , $attributes );
843 $last_tag = array_pop ( $last_tag_history );
844 array_pop ( $has_opened_tr );
845 array_push ( $has_opened_tr , true );
847 if ( array_pop ( $tr_history ) ) {
851 if ( array_pop ( $td_history ) ) {
852 $line = "</{$last_tag}>{$line}";
855 $lines[$key] = $line;
856 array_push ( $tr_history , false );
857 array_push ( $td_history , false );
858 array_push ( $last_tag_history , '' );
860 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
861 // This might be cell elements, td, th or captions
862 if ( substr ( $line , 0 , 2 ) == '|+' ) {
863 $first_character = '+';
864 $line = substr ( $line , 1 );
867 $line = substr ( $line , 1 );
869 if ( $first_character == '!' ) {
870 $line = str_replace ( '!!' , '||' , $line );
873 // Split up multiple cells on the same line.
874 // FIXME : This can result in improper nesting of tags processed
875 // by earlier parser steps, but should avoid splitting up eg
876 // attribute values containing literal "||".
877 $cells = StringUtils
::explodeMarkup( '||' , $line );
881 // Loop through each table cell
882 foreach ( $cells as $cell )
885 if ( $first_character != '+' )
887 $tr_after = array_pop ( $tr_attributes );
888 if ( !array_pop ( $tr_history ) ) {
889 $previous = "<tr{$tr_after}>\n";
891 array_push ( $tr_history , true );
892 array_push ( $tr_attributes , '' );
893 array_pop ( $has_opened_tr );
894 array_push ( $has_opened_tr , true );
897 $last_tag = array_pop ( $last_tag_history );
899 if ( array_pop ( $td_history ) ) {
900 $previous = "</{$last_tag}>{$previous}";
903 if ( $first_character == '|' ) {
905 } else if ( $first_character == '!' ) {
907 } else if ( $first_character == '+' ) {
908 $last_tag = 'caption';
913 array_push ( $last_tag_history , $last_tag );
915 // A cell could contain both parameters and data
916 $cell_data = explode ( '|' , $cell , 2 );
918 // Bug 553: Note that a '|' inside an invalid link should not
919 // be mistaken as delimiting cell parameters
920 if ( strpos( $cell_data[0], '[[' ) !== false ) {
921 $cell = "{$previous}<{$last_tag}>{$cell}";
922 } else if ( count ( $cell_data ) == 1 )
923 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
925 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
926 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
927 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
930 $lines[$key] .= $cell;
931 array_push ( $td_history , true );
936 // Closing open td, tr && table
937 while ( count ( $td_history ) > 0 )
939 if ( array_pop ( $td_history ) ) {
942 if ( array_pop ( $tr_history ) ) {
945 if ( !array_pop ( $has_opened_tr ) ) {
946 $lines[] = "<tr><td></td></tr>" ;
949 $lines[] = '</table>' ;
952 $output = implode ( "\n" , $lines ) ;
954 // special case: don't return empty table
955 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
959 wfProfileOut( $fname );
965 * Helper function for parse() that transforms wiki markup into
966 * HTML. Only called for $mOutputType == self::OT_HTML.
970 function internalParse( $text ) {
972 $fname = 'Parser::internalParse';
973 wfProfileIn( $fname );
975 # Hook to suspend the parser in this state
976 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
977 wfProfileOut( $fname );
981 $text = $this->replaceVariables( $text );
982 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
983 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
985 // Tables need to come after variable replacement for things to work
986 // properly; putting them before other transformations should keep
987 // exciting things like link expansions from showing up in surprising
989 $text = $this->doTableStuff( $text );
991 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
993 $text = $this->stripToc( $text );
994 $this->stripNoGallery( $text );
995 $text = $this->doHeadings( $text );
996 if($this->mOptions
->getUseDynamicDates()) {
997 $df =& DateFormatter
::getInstance();
998 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1000 $text = $this->doAllQuotes( $text );
1001 $text = $this->replaceInternalLinks( $text );
1002 $text = $this->replaceExternalLinks( $text );
1004 # replaceInternalLinks may sometimes leave behind
1005 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1006 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1008 $text = $this->doMagicLinks( $text );
1009 $text = $this->formatHeadings( $text, $isMain );
1011 wfProfileOut( $fname );
1016 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1017 * magic external links.
1021 function doMagicLinks( $text ) {
1022 wfProfileIn( __METHOD__
);
1023 $text = preg_replace_callback(
1025 <a.*?</a> | # Skip link text
1026 <.*?> | # Skip stuff inside HTML elements
1027 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1028 ISBN\s+(\b # ISBN, capture number as m[2]
1029 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1030 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1031 [0-9Xx] # check digit
1033 )!x', array( &$this, 'magicLinkCallback' ), $text );
1034 wfProfileOut( __METHOD__
);
1038 function magicLinkCallback( $m ) {
1039 if ( substr( $m[0], 0, 1 ) == '<' ) {
1042 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1044 $num = strtr( $isbn, array(
1049 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1050 $text = '<a href="' .
1051 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1052 "\" class=\"internal\">ISBN $isbn</a>";
1054 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1058 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1060 $urlmsg = 'pubmedurl';
1063 throw new MWException( __METHOD__
.': unrecognised match type "' .
1064 substr($m[0], 0, 20 ) . '"' );
1067 $url = wfMsg( $urlmsg, $id);
1068 $sk = $this->mOptions
->getSkin();
1069 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1070 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1076 * Parse headers and return html
1080 function doHeadings( $text ) {
1081 $fname = 'Parser::doHeadings';
1082 wfProfileIn( $fname );
1083 for ( $i = 6; $i >= 1; --$i ) {
1084 $h = str_repeat( '=', $i );
1085 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1086 "<h$i>\\1</h$i>", $text );
1088 wfProfileOut( $fname );
1093 * Replace single quotes with HTML markup
1095 * @return string the altered text
1097 function doAllQuotes( $text ) {
1098 $fname = 'Parser::doAllQuotes';
1099 wfProfileIn( $fname );
1101 $lines = explode( "\n", $text );
1102 foreach ( $lines as $line ) {
1103 $outtext .= $this->doQuotes ( $line ) . "\n";
1105 $outtext = substr($outtext, 0,-1);
1106 wfProfileOut( $fname );
1111 * Helper function for doAllQuotes()
1113 public function doQuotes( $text ) {
1114 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1115 if ( count( $arr ) == 1 )
1119 # First, do some preliminary work. This may shift some apostrophes from
1120 # being mark-up to being text. It also counts the number of occurrences
1121 # of bold and italics mark-ups.
1125 foreach ( $arr as $r )
1127 if ( ( $i %
2 ) == 1 )
1129 # If there are ever four apostrophes, assume the first is supposed to
1130 # be text, and the remaining three constitute mark-up for bold text.
1131 if ( strlen( $arr[$i] ) == 4 )
1136 # If there are more than 5 apostrophes in a row, assume they're all
1137 # text except for the last 5.
1138 else if ( strlen( $arr[$i] ) > 5 )
1140 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1143 # Count the number of occurrences of bold and italics mark-ups.
1144 # We are not counting sequences of five apostrophes.
1145 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1146 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1147 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1152 # If there is an odd number of both bold and italics, it is likely
1153 # that one of the bold ones was meant to be an apostrophe followed
1154 # by italics. Which one we cannot know for certain, but it is more
1155 # likely to be one that has a single-letter word before it.
1156 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1159 $firstsingleletterword = -1;
1160 $firstmultiletterword = -1;
1162 foreach ( $arr as $r )
1164 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1166 $x1 = substr ($arr[$i-1], -1);
1167 $x2 = substr ($arr[$i-1], -2, 1);
1169 if ($firstspace == -1) $firstspace = $i;
1170 } else if ($x2 == ' ') {
1171 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1173 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1179 # If there is a single-letter word, use it!
1180 if ($firstsingleletterword > -1)
1182 $arr [ $firstsingleletterword ] = "''";
1183 $arr [ $firstsingleletterword-1 ] .= "'";
1185 # If not, but there's a multi-letter word, use that one.
1186 else if ($firstmultiletterword > -1)
1188 $arr [ $firstmultiletterword ] = "''";
1189 $arr [ $firstmultiletterword-1 ] .= "'";
1191 # ... otherwise use the first one that has neither.
1192 # (notice that it is possible for all three to be -1 if, for example,
1193 # there is only one pentuple-apostrophe in the line)
1194 else if ($firstspace > -1)
1196 $arr [ $firstspace ] = "''";
1197 $arr [ $firstspace-1 ] .= "'";
1201 # Now let's actually convert our apostrophic mush to HTML!
1206 foreach ($arr as $r)
1210 if ($state == 'both')
1217 if (strlen ($r) == 2)
1220 { $output .= '</i>'; $state = ''; }
1221 else if ($state == 'bi')
1222 { $output .= '</i>'; $state = 'b'; }
1223 else if ($state == 'ib')
1224 { $output .= '</b></i><b>'; $state = 'b'; }
1225 else if ($state == 'both')
1226 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1227 else # $state can be 'b' or ''
1228 { $output .= '<i>'; $state .= 'i'; }
1230 else if (strlen ($r) == 3)
1233 { $output .= '</b>'; $state = ''; }
1234 else if ($state == 'bi')
1235 { $output .= '</i></b><i>'; $state = 'i'; }
1236 else if ($state == 'ib')
1237 { $output .= '</b>'; $state = 'i'; }
1238 else if ($state == 'both')
1239 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1240 else # $state can be 'i' or ''
1241 { $output .= '<b>'; $state .= 'b'; }
1243 else if (strlen ($r) == 5)
1246 { $output .= '</b><i>'; $state = 'i'; }
1247 else if ($state == 'i')
1248 { $output .= '</i><b>'; $state = 'b'; }
1249 else if ($state == 'bi')
1250 { $output .= '</i></b>'; $state = ''; }
1251 else if ($state == 'ib')
1252 { $output .= '</b></i>'; $state = ''; }
1253 else if ($state == 'both')
1254 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1255 else # ($state == '')
1256 { $buffer = ''; $state = 'both'; }
1261 # Now close all remaining tags. Notice that the order is important.
1262 if ($state == 'b' ||
$state == 'ib')
1264 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1268 # There might be lonely ''''', so make sure we have a buffer
1269 if ($state == 'both' && $buffer)
1270 $output .= '<b><i>'.$buffer.'</i></b>';
1276 * Replace external links
1278 * Note: this is all very hackish and the order of execution matters a lot.
1279 * Make sure to run maintenance/parserTests.php if you change this code.
1283 function replaceExternalLinks( $text ) {
1285 $fname = 'Parser::replaceExternalLinks';
1286 wfProfileIn( $fname );
1288 $sk = $this->mOptions
->getSkin();
1290 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1292 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1295 while ( $i<count( $bits ) ) {
1297 $protocol = $bits[$i++
];
1298 $text = $bits[$i++
];
1299 $trail = $bits[$i++
];
1301 # The characters '<' and '>' (which were escaped by
1302 # removeHTMLtags()) should not be included in
1303 # URLs, per RFC 2396.
1305 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1306 $text = substr($url, $m2[0][1]) . ' ' . $text;
1307 $url = substr($url, 0, $m2[0][1]);
1310 # If the link text is an image URL, replace it with an <img> tag
1311 # This happened by accident in the original parser, but some people used it extensively
1312 $img = $this->maybeMakeExternalImage( $text );
1313 if ( $img !== false ) {
1319 # Set linktype for CSS - if URL==text, link is essentially free
1320 $linktype = ($text == $url) ?
'free' : 'text';
1322 # No link text, e.g. [http://domain.tld/some.link]
1323 if ( $text == '' ) {
1324 # Autonumber if allowed. See bug #5918
1325 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1326 $text = '[' . ++
$this->mAutonumber
. ']';
1327 $linktype = 'autonumber';
1329 # Otherwise just use the URL
1330 $text = htmlspecialchars( $url );
1334 # Have link text, e.g. [http://domain.tld/some.link text]s
1336 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1339 $text = $wgContLang->markNoConversion($text);
1341 $url = Sanitizer
::cleanUrl( $url );
1343 # Process the trail (i.e. everything after this link up until start of the next link),
1344 # replacing any non-bracketed links
1345 $trail = $this->replaceFreeExternalLinks( $trail );
1347 # Use the encoded URL
1348 # This means that users can paste URLs directly into the text
1349 # Funny characters like ö aren't valid in URLs anyway
1350 # This was changed in August 2004
1351 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1353 # Register link in the output object.
1354 # Replace unnecessary URL escape codes with the referenced character
1355 # This prevents spammers from hiding links from the filters
1356 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1357 $this->mOutput
->addExternalLink( $pasteurized );
1360 wfProfileOut( $fname );
1365 * Replace anything that looks like a URL with a link
1368 function replaceFreeExternalLinks( $text ) {
1370 $fname = 'Parser::replaceFreeExternalLinks';
1371 wfProfileIn( $fname );
1373 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1374 $s = array_shift( $bits );
1377 $sk = $this->mOptions
->getSkin();
1379 while ( $i < count( $bits ) ){
1380 $protocol = $bits[$i++
];
1381 $remainder = $bits[$i++
];
1384 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1385 # Found some characters after the protocol that look promising
1386 $url = $protocol . $m[1];
1389 # special case: handle urls as url args:
1390 # http://www.example.com/foo?=http://www.example.com/bar
1391 if(strlen($trail) == 0 &&
1393 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1394 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1397 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1402 # The characters '<' and '>' (which were escaped by
1403 # removeHTMLtags()) should not be included in
1404 # URLs, per RFC 2396.
1406 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1407 $trail = substr($url, $m2[0][1]) . $trail;
1408 $url = substr($url, 0, $m2[0][1]);
1411 # Move trailing punctuation to $trail
1413 # If there is no left bracket, then consider right brackets fair game too
1414 if ( strpos( $url, '(' ) === false ) {
1418 $numSepChars = strspn( strrev( $url ), $sep );
1419 if ( $numSepChars ) {
1420 $trail = substr( $url, -$numSepChars ) . $trail;
1421 $url = substr( $url, 0, -$numSepChars );
1424 $url = Sanitizer
::cleanUrl( $url );
1426 # Is this an external image?
1427 $text = $this->maybeMakeExternalImage( $url );
1428 if ( $text === false ) {
1429 # Not an image, make a link
1430 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1431 # Register it in the output object...
1432 # Replace unnecessary URL escape codes with their equivalent characters
1433 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1434 $this->mOutput
->addExternalLink( $pasteurized );
1436 $s .= $text . $trail;
1438 $s .= $protocol . $remainder;
1441 wfProfileOut( $fname );
1446 * Replace unusual URL escape codes with their equivalent characters
1450 * @todo This can merge genuinely required bits in the path or query string,
1451 * breaking legit URLs. A proper fix would treat the various parts of
1452 * the URL differently; as a workaround, just use the output for
1453 * statistical records, not for actual linking/output.
1455 static function replaceUnusualEscapes( $url ) {
1456 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1457 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1461 * Callback function used in replaceUnusualEscapes().
1462 * Replaces unusual URL escape codes with their equivalent character
1466 private static function replaceUnusualEscapesCallback( $matches ) {
1467 $char = urldecode( $matches[0] );
1468 $ord = ord( $char );
1469 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1470 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1471 // No, shouldn't be escaped
1474 // Yes, leave it escaped
1480 * make an image if it's allowed, either through the global
1481 * option or through the exception
1484 function maybeMakeExternalImage( $url ) {
1485 $sk = $this->mOptions
->getSkin();
1486 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1487 $imagesexception = !empty($imagesfrom);
1489 if ( $this->mOptions
->getAllowExternalImages()
1490 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1491 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1493 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1500 * Process [[ ]] wikilinks
1504 function replaceInternalLinks( $s ) {
1506 static $fname = 'Parser::replaceInternalLinks' ;
1508 wfProfileIn( $fname );
1510 wfProfileIn( $fname.'-setup' );
1512 # the % is needed to support urlencoded titles as well
1513 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1515 $sk = $this->mOptions
->getSkin();
1517 #split the entire text string on occurences of [[
1518 $a = explode( '[[', ' ' . $s );
1519 #get the first element (all text up to first [[), and remove the space we added
1520 $s = array_shift( $a );
1521 $s = substr( $s, 1 );
1523 # Match a link having the form [[namespace:link|alternate]]trail
1525 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1526 # Match cases where there is no "]]", which might still be images
1527 static $e1_img = FALSE;
1528 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1530 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1532 if ( $useLinkPrefixExtension ) {
1533 # Match the end of a line for a word that's not followed by whitespace,
1534 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1535 $e2 = wfMsgForContent( 'linkprefix' );
1538 if( is_null( $this->mTitle
) ) {
1539 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1541 $nottalk = !$this->mTitle
->isTalkPage();
1543 if ( $useLinkPrefixExtension ) {
1545 if ( preg_match( $e2, $s, $m ) ) {
1546 $first_prefix = $m[2];
1548 $first_prefix = false;
1554 if($wgContLang->hasVariants()) {
1555 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1557 $selflink = array($this->mTitle
->getPrefixedText());
1559 $useSubpages = $this->areSubpagesAllowed();
1560 wfProfileOut( $fname.'-setup' );
1562 # Loop for each link
1563 for ($k = 0; isset( $a[$k] ); $k++
) {
1565 if ( $useLinkPrefixExtension ) {
1566 wfProfileIn( $fname.'-prefixhandling' );
1567 if ( preg_match( $e2, $s, $m ) ) {
1575 $prefix = $first_prefix;
1576 $first_prefix = false;
1578 wfProfileOut( $fname.'-prefixhandling' );
1581 $might_be_img = false;
1583 wfProfileIn( "$fname-e1" );
1584 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1586 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1587 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1588 # the real problem is with the $e1 regex
1591 # Still some problems for cases where the ] is meant to be outside punctuation,
1592 # and no image is in sight. See bug 2095.
1595 substr( $m[3], 0, 1 ) === ']' &&
1596 strpos($text, '[') !== false
1599 $text .= ']'; # so that replaceExternalLinks($text) works later
1600 $m[3] = substr( $m[3], 1 );
1602 # fix up urlencoded title texts
1603 if( strpos( $m[1], '%' ) !== false ) {
1604 # Should anchors '#' also be rejected?
1605 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1608 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1609 $might_be_img = true;
1611 if ( strpos( $m[1], '%' ) !== false ) {
1612 $m[1] = urldecode($m[1]);
1615 } else { # Invalid form; output directly
1616 $s .= $prefix . '[[' . $line ;
1617 wfProfileOut( "$fname-e1" );
1620 wfProfileOut( "$fname-e1" );
1621 wfProfileIn( "$fname-misc" );
1623 # Don't allow internal links to pages containing
1624 # PROTO: where PROTO is a valid URL protocol; these
1625 # should be external links.
1626 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1627 $s .= $prefix . '[[' . $line ;
1631 # Make subpage if necessary
1632 if( $useSubpages ) {
1633 $link = $this->maybeDoSubpageLink( $m[1], $text );
1638 $noforce = (substr($m[1], 0, 1) != ':');
1640 # Strip off leading ':'
1641 $link = substr($link, 1);
1644 wfProfileOut( "$fname-misc" );
1645 wfProfileIn( "$fname-title" );
1646 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1648 $s .= $prefix . '[[' . $line;
1649 wfProfileOut( "$fname-title" );
1653 $ns = $nt->getNamespace();
1654 $iw = $nt->getInterWiki();
1655 wfProfileOut( "$fname-title" );
1657 if ($might_be_img) { # if this is actually an invalid link
1658 wfProfileIn( "$fname-might_be_img" );
1659 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1661 while (isset ($a[$k+
1]) ) {
1662 #look at the next 'line' to see if we can close it there
1663 $spliced = array_splice( $a, $k +
1, 1 );
1664 $next_line = array_shift( $spliced );
1665 $m = explode( ']]', $next_line, 3 );
1666 if ( count( $m ) == 3 ) {
1667 # the first ]] closes the inner link, the second the image
1669 $text .= "[[{$m[0]}]]{$m[1]}";
1672 } elseif ( count( $m ) == 2 ) {
1673 #if there's exactly one ]] that's fine, we'll keep looking
1674 $text .= "[[{$m[0]}]]{$m[1]}";
1676 #if $next_line is invalid too, we need look no further
1677 $text .= '[[' . $next_line;
1682 # we couldn't find the end of this imageLink, so output it raw
1683 #but don't ignore what might be perfectly normal links in the text we've examined
1684 $text = $this->replaceInternalLinks($text);
1685 $s .= "{$prefix}[[$link|$text";
1686 # note: no $trail, because without an end, there *is* no trail
1687 wfProfileOut( "$fname-might_be_img" );
1690 } else { #it's not an image, so output it raw
1691 $s .= "{$prefix}[[$link|$text";
1692 # note: no $trail, because without an end, there *is* no trail
1693 wfProfileOut( "$fname-might_be_img" );
1696 wfProfileOut( "$fname-might_be_img" );
1699 $wasblank = ( '' == $text );
1700 if( $wasblank ) $text = $link;
1702 # Link not escaped by : , create the various objects
1706 wfProfileIn( "$fname-interwiki" );
1707 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1708 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1709 $s = rtrim($s . $prefix);
1710 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1711 wfProfileOut( "$fname-interwiki" );
1714 wfProfileOut( "$fname-interwiki" );
1716 if ( $ns == NS_IMAGE
) {
1717 wfProfileIn( "$fname-image" );
1718 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1719 # recursively parse links inside the image caption
1720 # actually, this will parse them in any other parameters, too,
1721 # but it might be hard to fix that, and it doesn't matter ATM
1722 $text = $this->replaceExternalLinks($text);
1723 $text = $this->replaceInternalLinks($text);
1725 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1726 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1727 $this->mOutput
->addImage( $nt->getDBkey() );
1729 wfProfileOut( "$fname-image" );
1732 # We still need to record the image's presence on the page
1733 $this->mOutput
->addImage( $nt->getDBkey() );
1735 wfProfileOut( "$fname-image" );
1739 if ( $ns == NS_CATEGORY
) {
1740 wfProfileIn( "$fname-category" );
1741 $s = rtrim($s . "\n"); # bug 87
1744 $sortkey = $this->getDefaultSort();
1748 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1749 $sortkey = str_replace( "\n", '', $sortkey );
1750 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1751 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1754 * Strip the whitespace Category links produce, see bug 87
1755 * @todo We might want to use trim($tmp, "\n") here.
1757 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1759 wfProfileOut( "$fname-category" );
1764 # Self-link checking
1765 if( $nt->getFragment() === '' ) {
1766 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1767 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1772 # Special and Media are pseudo-namespaces; no pages actually exist in them
1773 if( $ns == NS_MEDIA
) {
1774 $link = $sk->makeMediaLinkObj( $nt, $text );
1775 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1776 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1777 $this->mOutput
->addImage( $nt->getDBkey() );
1779 } elseif( $ns == NS_SPECIAL
) {
1780 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1781 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1783 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1786 } elseif( $ns == NS_IMAGE
) {
1787 $img = wfFindFile( $nt );
1789 // Force a blue link if the file exists; may be a remote
1790 // upload on the shared repository, and we want to see its
1791 // auto-generated page.
1792 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1793 $this->mOutput
->addLink( $nt );
1797 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1799 wfProfileOut( $fname );
1804 * Make a link placeholder. The text returned can be later resolved to a real link with
1805 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1806 * parsing of interwiki links, and secondly to allow all existence checks and
1807 * article length checks (for stub links) to be bundled into a single query.
1810 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1811 wfProfileIn( __METHOD__
);
1812 if ( ! is_object($nt) ) {
1814 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1816 # Separate the link trail from the rest of the link
1817 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1819 if ( $nt->isExternal() ) {
1820 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1821 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1822 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1824 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1825 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1826 $this->mLinkHolders
['queries'][] = $query;
1827 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1828 $this->mLinkHolders
['titles'][] = $nt;
1830 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1833 wfProfileOut( __METHOD__
);
1838 * Render a forced-blue link inline; protect against double expansion of
1839 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1840 * Since this little disaster has to split off the trail text to avoid
1841 * breaking URLs in the following text without breaking trails on the
1842 * wiki links, it's been made into a horrible function.
1845 * @param string $text
1846 * @param string $query
1847 * @param string $trail
1848 * @param string $prefix
1849 * @return string HTML-wikitext mix oh yuck
1851 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1852 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1853 $sk = $this->mOptions
->getSkin();
1854 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1855 return $this->armorLinks( $link ) . $trail;
1859 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1860 * going to go through further parsing steps before inline URL expansion.
1862 * In particular this is important when using action=render, which causes
1863 * full URLs to be included.
1865 * Oh man I hate our multi-layer parser!
1867 * @param string more-or-less HTML
1868 * @return string less-or-more HTML with NOPARSE bits
1870 function armorLinks( $text ) {
1871 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1872 "{$this->mUniqPrefix}NOPARSE$1", $text );
1876 * Return true if subpage links should be expanded on this page.
1879 function areSubpagesAllowed() {
1880 # Some namespaces don't allow subpages
1881 global $wgNamespacesWithSubpages;
1882 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1886 * Handle link to subpage if necessary
1887 * @param string $target the source of the link
1888 * @param string &$text the link text, modified as necessary
1889 * @return string the full name of the link
1892 function maybeDoSubpageLink($target, &$text) {
1895 # :Foobar -- override special treatment of prefix (images, language links)
1896 # /Foobar -- convert to CurrentPage/Foobar
1897 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1898 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1899 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1901 $fname = 'Parser::maybeDoSubpageLink';
1902 wfProfileIn( $fname );
1903 $ret = $target; # default return value is no change
1905 # Some namespaces don't allow subpages,
1906 # so only perform processing if subpages are allowed
1907 if( $this->areSubpagesAllowed() ) {
1908 $hash = strpos( $target, '#' );
1909 if( $hash !== false ) {
1910 $suffix = substr( $target, $hash );
1911 $target = substr( $target, 0, $hash );
1916 $target = trim( $target );
1917 # Look at the first character
1918 if( $target != '' && $target{0} == '/' ) {
1919 # / at end means we don't want the slash to be shown
1921 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1922 if( $trailingSlashes ) {
1923 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1925 $noslash = substr( $target, 1 );
1928 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1929 if( '' === $text ) {
1930 $text = $target . $suffix;
1931 } # this might be changed for ugliness reasons
1933 # check for .. subpage backlinks
1935 $nodotdot = $target;
1936 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1938 $nodotdot = substr( $nodotdot, 3 );
1940 if($dotdotcount > 0) {
1941 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1942 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1943 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1944 # / at the end means don't show full path
1945 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1946 $nodotdot = substr( $nodotdot, 0, -1 );
1947 if( '' === $text ) {
1948 $text = $nodotdot . $suffix;
1951 $nodotdot = trim( $nodotdot );
1952 if( $nodotdot != '' ) {
1953 $ret .= '/' . $nodotdot;
1961 wfProfileOut( $fname );
1966 * Used by doBlockLevels()
1969 /* private */ function closeParagraph() {
1971 if ( '' != $this->mLastSection
) {
1972 $result = '</' . $this->mLastSection
. ">\n";
1974 $this->mInPre
= false;
1975 $this->mLastSection
= '';
1978 # getCommon() returns the length of the longest common substring
1979 # of both arguments, starting at the beginning of both.
1981 /* private */ function getCommon( $st1, $st2 ) {
1982 $fl = strlen( $st1 );
1983 $shorter = strlen( $st2 );
1984 if ( $fl < $shorter ) { $shorter = $fl; }
1986 for ( $i = 0; $i < $shorter; ++
$i ) {
1987 if ( $st1{$i} != $st2{$i} ) { break; }
1991 # These next three functions open, continue, and close the list
1992 # element appropriate to the prefix character passed into them.
1994 /* private */ function openList( $char ) {
1995 $result = $this->closeParagraph();
1997 if ( '*' == $char ) { $result .= '<ul><li>'; }
1998 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1999 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2000 else if ( ';' == $char ) {
2001 $result .= '<dl><dt>';
2002 $this->mDTopen
= true;
2004 else { $result = '<!-- ERR 1 -->'; }
2009 /* private */ function nextItem( $char ) {
2010 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2011 else if ( ':' == $char ||
';' == $char ) {
2013 if ( $this->mDTopen
) { $close = '</dt>'; }
2014 if ( ';' == $char ) {
2015 $this->mDTopen
= true;
2016 return $close . '<dt>';
2018 $this->mDTopen
= false;
2019 return $close . '<dd>';
2022 return '<!-- ERR 2 -->';
2025 /* private */ function closeList( $char ) {
2026 if ( '*' == $char ) { $text = '</li></ul>'; }
2027 else if ( '#' == $char ) { $text = '</li></ol>'; }
2028 else if ( ':' == $char ) {
2029 if ( $this->mDTopen
) {
2030 $this->mDTopen
= false;
2031 $text = '</dt></dl>';
2033 $text = '</dd></dl>';
2036 else { return '<!-- ERR 3 -->'; }
2042 * Make lists from lines starting with ':', '*', '#', etc.
2045 * @return string the lists rendered as HTML
2047 function doBlockLevels( $text, $linestart ) {
2048 $fname = 'Parser::doBlockLevels';
2049 wfProfileIn( $fname );
2051 # Parsing through the text line by line. The main thing
2052 # happening here is handling of block-level elements p, pre,
2053 # and making lists from lines starting with * # : etc.
2055 $textLines = explode( "\n", $text );
2057 $lastPrefix = $output = '';
2058 $this->mDTopen
= $inBlockElem = false;
2060 $paragraphStack = false;
2062 if ( !$linestart ) {
2063 $output .= array_shift( $textLines );
2065 foreach ( $textLines as $oLine ) {
2066 $lastPrefixLength = strlen( $lastPrefix );
2067 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2068 $preOpenMatch = preg_match('/<pre/i', $oLine );
2069 if ( !$this->mInPre
) {
2070 # Multiple prefixes may abut each other for nested lists.
2071 $prefixLength = strspn( $oLine, '*#:;' );
2072 $pref = substr( $oLine, 0, $prefixLength );
2075 $pref2 = str_replace( ';', ':', $pref );
2076 $t = substr( $oLine, $prefixLength );
2077 $this->mInPre
= !empty($preOpenMatch);
2079 # Don't interpret any other prefixes in preformatted text
2081 $pref = $pref2 = '';
2086 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2087 # Same as the last item, so no need to deal with nesting or opening stuff
2088 $output .= $this->nextItem( substr( $pref, -1 ) );
2089 $paragraphStack = false;
2091 if ( substr( $pref, -1 ) == ';') {
2092 # The one nasty exception: definition lists work like this:
2093 # ; title : definition text
2094 # So we check for : in the remainder text to split up the
2095 # title and definition, without b0rking links.
2097 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2099 $output .= $term . $this->nextItem( ':' );
2102 } elseif( $prefixLength ||
$lastPrefixLength ) {
2103 # Either open or close a level...
2104 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2105 $paragraphStack = false;
2107 while( $commonPrefixLength < $lastPrefixLength ) {
2108 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2109 --$lastPrefixLength;
2111 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2112 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2114 while ( $prefixLength > $commonPrefixLength ) {
2115 $char = substr( $pref, $commonPrefixLength, 1 );
2116 $output .= $this->openList( $char );
2118 if ( ';' == $char ) {
2119 # FIXME: This is dupe of code above
2120 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2122 $output .= $term . $this->nextItem( ':' );
2125 ++
$commonPrefixLength;
2127 $lastPrefix = $pref2;
2129 if( 0 == $prefixLength ) {
2130 wfProfileIn( "$fname-paragraph" );
2131 # No prefix (not in list)--go to paragraph mode
2132 // XXX: use a stack for nestable elements like span, table and div
2133 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2134 $closematch = preg_match(
2135 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2136 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2137 if ( $openmatch or $closematch ) {
2138 $paragraphStack = false;
2139 #Â TODO bug 5718: paragraph closed
2140 $output .= $this->closeParagraph();
2141 if ( $preOpenMatch and !$preCloseMatch ) {
2142 $this->mInPre
= true;
2144 if ( $closematch ) {
2145 $inBlockElem = false;
2147 $inBlockElem = true;
2149 } else if ( !$inBlockElem && !$this->mInPre
) {
2150 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2152 if ($this->mLastSection
!= 'pre') {
2153 $paragraphStack = false;
2154 $output .= $this->closeParagraph().'<pre>';
2155 $this->mLastSection
= 'pre';
2157 $t = substr( $t, 1 );
2160 if ( '' == trim($t) ) {
2161 if ( $paragraphStack ) {
2162 $output .= $paragraphStack.'<br />';
2163 $paragraphStack = false;
2164 $this->mLastSection
= 'p';
2166 if ($this->mLastSection
!= 'p' ) {
2167 $output .= $this->closeParagraph();
2168 $this->mLastSection
= '';
2169 $paragraphStack = '<p>';
2171 $paragraphStack = '</p><p>';
2175 if ( $paragraphStack ) {
2176 $output .= $paragraphStack;
2177 $paragraphStack = false;
2178 $this->mLastSection
= 'p';
2179 } else if ($this->mLastSection
!= 'p') {
2180 $output .= $this->closeParagraph().'<p>';
2181 $this->mLastSection
= 'p';
2186 wfProfileOut( "$fname-paragraph" );
2188 // somewhere above we forget to get out of pre block (bug 785)
2189 if($preCloseMatch && $this->mInPre
) {
2190 $this->mInPre
= false;
2192 if ($paragraphStack === false) {
2196 while ( $prefixLength ) {
2197 $output .= $this->closeList( $pref2{$prefixLength-1} );
2200 if ( '' != $this->mLastSection
) {
2201 $output .= '</' . $this->mLastSection
. '>';
2202 $this->mLastSection
= '';
2205 wfProfileOut( $fname );
2210 * Split up a string on ':', ignoring any occurences inside tags
2211 * to prevent illegal overlapping.
2212 * @param string $str the string to split
2213 * @param string &$before set to everything before the ':'
2214 * @param string &$after set to everything after the ':'
2215 * return string the position of the ':', or false if none found
2217 function findColonNoLinks($str, &$before, &$after) {
2218 $fname = 'Parser::findColonNoLinks';
2219 wfProfileIn( $fname );
2221 $pos = strpos( $str, ':' );
2222 if( $pos === false ) {
2224 wfProfileOut( $fname );
2228 $lt = strpos( $str, '<' );
2229 if( $lt === false ||
$lt > $pos ) {
2230 // Easy; no tag nesting to worry about
2231 $before = substr( $str, 0, $pos );
2232 $after = substr( $str, $pos+
1 );
2233 wfProfileOut( $fname );
2237 // Ugly state machine to walk through avoiding tags.
2238 $state = self
::COLON_STATE_TEXT
;
2240 $len = strlen( $str );
2241 for( $i = 0; $i < $len; $i++
) {
2245 // (Using the number is a performance hack for common cases)
2246 case 0: // self::COLON_STATE_TEXT:
2249 // Could be either a <start> tag or an </end> tag
2250 $state = self
::COLON_STATE_TAGSTART
;
2255 $before = substr( $str, 0, $i );
2256 $after = substr( $str, $i +
1 );
2257 wfProfileOut( $fname );
2260 // Embedded in a tag; don't break it.
2263 // Skip ahead looking for something interesting
2264 $colon = strpos( $str, ':', $i );
2265 if( $colon === false ) {
2266 // Nothing else interesting
2267 wfProfileOut( $fname );
2270 $lt = strpos( $str, '<', $i );
2271 if( $stack === 0 ) {
2272 if( $lt === false ||
$colon < $lt ) {
2274 $before = substr( $str, 0, $colon );
2275 $after = substr( $str, $colon +
1 );
2276 wfProfileOut( $fname );
2280 if( $lt === false ) {
2281 // Nothing else interesting to find; abort!
2282 // We're nested, but there's no close tags left. Abort!
2285 // Skip ahead to next tag start
2287 $state = self
::COLON_STATE_TAGSTART
;
2290 case 1: // self::COLON_STATE_TAG:
2295 $state = self
::COLON_STATE_TEXT
;
2298 // Slash may be followed by >?
2299 $state = self
::COLON_STATE_TAGSLASH
;
2305 case 2: // self::COLON_STATE_TAGSTART:
2308 $state = self
::COLON_STATE_CLOSETAG
;
2311 $state = self
::COLON_STATE_COMMENT
;
2314 // Illegal early close? This shouldn't happen D:
2315 $state = self
::COLON_STATE_TEXT
;
2318 $state = self
::COLON_STATE_TAG
;
2321 case 3: // self::COLON_STATE_CLOSETAG:
2326 wfDebug( "Invalid input in $fname; too many close tags\n" );
2327 wfProfileOut( $fname );
2330 $state = self
::COLON_STATE_TEXT
;
2333 case self
::COLON_STATE_TAGSLASH
:
2335 // Yes, a self-closed tag <blah/>
2336 $state = self
::COLON_STATE_TEXT
;
2338 // Probably we're jumping the gun, and this is an attribute
2339 $state = self
::COLON_STATE_TAG
;
2342 case 5: // self::COLON_STATE_COMMENT:
2344 $state = self
::COLON_STATE_COMMENTDASH
;
2347 case self
::COLON_STATE_COMMENTDASH
:
2349 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2351 $state = self
::COLON_STATE_COMMENT
;
2354 case self
::COLON_STATE_COMMENTDASHDASH
:
2356 $state = self
::COLON_STATE_TEXT
;
2358 $state = self
::COLON_STATE_COMMENT
;
2362 throw new MWException( "State machine error in $fname" );
2366 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2369 wfProfileOut( $fname );
2374 * Return value of a magic variable (like PAGENAME)
2378 function getVariableValue( $index ) {
2379 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2382 * Some of these require message or data lookups and can be
2383 * expensive to check many times.
2385 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2386 if ( isset( $this->mVarCache
[$index] ) ) {
2387 return $this->mVarCache
[$index];
2391 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2392 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2395 global $wgLocaltimezone;
2396 if ( isset( $wgLocaltimezone ) ) {
2397 $oldtz = getenv( 'TZ' );
2398 putenv( 'TZ='.$wgLocaltimezone );
2401 wfSuppressWarnings(); // E_STRICT system time bitching
2402 $localTimestamp = date( 'YmdHis', $ts );
2403 $localMonth = date( 'm', $ts );
2404 $localMonthName = date( 'n', $ts );
2405 $localDay = date( 'j', $ts );
2406 $localDay2 = date( 'd', $ts );
2407 $localDayOfWeek = date( 'w', $ts );
2408 $localWeek = date( 'W', $ts );
2409 $localYear = date( 'Y', $ts );
2410 $localHour = date( 'H', $ts );
2411 if ( isset( $wgLocaltimezone ) ) {
2412 putenv( 'TZ='.$oldtz );
2414 wfRestoreWarnings();
2417 case 'currentmonth':
2418 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2419 case 'currentmonthname':
2420 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2421 case 'currentmonthnamegen':
2422 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2423 case 'currentmonthabbrev':
2424 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2426 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2428 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2430 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2431 case 'localmonthname':
2432 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2433 case 'localmonthnamegen':
2434 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2435 case 'localmonthabbrev':
2436 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2438 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2440 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2442 return wfEscapeWikiText( $this->mTitle
->getText() );
2444 return $this->mTitle
->getPartialURL();
2445 case 'fullpagename':
2446 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2447 case 'fullpagenamee':
2448 return $this->mTitle
->getPrefixedURL();
2450 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2451 case 'subpagenamee':
2452 return $this->mTitle
->getSubpageUrlForm();
2453 case 'basepagename':
2454 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2455 case 'basepagenamee':
2456 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2457 case 'talkpagename':
2458 if( $this->mTitle
->canTalk() ) {
2459 $talkPage = $this->mTitle
->getTalkPage();
2460 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2464 case 'talkpagenamee':
2465 if( $this->mTitle
->canTalk() ) {
2466 $talkPage = $this->mTitle
->getTalkPage();
2467 return $talkPage->getPrefixedUrl();
2471 case 'subjectpagename':
2472 $subjPage = $this->mTitle
->getSubjectPage();
2473 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2474 case 'subjectpagenamee':
2475 $subjPage = $this->mTitle
->getSubjectPage();
2476 return $subjPage->getPrefixedUrl();
2478 // Let the edit saving system know we should parse the page
2479 // *after* a revision ID has been assigned.
2480 $this->mOutput
->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2482 return $this->mRevisionId
;
2484 // Let the edit saving system know we should parse the page
2485 // *after* a revision ID has been assigned. This is for null edits.
2486 $this->mOutput
->setFlag( 'vary-revision' );
2487 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2488 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2489 case 'revisionday2':
2490 // Let the edit saving system know we should parse the page
2491 // *after* a revision ID has been assigned. This is for null edits.
2492 $this->mOutput
->setFlag( 'vary-revision' );
2493 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2494 return substr( $this->getRevisionTimestamp(), 6, 2 );
2495 case 'revisionmonth':
2496 // Let the edit saving system know we should parse the page
2497 // *after* a revision ID has been assigned. This is for null edits.
2498 $this->mOutput
->setFlag( 'vary-revision' );
2499 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2500 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2501 case 'revisionyear':
2502 // Let the edit saving system know we should parse the page
2503 // *after* a revision ID has been assigned. This is for null edits.
2504 $this->mOutput
->setFlag( 'vary-revision' );
2505 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2506 return substr( $this->getRevisionTimestamp(), 0, 4 );
2507 case 'revisiontimestamp':
2508 // Let the edit saving system know we should parse the page
2509 // *after* a revision ID has been assigned. This is for null edits.
2510 $this->mOutput
->setFlag( 'vary-revision' );
2511 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2512 return $this->getRevisionTimestamp();
2514 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2516 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2518 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2520 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2521 case 'subjectspace':
2522 return $this->mTitle
->getSubjectNsText();
2523 case 'subjectspacee':
2524 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2525 case 'currentdayname':
2526 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2530 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2534 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2535 // int to remove the padding
2536 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2538 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2539 case 'localdayname':
2540 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2542 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2544 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2546 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2548 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2549 // int to remove the padding
2550 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2552 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2553 case 'numberofarticles':
2554 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2555 case 'numberoffiles':
2556 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2557 case 'numberofusers':
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2559 case 'numberofpages':
2560 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2561 case 'numberofadmins':
2562 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2563 case 'numberofedits':
2564 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2565 case 'currenttimestamp':
2566 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2567 case 'localtimestamp':
2568 return $this->mVarCache
[$index] = $localTimestamp;
2569 case 'currentversion':
2570 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2576 return $wgServerName;
2578 return $wgScriptPath;
2579 case 'directionmark':
2580 return $wgContLang->getDirMark();
2581 case 'contentlanguage':
2582 global $wgContLanguageCode;
2583 return $wgContLanguageCode;
2586 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2594 * initialise the magic variables (like CURRENTMONTHNAME)
2598 function initialiseVariables() {
2599 $fname = 'Parser::initialiseVariables';
2600 wfProfileIn( $fname );
2601 $variableIDs = MagicWord
::getVariableIDs();
2603 $this->mVariables
= new MagicWordArray( $variableIDs );
2604 wfProfileOut( $fname );
2608 * Preprocess some wikitext and return the document tree.
2609 * This is the ghost of replace_variables().
2611 * @param string $text The text to parse
2612 * @param integer flags Bitwise combination of:
2613 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2614 * included. Default is to assume a direct page view.
2616 * The generated DOM tree must depend only on the input text and the flags.
2617 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2619 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2620 * change in the DOM tree for a given text, must be passed through the section identifier
2621 * in the section edit link and thus back to extractSections().
2623 * The output of this function is currently only cached in process memory, but a persistent
2624 * cache may be implemented at a later date which takes further advantage of these strict
2625 * dependency requirements.
2629 function preprocessToDom ( $text, $flags = 0 ) {
2630 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2635 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2637 public static function splitWhitespace( $s ) {
2638 $ltrimmed = ltrim( $s );
2639 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2640 $trimmed = rtrim( $ltrimmed );
2641 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2643 $w2 = substr( $ltrimmed, -$diff );
2647 return array( $w1, $trimmed, $w2 );
2651 * Replace magic variables, templates, and template arguments
2652 * with the appropriate text. Templates are substituted recursively,
2653 * taking care to avoid infinite loops.
2655 * Note that the substitution depends on value of $mOutputType:
2656 * self::OT_WIKI: only {{subst:}} templates
2657 * self::OT_PREPROCESS: templates but not extension tags
2658 * self::OT_HTML: all templates and extension tags
2660 * @param string $tex The text to transform
2661 * @param PPFrame $frame Object describing the arguments passed to the template
2662 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2665 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2666 # Prevent too big inclusions
2667 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2671 $fname = __METHOD__
;
2672 wfProfileIn( $fname );
2674 if ( $frame === false ) {
2675 $frame = $this->getPreprocessor()->newFrame();
2676 } elseif ( !( $frame instanceof PPFrame
) ) {
2677 throw new MWException( __METHOD__
. ' called using the old argument format' );
2680 $dom = $this->preprocessToDom( $text );
2681 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2682 $text = $frame->expand( $dom, $flags );
2684 wfProfileOut( $fname );
2688 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2689 static function createAssocArgs( $args ) {
2690 $assocArgs = array();
2692 foreach( $args as $arg ) {
2693 $eqpos = strpos( $arg, '=' );
2694 if ( $eqpos === false ) {
2695 $assocArgs[$index++
] = $arg;
2697 $name = trim( substr( $arg, 0, $eqpos ) );
2698 $value = trim( substr( $arg, $eqpos+
1 ) );
2699 if ( $value === false ) {
2702 if ( $name !== false ) {
2703 $assocArgs[$name] = $value;
2712 * Return the text of a template, after recursively
2713 * replacing any variables or templates within the template.
2715 * @param array $piece The parts of the template
2716 * $piece['title']: the title, i.e. the part before the |
2717 * $piece['parts']: the parameter array
2718 * $piece['lineStart']: whether the brace was at the start of a line
2719 * @param PPFrame The current frame, contains template arguments
2720 * @return string the text of the template
2723 function braceSubstitution( $piece, $frame ) {
2724 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2725 $fname = __METHOD__
;
2726 wfProfileIn( $fname );
2727 wfProfileIn( __METHOD__
.'-setup' );
2730 $found = false; # $text has been filled
2731 $nowiki = false; # wiki markup in $text should be escaped
2732 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2733 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2734 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2735 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2737 # Title object, where $text came from
2740 # $part1 is the bit before the first |, and must contain only title characters.
2741 # Various prefixes will be stripped from it later.
2742 $titleWithSpaces = $frame->expand( $piece['title'] );
2743 $part1 = trim( $titleWithSpaces );
2746 # Original title text preserved for various purposes
2747 $originalTitle = $part1;
2749 # $args is a list of argument nodes, starting from index 0, not including $part1
2750 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2751 wfProfileOut( __METHOD__
.'-setup' );
2754 wfProfileIn( __METHOD__
.'-modifiers' );
2756 $mwSubst =& MagicWord
::get( 'subst' );
2757 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2758 # One of two possibilities is true:
2759 # 1) Found SUBST but not in the PST phase
2760 # 2) Didn't find SUBST and in the PST phase
2761 # In either case, return without further processing
2762 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2769 if ( !$found && $args->getLength() == 0 ) {
2770 $id = $this->mVariables
->matchStartToEnd( $part1 );
2771 if ( $id !== false ) {
2772 $text = $this->getVariableValue( $id );
2773 if (MagicWord
::getCacheTTL($id)>-1)
2774 $this->mOutput
->mContainsOldMagic
= true;
2779 # MSG, MSGNW and RAW
2782 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2783 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2786 # Remove obsolete MSG:
2787 $mwMsg =& MagicWord
::get( 'msg' );
2788 $mwMsg->matchStartAndRemove( $part1 );
2792 $mwRaw =& MagicWord
::get( 'raw' );
2793 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2794 $forceRawInterwiki = true;
2797 wfProfileOut( __METHOD__
.'-modifiers' );
2801 wfProfileIn( __METHOD__
. '-pfunc' );
2803 $colonPos = strpos( $part1, ':' );
2804 if ( $colonPos !== false ) {
2805 # Case sensitive functions
2806 $function = substr( $part1, 0, $colonPos );
2807 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2808 $function = $this->mFunctionSynonyms
[1][$function];
2810 # Case insensitive functions
2811 $function = strtolower( $function );
2812 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2813 $function = $this->mFunctionSynonyms
[0][$function];
2819 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2820 $initialArgs = array( &$this );
2821 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2822 if ( $flags & SFH_OBJECT_ARGS
) {
2823 # Add a frame parameter, and pass the arguments as an array
2824 $allArgs = $initialArgs;
2825 $allArgs[] = $frame;
2826 for ( $i = 0; $i < $args->getLength(); $i++
) {
2827 $funcArgs[] = $args->item( $i );
2829 $allArgs[] = $funcArgs;
2831 # Convert arguments to plain text
2832 for ( $i = 0; $i < $args->getLength(); $i++
) {
2833 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2835 $allArgs = array_merge( $initialArgs, $funcArgs );
2838 $result = call_user_func_array( $callback, $allArgs );
2841 if ( is_array( $result ) ) {
2842 if ( isset( $result[0] ) ) {
2844 unset( $result[0] );
2847 // Extract flags into the local scope
2848 // This allows callers to set flags such as nowiki, found, etc.
2855 wfProfileOut( __METHOD__
. '-pfunc' );
2858 # Finish mangling title and then check for loops.
2859 # Set $title to a Title object and $titleText to the PDBK
2862 # Split the title into page and subpage
2864 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2865 if ($subpage !== '') {
2866 $ns = $this->mTitle
->getNamespace();
2868 $title = Title
::newFromText( $part1, $ns );
2870 $titleText = $title->getPrefixedText();
2871 # Check for language variants if the template is not found
2872 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2873 $wgContLang->findVariantLink($part1, $title);
2875 # Do infinite loop check
2876 if ( !$frame->loopCheck( $title ) ) {
2878 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2879 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2881 # Do recursion depth check
2882 $limit = $this->mOptions
->getMaxTemplateDepth();
2883 if ( $frame->depth
>= $limit ) {
2885 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2890 # Load from database
2891 if ( !$found && $title ) {
2892 wfProfileIn( __METHOD__
. '-loadtpl' );
2893 if ( !$title->isExternal() ) {
2894 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2895 $text = SpecialPage
::capturePath( $title );
2896 if ( is_string( $text ) ) {
2899 $this->disableCache();
2901 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2902 $found = false; //access denied
2903 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2905 list( $text, $title ) = $this->getTemplateDom( $title );
2906 if ( $text !== false ) {
2912 # If the title is valid but undisplayable, make a link to it
2913 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2914 $text = "[[:$titleText]]";
2917 } elseif ( $title->isTrans() ) {
2918 // Interwiki transclusion
2919 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2920 $text = $this->interwikiTransclude( $title, 'render' );
2923 $text = $this->interwikiTransclude( $title, 'raw' );
2924 // Preprocess it like a template
2925 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2930 wfProfileOut( __METHOD__
. '-loadtpl' );
2933 # If we haven't found text to substitute by now, we're done
2934 # Recover the source wikitext and return it
2936 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2937 wfProfileOut( $fname );
2938 return array( 'object' => $text );
2941 # Expand DOM-style return values in a child frame
2942 if ( $isChildObj ) {
2943 # Clean up argument array
2944 $newFrame = $frame->newChild( $args, $title );
2947 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2948 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2949 # Expansion is eligible for the empty-frame cache
2950 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2951 $text = $this->mTplExpandCache
[$titleText];
2953 $text = $newFrame->expand( $text );
2954 $this->mTplExpandCache
[$titleText] = $text;
2957 # Uncached expansion
2958 $text = $newFrame->expand( $text );
2961 if ( $isLocalObj && $nowiki ) {
2962 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2963 $isLocalObj = false;
2966 # Replace raw HTML by a placeholder
2967 # Add a blank line preceding, to prevent it from mucking up
2968 # immediately preceding headings
2970 $text = "\n\n" . $this->insertStripItem( $text );
2972 # Escape nowiki-style return values
2973 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2974 $text = wfEscapeWikiText( $text );
2976 # Bug 529: if the template begins with a table or block-level
2977 # element, it should be treated as beginning a new line.
2978 # This behaviour is somewhat controversial.
2979 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2980 $text = "\n" . $text;
2983 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2984 # Error, oversize inclusion
2985 $text = "[[$originalTitle]]" .
2986 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2989 if ( $isLocalObj ) {
2990 $ret = array( 'object' => $text );
2992 $ret = array( 'text' => $text );
2995 wfProfileOut( $fname );
3000 * Get the semi-parsed DOM representation of a template with a given title,
3001 * and its redirect destination title. Cached.
3003 function getTemplateDom( $title ) {
3004 $cacheTitle = $title;
3005 $titleText = $title->getPrefixedDBkey();
3007 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3008 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3009 $title = Title
::makeTitle( $ns, $dbk );
3010 $titleText = $title->getPrefixedDBkey();
3012 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3013 return array( $this->mTplDomCache
[$titleText], $title );
3016 // Cache miss, go to the database
3017 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3019 if ( $text === false ) {
3020 $this->mTplDomCache
[$titleText] = false;
3021 return array( false, $title );
3024 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3025 $this->mTplDomCache
[ $titleText ] = $dom;
3027 if (! $title->equals($cacheTitle)) {
3028 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3029 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3032 return array( $dom, $title );
3036 * Fetch the unparsed text of a template and register a reference to it.
3038 function fetchTemplateAndTitle( $title ) {
3039 $templateCb = $this->mOptions
->getTemplateCallback();
3040 $stuff = call_user_func( $templateCb, $title );
3041 $text = $stuff['text'];
3042 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3043 if ( isset( $stuff['deps'] ) ) {
3044 foreach ( $stuff['deps'] as $dep ) {
3045 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3048 return array($text,$finalTitle);
3051 function fetchTemplate( $title ) {
3052 $rv = $this->fetchTemplateAndTitle($title);
3057 * Static function to get a template
3058 * Can be overridden via ParserOptions::setTemplateCallback().
3060 static function statelessFetchTemplate( $title ) {
3061 $text = $skip = false;
3062 $finalTitle = $title;
3065 // Loop to fetch the article, with up to 1 redirect
3066 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3067 # Give extensions a chance to select the revision instead
3068 $id = false; // Assume current
3069 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3075 'page_id' => $title->getArticleID(),
3079 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3080 $rev_id = $rev ?
$rev->getId() : 0;
3084 'page_id' => $title->getArticleID(),
3085 'rev_id' => $rev_id );
3088 $text = $rev->getText();
3089 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3091 $message = $wgLang->lcfirst( $title->getText() );
3092 $text = wfMsgForContentNoTrans( $message );
3093 if( wfEmptyMsg( $message, $text ) ) {
3100 if ( $text === false ) {
3104 $finalTitle = $title;
3105 $title = Title
::newFromRedirect( $text );
3109 'finalTitle' => $finalTitle,
3114 * Transclude an interwiki link.
3116 function interwikiTransclude( $title, $action ) {
3117 global $wgEnableScaryTranscluding;
3119 if (!$wgEnableScaryTranscluding)
3120 return wfMsg('scarytranscludedisabled');
3122 $url = $title->getFullUrl( "action=$action" );
3124 if (strlen($url) > 255)
3125 return wfMsg('scarytranscludetoolong');
3126 return $this->fetchScaryTemplateMaybeFromCache($url);
3129 function fetchScaryTemplateMaybeFromCache($url) {
3130 global $wgTranscludeCacheExpiry;
3131 $dbr = wfGetDB(DB_SLAVE
);
3132 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3133 array('tc_url' => $url));
3135 $time = $obj->tc_time
;
3136 $text = $obj->tc_contents
;
3137 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3142 $text = Http
::get($url);
3144 return wfMsg('scarytranscludefailed', $url);
3146 $dbw = wfGetDB(DB_MASTER
);
3147 $dbw->replace('transcache', array('tc_url'), array(
3149 'tc_time' => time(),
3150 'tc_contents' => $text));
3156 * Triple brace replacement -- used for template arguments
3159 function argSubstitution( $piece, $frame ) {
3160 wfProfileIn( __METHOD__
);
3163 $parts = $piece['parts'];
3164 $nameWithSpaces = $frame->expand( $piece['title'] );
3165 $argName = trim( $nameWithSpaces );
3167 $text = $frame->getArgument( $argName );
3168 if ( $text === false && ( $this->ot
['html'] ||
$this->ot
['pre'] ) && $parts->getLength() > 0 ) {
3169 # No match in frame, use the supplied default
3170 $object = $parts->item( 0 )->getChildren();
3172 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3173 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3176 if ( $text === false && $object === false ) {
3178 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3180 if ( $error !== false ) {
3183 if ( $object !== false ) {
3184 $ret = array( 'object' => $object );
3186 $ret = array( 'text' => $text );
3189 wfProfileOut( __METHOD__
);
3194 * Return the text to be used for a given extension tag.
3195 * This is the ghost of strip().
3197 * @param array $params Associative array of parameters:
3198 * name PPNode for the tag name
3199 * attr PPNode for unparsed text where tag attributes are thought to be
3200 * attributes Optional associative array of parsed attributes
3201 * inner Contents of extension element
3202 * noClose Original text did not have a close tag
3203 * @param PPFrame $frame
3205 function extensionSubstitution( $params, $frame ) {
3206 global $wgRawHtml, $wgContLang;
3209 $name = $frame->expand( $params['name'] );
3210 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3211 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3213 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
3215 if ( $this->ot
['html'] ) {
3216 $name = strtolower( $name );
3218 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3219 if ( isset( $params['attributes'] ) ) {
3220 $attributes = $attributes +
$params['attributes'];
3228 throw new MWException( '<html> extension tag encountered unexpectedly' );
3231 $output = Xml
::escapeTagsOnly( $content );
3234 $output = $wgContLang->armourMath(
3235 MathRenderer
::renderMath( $content, $attributes ) );
3238 $output = $this->renderImageGallery( $content, $attributes );
3241 if( isset( $this->mTagHooks
[$name] ) ) {
3242 $output = call_user_func_array( $this->mTagHooks
[$name],
3243 array( $content, $attributes, $this ) );
3245 throw new MWException( "Invalid call hook $name" );
3249 if ( is_null( $attrText ) ) {
3252 if ( isset( $params['attributes'] ) ) {
3253 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3254 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3255 htmlspecialchars( $attrValue ) . '"';
3258 if ( $content === null ) {
3259 $output = "<$name$attrText/>";
3261 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3262 $output = "<$name$attrText>$content$close";
3266 if ( $name == 'html' ||
$name == 'nowiki' ) {
3267 $this->mStripState
->nowiki
->setPair( $marker, $output );
3269 $this->mStripState
->general
->setPair( $marker, $output );
3275 * Increment an include size counter
3277 * @param string $type The type of expansion
3278 * @param integer $size The size of the text
3279 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3281 function incrementIncludeSize( $type, $size ) {
3282 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3285 $this->mIncludeSizes
[$type] +
= $size;
3291 * Detect __NOGALLERY__ magic word and set a placeholder
3293 function stripNoGallery( &$text ) {
3294 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3296 $mw = MagicWord
::get( 'nogallery' );
3297 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3301 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3302 * placeholder that will then be replaced by the real TOC in
3303 * ->formatHeadings, this works because at this points real
3304 * comments will have already been discarded by the sanitizer.
3306 * Any additional __TOC__ magic words left over will be discarded
3307 * as there can only be one TOC on the page.
3309 function stripToc( $text ) {
3310 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3312 $mw = MagicWord
::get( 'notoc' );
3313 if( $mw->matchAndRemove( $text ) ) {
3314 $this->mShowToc
= false;
3317 $mw = MagicWord
::get( 'toc' );
3318 if( $mw->match( $text ) ) {
3319 $this->mShowToc
= true;
3320 $this->mForceTocPosition
= true;
3322 // Set a placeholder. At the end we'll fill it in with the TOC.
3323 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3325 // Only keep the first one.
3326 $text = $mw->replace( '', $text );
3332 * This function accomplishes several tasks:
3333 * 1) Auto-number headings if that option is enabled
3334 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3335 * 3) Add a Table of contents on the top for users who have enabled the option
3336 * 4) Auto-anchor headings
3338 * It loops through all headlines, collects the necessary data, then splits up the
3339 * string and re-inserts the newly formatted headlines.
3341 * @param string $text
3342 * @param boolean $isMain
3345 function formatHeadings( $text, $isMain=true ) {
3346 global $wgMaxTocLevel, $wgContLang;
3348 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3349 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3352 $showEditLink = $this->mOptions
->getEditSection();
3355 # Inhibit editsection links if requested in the page
3356 $esw =& MagicWord
::get( 'noeditsection' );
3357 if( $esw->matchAndRemove( $text ) ) {
3361 # Get all headlines for numbering them and adding funky stuff like [edit]
3362 # links - this is for later, but we need the number of headlines right now
3364 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3366 # if there are fewer than 4 headlines in the article, do not show TOC
3367 # unless it's been explicitly enabled.
3368 $enoughToc = $this->mShowToc
&&
3369 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3371 # Allow user to stipulate that a page should have a "new section"
3372 # link added via __NEWSECTIONLINK__
3373 $mw =& MagicWord
::get( 'newsectionlink' );
3374 if( $mw->matchAndRemove( $text ) )
3375 $this->mOutput
->setNewSection( true );
3377 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3378 # override above conditions and always show TOC above first header
3379 $mw =& MagicWord
::get( 'forcetoc' );
3380 if ($mw->matchAndRemove( $text ) ) {
3381 $this->mShowToc
= true;
3385 # We need this to perform operations on the HTML
3386 $sk = $this->mOptions
->getSkin();
3392 # Ugh .. the TOC should have neat indentation levels which can be
3393 # passed to the skin functions. These are determined here
3397 $sublevelCount = array();
3398 $levelCount = array();
3404 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3405 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3408 foreach( $matches[3] as $headline ) {
3409 $isTemplate = false;
3411 $sectionIndex = false;
3413 $markerMatches = array();
3414 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3415 $serial = $markerMatches[1];
3416 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3417 $isTemplate = ($titleText != $baseTitleText);
3418 $headline = preg_replace("/^$markerRegex/", "", $headline);
3422 $prevlevel = $level;
3423 $prevtoclevel = $toclevel;
3425 $level = $matches[1][$headlineCount];
3427 if( $doNumberHeadings ||
$enoughToc ) {
3429 if ( $level > $prevlevel ) {
3430 # Increase TOC level
3432 $sublevelCount[$toclevel] = 0;
3433 if( $toclevel<$wgMaxTocLevel ) {
3434 $prevtoclevel = $toclevel;
3435 $toc .= $sk->tocIndent();
3439 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3440 # Decrease TOC level, find level to jump to
3442 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3443 # Can only go down to level 1
3446 for ($i = $toclevel; $i > 0; $i--) {
3447 if ( $levelCount[$i] == $level ) {
3448 # Found last matching level
3452 elseif ( $levelCount[$i] < $level ) {
3453 # Found first matching level below current level
3459 if( $toclevel<$wgMaxTocLevel ) {
3460 if($prevtoclevel < $wgMaxTocLevel) {
3461 # Unindent only if the previous toc level was shown :p
3462 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3464 $toc .= $sk->tocLineEnd();
3469 # No change in level, end TOC line
3470 if( $toclevel<$wgMaxTocLevel ) {
3471 $toc .= $sk->tocLineEnd();
3475 $levelCount[$toclevel] = $level;
3477 # count number of headlines for each level
3478 @$sublevelCount[$toclevel]++
;
3480 for( $i = 1; $i <= $toclevel; $i++
) {
3481 if( !empty( $sublevelCount[$i] ) ) {
3485 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3491 # The safe header is a version of the header text safe to use for links
3492 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3493 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3495 # Remove link placeholders by the link text.
3496 # <!--LINK number-->
3498 # link text with suffix
3499 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3500 "\$this->mLinkHolders['texts'][\$1]",
3502 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3503 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3506 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3507 $tocline = preg_replace(
3508 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3512 $tocline = trim( $tocline );
3514 # For the anchor, strip out HTML-y stuff period
3515 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3516 $safeHeadline = trim( $safeHeadline );
3518 # Save headline for section edit hint before it's escaped
3519 $headlineHint = $safeHeadline;
3520 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3521 $refers[$headlineCount] = $safeHeadline;
3523 # count how many in assoc. array so we can track dupes in anchors
3524 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3525 $refcount[$headlineCount] = $refers[$safeHeadline];
3527 # Don't number the heading if it is the only one (looks silly)
3528 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3529 # the two are different if the line contains a link
3530 $headline=$numbering . ' ' . $headline;
3533 # Create the anchor for linking from the TOC to the section
3534 $anchor = $safeHeadline;
3535 if($refcount[$headlineCount] > 1 ) {
3536 $anchor .= '_' . $refcount[$headlineCount];
3538 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3539 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3540 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3542 # give headline the correct <h#> tag
3543 if( $showEditLink && $sectionIndex !== false ) {
3545 # Put a T flag in the section identifier, to indicate to extractSections()
3546 # that sections inside <includeonly> should be counted.
3547 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3549 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3554 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3559 $this->mOutput
->setSections( $tocraw );
3561 # Never ever show TOC if no headers
3562 if( $numVisible < 1 ) {
3567 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3568 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3570 $toc = $sk->tocList( $toc );
3573 # split up and insert constructed headlines
3575 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3578 foreach( $blocks as $block ) {
3579 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3580 # This is the [edit] link that appears for the top block of text when
3581 # section editing is enabled
3583 # Disabled because it broke block formatting
3584 # For example, a bullet point in the top line
3585 # $full .= $sk->editSectionLink(0);
3588 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3589 # Top anchor now in skin
3593 if( !empty( $head[$i] ) ) {
3598 if( $this->mForceTocPosition
) {
3599 return str_replace( '<!--MWTOC-->', $toc, $full );
3606 * Transform wiki markup when saving a page by doing \r\n -> \n
3607 * conversion, substitting signatures, {{subst:}} templates, etc.
3609 * @param string $text the text to transform
3610 * @param Title &$title the Title object for the current article
3611 * @param User &$user the User object describing the current user
3612 * @param ParserOptions $options parsing options
3613 * @param bool $clearState whether to clear the parser state first
3614 * @return string the altered wiki markup
3617 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3618 $this->mOptions
= $options;
3619 $this->setTitle( $title );
3620 $this->setOutputType( self
::OT_WIKI
);
3622 if ( $clearState ) {
3623 $this->clearState();
3629 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3630 $text = $this->pstPass2( $text, $user );
3631 $text = $this->mStripState
->unstripBoth( $text );
3636 * Pre-save transform helper function
3639 function pstPass2( $text, $user ) {
3640 global $wgContLang, $wgLocaltimezone;
3642 /* Note: This is the timestamp saved as hardcoded wikitext to
3643 * the database, we use $wgContLang here in order to give
3644 * everyone the same signature and use the default one rather
3645 * than the one selected in each user's preferences.
3647 if ( isset( $wgLocaltimezone ) ) {
3648 $oldtz = getenv( 'TZ' );
3649 putenv( 'TZ='.$wgLocaltimezone );
3651 $d = $wgContLang->timeanddate( $this->mOptions
->getTimestamp(), false, false) .
3652 ' (' . date( 'T' ) . ')';
3653 if ( isset( $wgLocaltimezone ) ) {
3654 putenv( 'TZ='.$oldtz );
3657 # Variable replacement
3658 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3659 $text = $this->replaceVariables( $text );
3661 # Strip out <nowiki> etc. added via replaceVariables
3662 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
3665 $sigText = $this->getUserSig( $user );
3666 $text = strtr( $text, array(
3668 '~~~~' => "$sigText $d",
3672 # Context links: [[|name]] and [[name (context)|]]
3674 global $wgLegalTitleChars;
3675 $tc = "[$wgLegalTitleChars]";
3676 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3678 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3679 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3680 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3682 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3683 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3684 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3686 $t = $this->mTitle
->getText();
3688 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3689 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3690 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3691 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3693 # if there's no context, don't bother duplicating the title
3694 $text = preg_replace( $p2, '[[\\1]]', $text );
3697 # Trim trailing whitespace
3698 $text = rtrim( $text );
3704 * Fetch the user's signature text, if any, and normalize to
3705 * validated, ready-to-insert wikitext.
3711 function getUserSig( &$user ) {
3712 global $wgMaxSigChars;
3714 $username = $user->getName();
3715 $nickname = $user->getOption( 'nickname' );
3716 $nickname = $nickname === '' ?
$username : $nickname;
3718 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3719 $nickname = $username;
3720 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3721 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3722 # Sig. might contain markup; validate this
3723 if( $this->validateSig( $nickname ) !== false ) {
3724 # Validated; clean up (if needed) and return it
3725 return $this->cleanSig( $nickname, true );
3727 # Failed to validate; fall back to the default
3728 $nickname = $username;
3729 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3733 // Make sure nickname doesnt get a sig in a sig
3734 $nickname = $this->cleanSigInSig( $nickname );
3736 # If we're still here, make it a link to the user page
3737 $userText = wfEscapeWikiText( $username );
3738 $nickText = wfEscapeWikiText( $nickname );
3739 if ( $user->isAnon() ) {
3740 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3742 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3747 * Check that the user's signature contains no bad XML
3749 * @param string $text
3750 * @return mixed An expanded string, or false if invalid.
3752 function validateSig( $text ) {
3753 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3757 * Clean up signature text
3759 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3760 * 2) Substitute all transclusions
3762 * @param string $text
3763 * @param $parsing Whether we're cleaning (preferences save) or parsing
3764 * @return string Signature text
3766 function cleanSig( $text, $parsing = false ) {
3769 $this->clearState();
3770 $this->setTitle( $wgTitle );
3771 $this->mOptions
= new ParserOptions
;
3772 $this->setOutputType
= self
::OT_PREPROCESS
;
3775 # FIXME: regex doesn't respect extension tags or nowiki
3776 # => Move this logic to braceSubstitution()
3777 $substWord = MagicWord
::get( 'subst' );
3778 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3779 $substText = '{{' . $substWord->getSynonym( 0 );
3781 $text = preg_replace( $substRegex, $substText, $text );
3782 $text = $this->cleanSigInSig( $text );
3783 $dom = $this->preprocessToDom( $text );
3784 $frame = $this->getPreprocessor()->newFrame();
3785 $text = $frame->expand( $dom );
3788 $text = $this->mStripState
->unstripBoth( $text );
3795 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3796 * @param string $text
3797 * @return string Signature text with /~{3,5}/ removed
3799 function cleanSigInSig( $text ) {
3800 $text = preg_replace( '/~{3,5}/', '', $text );
3805 * Set up some variables which are usually set up in parse()
3806 * so that an external function can call some class members with confidence
3809 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3810 $this->setTitle( $title );
3811 $this->mOptions
= $options;
3812 $this->setOutputType( $outputType );
3813 if ( $clearState ) {
3814 $this->clearState();
3819 * Wrapper for preprocess()
3821 * @param string $text the text to preprocess
3822 * @param ParserOptions $options options
3826 function transformMsg( $text, $options ) {
3828 static $executing = false;
3830 $fname = "Parser::transformMsg";
3832 # Guard against infinite recursion
3838 wfProfileIn($fname);
3839 $text = $this->preprocess( $text, $wgTitle, $options );
3842 wfProfileOut($fname);
3847 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3848 * The callback should have the following form:
3849 * function myParserHook( $text, $params, &$parser ) { ... }
3851 * Transform and return $text. Use $parser for any required context, e.g. use
3852 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3856 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3857 * @param mixed $callback The callback function (and object) to use for the tag
3859 * @return The old value of the mTagHooks array associated with the hook
3861 function setHook( $tag, $callback ) {
3862 $tag = strtolower( $tag );
3863 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3864 $this->mTagHooks
[$tag] = $callback;
3865 $this->mStripList
[] = $tag;
3870 function setTransparentTagHook( $tag, $callback ) {
3871 $tag = strtolower( $tag );
3872 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3873 $this->mTransparentTagHooks
[$tag] = $callback;
3879 * Remove all tag hooks
3881 function clearTagHooks() {
3882 $this->mTagHooks
= array();
3883 $this->mStripList
= $this->mDefaultStripList
;
3887 * Create a function, e.g. {{sum:1|2|3}}
3888 * The callback function should have the form:
3889 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3891 * The callback may either return the text result of the function, or an array with the text
3892 * in element 0, and a number of flags in the other elements. The names of the flags are
3893 * specified in the keys. Valid flags are:
3894 * found The text returned is valid, stop processing the template. This
3896 * nowiki Wiki markup in the return value should be escaped
3897 * isHTML The returned text is HTML, armour it against wikitext transformation
3901 * @param string $id The magic word ID
3902 * @param mixed $callback The callback function (and object) to use
3903 * @param integer $flags a combination of the following flags:
3904 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3906 * @return The old callback function for this name, if any
3908 function setFunctionHook( $id, $callback, $flags = 0 ) {
3909 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3910 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3912 # Add to function cache
3913 $mw = MagicWord
::get( $id );
3915 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3917 $synonyms = $mw->getSynonyms();
3918 $sensitive = intval( $mw->isCaseSensitive() );
3920 foreach ( $synonyms as $syn ) {
3922 if ( !$sensitive ) {
3923 $syn = strtolower( $syn );
3926 if ( !( $flags & SFH_NO_HASH
) ) {
3929 # Remove trailing colon
3930 if ( substr( $syn, -1, 1 ) == ':' ) {
3931 $syn = substr( $syn, 0, -1 );
3933 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3939 * Get all registered function hook identifiers
3943 function getFunctionHooks() {
3944 return array_keys( $this->mFunctionHooks
);
3948 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3949 * Placeholders created in Skin::makeLinkObj()
3950 * Returns an array of link CSS classes, indexed by PDBK.
3951 * $options is a bit field, RLH_FOR_UPDATE to select for update
3953 function replaceLinkHolders( &$text, $options = 0 ) {
3957 $fname = 'Parser::replaceLinkHolders';
3958 wfProfileIn( $fname );
3962 $linkcolour_ids = array();
3963 $sk = $this->mOptions
->getSkin();
3964 $linkCache =& LinkCache
::singleton();
3966 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3967 wfProfileIn( $fname.'-check' );
3968 $dbr = wfGetDB( DB_SLAVE
);
3969 $page = $dbr->tableName( 'page' );
3970 $threshold = $wgUser->getOption('stubthreshold');
3973 asort( $this->mLinkHolders
['namespaces'] );
3978 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3980 $title = $this->mLinkHolders
['titles'][$key];
3982 # Skip invalid entries.
3983 # Result will be ugly, but prevents crash.
3984 if ( is_null( $title ) ) {
3987 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3989 # Check if it's a static known link, e.g. interwiki
3990 if ( $title->isAlwaysKnown() ) {
3991 $colours[$pdbk] = '';
3992 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3993 $colours[$pdbk] = '';
3994 $this->mOutput
->addLink( $title, $id );
3995 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3996 $colours[$pdbk] = 'new';
3997 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
3998 $colours[$pdbk] = 'new';
4000 # Not in the link cache, add it to the query
4001 if ( !isset( $current ) ) {
4003 $query = "SELECT page_id, page_namespace, page_title";
4004 if ( $threshold > 0 ) {
4005 $query .= ', page_len, page_is_redirect';
4007 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4008 } elseif ( $current != $ns ) {
4010 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4015 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4020 if ( $options & RLH_FOR_UPDATE
) {
4021 $query .= ' FOR UPDATE';
4024 $res = $dbr->query( $query, $fname );
4026 # Fetch data and form into an associative array
4027 # non-existent = broken
4028 while ( $s = $dbr->fetchObject($res) ) {
4029 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4030 $pdbk = $title->getPrefixedDBkey();
4031 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4032 $this->mOutput
->addLink( $title, $s->page_id
);
4033 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4034 //add id to the extension todolist
4035 $linkcolour_ids[$s->page_id
] = $pdbk;
4037 //pass an array of page_ids to an extension
4038 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4040 wfProfileOut( $fname.'-check' );
4042 # Do a second query for different language variants of links and categories
4043 if($wgContLang->hasVariants()){
4044 $linkBatch = new LinkBatch();
4045 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4046 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4047 $varCategories = array(); // category replacements oldDBkey => newDBkey
4049 $categories = $this->mOutput
->getCategoryLinks();
4051 // Add variants of links to link batch
4052 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4053 $title = $this->mLinkHolders
['titles'][$key];
4054 if ( is_null( $title ) )
4057 $pdbk = $title->getPrefixedDBkey();
4058 $titleText = $title->getText();
4060 // generate all variants of the link title text
4061 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4063 // if link was not found (in first query), add all variants to query
4064 if ( !isset($colours[$pdbk]) ){
4065 foreach($allTextVariants as $textVariant){
4066 if($textVariant != $titleText){
4067 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4068 if(is_null($variantTitle)) continue;
4069 $linkBatch->addObj( $variantTitle );
4070 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4076 // process categories, check if a category exists in some variant
4077 foreach( $categories as $category ){
4078 $variants = $wgContLang->convertLinkToAllVariants($category);
4079 foreach($variants as $variant){
4080 if($variant != $category){
4081 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4082 if(is_null($variantTitle)) continue;
4083 $linkBatch->addObj( $variantTitle );
4084 $categoryMap[$variant] = $category;
4090 if(!$linkBatch->isEmpty()){
4092 $titleClause = $linkBatch->constructSet('page', $dbr);
4094 $variantQuery = "SELECT page_id, page_namespace, page_title";
4095 if ( $threshold > 0 ) {
4096 $variantQuery .= ', page_len, page_is_redirect';
4099 $variantQuery .= " FROM $page WHERE $titleClause";
4100 if ( $options & RLH_FOR_UPDATE
) {
4101 $variantQuery .= ' FOR UPDATE';
4104 $varRes = $dbr->query( $variantQuery, $fname );
4106 // for each found variants, figure out link holders and replace
4107 while ( $s = $dbr->fetchObject($varRes) ) {
4109 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4110 $varPdbk = $variantTitle->getPrefixedDBkey();
4111 $vardbk = $variantTitle->getDBkey();
4113 $holderKeys = array();
4114 if(isset($variantMap[$varPdbk])){
4115 $holderKeys = $variantMap[$varPdbk];
4116 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4117 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4120 // loop over link holders
4121 foreach($holderKeys as $key){
4122 $title = $this->mLinkHolders
['titles'][$key];
4123 if ( is_null( $title ) ) continue;
4125 $pdbk = $title->getPrefixedDBkey();
4127 if(!isset($colours[$pdbk])){
4128 // found link in some of the variants, replace the link holder data
4129 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4130 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4132 // set pdbk and colour
4133 $pdbks[$key] = $varPdbk;
4134 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4135 $linkcolour_ids[$s->page_id
] = $pdbk;
4137 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4140 // check if the object is a variant of a category
4141 if(isset($categoryMap[$vardbk])){
4142 $oldkey = $categoryMap[$vardbk];
4143 if($oldkey != $vardbk)
4144 $varCategories[$oldkey]=$vardbk;
4148 // rebuild the categories in original order (if there are replacements)
4149 if(count($varCategories)>0){
4151 $originalCats = $this->mOutput
->getCategories();
4152 foreach($originalCats as $cat => $sortkey){
4153 // make the replacement
4154 if( array_key_exists($cat,$varCategories) )
4155 $newCats[$varCategories[$cat]] = $sortkey;
4156 else $newCats[$cat] = $sortkey;
4158 $this->mOutput
->setCategoryLinks($newCats);
4163 # Construct search and replace arrays
4164 wfProfileIn( $fname.'-construct' );
4165 $replacePairs = array();
4166 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4167 $pdbk = $pdbks[$key];
4168 $searchkey = "<!--LINK $key-->";
4169 $title = $this->mLinkHolders
['titles'][$key];
4170 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4171 $linkCache->addBadLinkObj( $title );
4172 $colours[$pdbk] = 'new';
4173 $this->mOutput
->addLink( $title, 0 );
4174 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4175 $this->mLinkHolders
['texts'][$key],
4176 $this->mLinkHolders
['queries'][$key] );
4178 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4179 $this->mLinkHolders
['texts'][$key],
4180 $this->mLinkHolders
['queries'][$key] );
4183 $replacer = new HashtableReplacer( $replacePairs, 1 );
4184 wfProfileOut( $fname.'-construct' );
4187 wfProfileIn( $fname.'-replace' );
4188 $text = preg_replace_callback(
4189 '/(<!--LINK .*?-->)/',
4193 wfProfileOut( $fname.'-replace' );
4196 # Now process interwiki link holders
4197 # This is quite a bit simpler than internal links
4198 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4199 wfProfileIn( $fname.'-interwiki' );
4200 # Make interwiki link HTML
4201 $replacePairs = array();
4202 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4203 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4204 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4206 $replacer = new HashtableReplacer( $replacePairs, 1 );
4208 $text = preg_replace_callback(
4209 '/<!--IWLINK (.*?)-->/',
4212 wfProfileOut( $fname.'-interwiki' );
4215 wfProfileOut( $fname );
4220 * Replace <!--LINK--> link placeholders with plain text of links
4221 * (not HTML-formatted).
4222 * @param string $text
4225 function replaceLinkHoldersText( $text ) {
4226 $fname = 'Parser::replaceLinkHoldersText';
4227 wfProfileIn( $fname );
4229 $text = preg_replace_callback(
4230 '/<!--(LINK|IWLINK) (.*?)-->/',
4231 array( &$this, 'replaceLinkHoldersTextCallback' ),
4234 wfProfileOut( $fname );
4239 * @param array $matches
4243 function replaceLinkHoldersTextCallback( $matches ) {
4244 $type = $matches[1];
4246 if( $type == 'LINK' ) {
4247 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4248 return $this->mLinkHolders
['texts'][$key];
4250 } elseif( $type == 'IWLINK' ) {
4251 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4252 return $this->mInterwikiLinkHolders
['texts'][$key];
4259 * Tag hook handler for 'pre'.
4261 function renderPreTag( $text, $attribs ) {
4262 // Backwards-compatibility hack
4263 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4265 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4266 return wfOpenElement( 'pre', $attribs ) .
4267 Xml
::escapeTagsOnly( $content ) .
4272 * Renders an image gallery from a text with one line per image.
4273 * text labels may be given by using |-style alternative text. E.g.
4274 * Image:one.jpg|The number "1"
4275 * Image:tree.jpg|A tree
4276 * given as text will return the HTML of a gallery with two images,
4277 * labeled 'The number "1"' and
4280 function renderImageGallery( $text, $params ) {
4281 $ig = new ImageGallery();
4282 $ig->setContextTitle( $this->mTitle
);
4283 $ig->setShowBytes( false );
4284 $ig->setShowFilename( false );
4285 $ig->setParser( $this );
4286 $ig->setHideBadImages();
4287 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4288 $ig->useSkin( $this->mOptions
->getSkin() );
4289 $ig->mRevisionId
= $this->mRevisionId
;
4291 if( isset( $params['caption'] ) ) {
4292 $caption = $params['caption'];
4293 $caption = htmlspecialchars( $caption );
4294 $caption = $this->replaceInternalLinks( $caption );
4295 $ig->setCaptionHtml( $caption );
4297 if( isset( $params['perrow'] ) ) {
4298 $ig->setPerRow( $params['perrow'] );
4300 if( isset( $params['widths'] ) ) {
4301 $ig->setWidths( $params['widths'] );
4303 if( isset( $params['heights'] ) ) {
4304 $ig->setHeights( $params['heights'] );
4307 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4309 $lines = explode( "\n", $text );
4310 foreach ( $lines as $line ) {
4311 # match lines like these:
4312 # Image:someimage.jpg|This is some image
4314 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4316 if ( count( $matches ) == 0 ) {
4319 $tp = Title
::newFromText( $matches[1] );
4321 if( is_null( $nt ) ) {
4322 # Bogus title. Ignore these so we don't bomb out later.
4325 if ( isset( $matches[3] ) ) {
4326 $label = $matches[3];
4331 $html = $this->recursiveTagParse( trim( $label ) );
4333 $ig->add( $nt, $html );
4335 # Only add real images (bug #5586)
4336 if ( $nt->getNamespace() == NS_IMAGE
) {
4337 $this->mOutput
->addImage( $nt->getDBkey() );
4340 return $ig->toHTML();
4343 function getImageParams( $handler ) {
4345 $handlerClass = get_class( $handler );
4349 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4350 // Initialise static lists
4351 static $internalParamNames = array(
4352 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4353 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4354 'bottom', 'text-bottom' ),
4355 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4356 'upright', 'border' ),
4358 static $internalParamMap;
4359 if ( !$internalParamMap ) {
4360 $internalParamMap = array();
4361 foreach ( $internalParamNames as $type => $names ) {
4362 foreach ( $names as $name ) {
4363 $magicName = str_replace( '-', '_', "img_$name" );
4364 $internalParamMap[$magicName] = array( $type, $name );
4369 // Add handler params
4370 $paramMap = $internalParamMap;
4372 $handlerParamMap = $handler->getParamMap();
4373 foreach ( $handlerParamMap as $magic => $paramName ) {
4374 $paramMap[$magic] = array( 'handler', $paramName );
4377 $this->mImageParams
[$handlerClass] = $paramMap;
4378 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4380 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4384 * Parse image options text and use it to make an image
4386 function makeImage( $title, $options ) {
4387 # @TODO: let the MediaHandler specify its transform parameters
4389 # Check if the options text is of the form "options|alt text"
4391 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4392 # * left no resizing, just left align. label is used for alt= only
4393 # * right same, but right aligned
4394 # * none same, but not aligned
4395 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4396 # * center center the image
4397 # * framed Keep original image size, no magnify-button.
4398 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4399 # * upright reduce width for upright images, rounded to full __0 px
4400 # * border draw a 1px border around the image
4401 # vertical-align values (no % or length right now):
4411 $parts = array_map( 'trim', explode( '|', $options) );
4412 $sk = $this->mOptions
->getSkin();
4414 # Give extensions a chance to select the file revision for us
4415 $skip = $time = false;
4416 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4419 return $sk->makeLinkObj( $title );
4423 $file = wfFindFile( $title, $time );
4424 $handler = $file ?
$file->getHandler() : false;
4426 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4428 # Process the input parameters
4430 $params = array( 'frame' => array(), 'handler' => array(),
4431 'horizAlign' => array(), 'vertAlign' => array() );
4432 foreach( $parts as $part ) {
4433 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4434 if ( isset( $paramMap[$magicName] ) ) {
4435 list( $type, $paramName ) = $paramMap[$magicName];
4436 $params[$type][$paramName] = $value;
4438 // Special case; width and height come in one variable together
4439 if( $type == 'handler' && $paramName == 'width' ) {
4441 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4442 $params[$type]['width'] = intval( $m[1] );
4443 $params[$type]['height'] = intval( $m[2] );
4445 $params[$type]['width'] = intval( $value );
4453 # Process alignment parameters
4454 if ( $params['horizAlign'] ) {
4455 $params['frame']['align'] = key( $params['horizAlign'] );
4457 if ( $params['vertAlign'] ) {
4458 $params['frame']['valign'] = key( $params['vertAlign'] );
4461 # Validate the handler parameters
4463 foreach ( $params['handler'] as $name => $value ) {
4464 if ( !$handler->validateParam( $name, $value ) ) {
4465 unset( $params['handler'][$name] );
4470 # Strip bad stuff out of the alt text
4471 $alt = $this->replaceLinkHoldersText( $caption );
4473 # make sure there are no placeholders in thumbnail attributes
4474 # that are later expanded to html- so expand them now and
4476 $alt = $this->mStripState
->unstripBoth( $alt );
4477 $alt = Sanitizer
::stripAllTags( $alt );
4479 $params['frame']['alt'] = $alt;
4480 $params['frame']['caption'] = $caption;
4482 # Linker does the rest
4483 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4485 # Give the handler a chance to modify the parser object
4487 $handler->parserTransformHook( $this, $file );
4494 * Set a flag in the output object indicating that the content is dynamic and
4495 * shouldn't be cached.
4497 function disableCache() {
4498 wfDebug( "Parser output marked as uncacheable.\n" );
4499 $this->mOutput
->mCacheTime
= -1;
4503 * Callback from the Sanitizer for expanding items found in HTML attribute
4504 * values, so they can be safely tested and escaped.
4505 * @param string $text
4506 * @param PPFrame $frame
4510 function attributeStripCallback( &$text, $frame = false ) {
4511 $text = $this->replaceVariables( $text, $frame );
4512 $text = $this->mStripState
->unstripBoth( $text );
4521 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4522 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4523 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4529 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4534 * Break wikitext input into sections, and either pull or replace
4535 * some particular section's text.
4537 * External callers should use the getSection and replaceSection methods.
4539 * @param string $text Page wikitext
4540 * @param string $section A section identifier string of the form:
4541 * <flag1> - <flag2> - ... - <section number>
4543 * Currently the only recognised flag is "T", which means the target section number
4544 * was derived during a template inclusion parse, in other words this is a template
4545 * section edit link. If no flags are given, it was an ordinary section edit link.
4546 * This flag is required to avoid a section numbering mismatch when a section is
4547 * enclosed by <includeonly> (bug 6563).
4549 * The section number 0 pulls the text before the first heading; other numbers will
4550 * pull the given section along with its lower-level subsections. If the section is
4551 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4553 * @param string $mode One of "get" or "replace"
4554 * @param string $newText Replacement text for section data.
4555 * @return string for "get", the extracted section text.
4556 * for "replace", the whole page with the section replaced.
4558 private function extractSections( $text, $section, $mode, $newText='' ) {
4560 $this->clearState();
4561 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4562 $this->mOptions
= new ParserOptions
;
4563 $this->setOutputType( self
::OT_WIKI
);
4566 $frame = $this->getPreprocessor()->newFrame();
4568 // Process section extraction flags
4570 $sectionParts = explode( '-', $section );
4571 $sectionIndex = array_pop( $sectionParts );
4572 foreach ( $sectionParts as $part ) {
4573 if ( $part == 'T' ) {
4574 $flags |
= self
::PTD_FOR_INCLUSION
;
4577 // Preprocess the text
4578 $root = $this->preprocessToDom( $text, $flags );
4580 // <h> nodes indicate section breaks
4581 // They can only occur at the top level, so we can find them by iterating the root's children
4582 $node = $root->getFirstChild();
4584 // Find the target section
4585 if ( $sectionIndex == 0 ) {
4586 // Section zero doesn't nest, level=big
4587 $targetLevel = 1000;
4590 if ( $node->getName() == 'h' ) {
4591 if ( $curIndex +
1 == $sectionIndex ) {
4596 if ( $mode == 'replace' ) {
4597 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4599 $node = $node->getNextSibling();
4602 $bits = $node->splitHeading();
4603 $targetLevel = $bits['level'];
4609 if ( $mode == 'get' ) {
4616 // Find the end of the section, including nested sections
4618 if ( $node->getName() == 'h' ) {
4620 $bits = $node->splitHeading();
4621 $curLevel = $bits['level'];
4622 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
4626 if ( $mode == 'get' ) {
4627 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4629 $node = $node->getNextSibling();
4632 // Write out the remainder (in replace mode only)
4633 if ( $mode == 'replace' ) {
4634 // Output the replacement text
4635 // Add two newlines on -- trailing whitespace in $newText is conventionally
4636 // stripped by the editor, so we need both newlines to restore the paragraph gap
4637 $outText .= $newText . "\n\n";
4639 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4640 $node = $node->getNextSibling();
4644 if ( is_string( $outText ) ) {
4645 // Re-insert stripped tags
4646 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4653 * This function returns the text of a section, specified by a number ($section).
4654 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4655 * the first section before any such heading (section 0).
4657 * If a section contains subsections, these are also returned.
4659 * @param string $text text to look in
4660 * @param string $section section identifier
4661 * @param string $deftext default to return if section is not found
4662 * @return string text of the requested section
4664 public function getSection( $text, $section, $deftext='' ) {
4665 return $this->extractSections( $text, $section, "get", $deftext );
4668 public function replaceSection( $oldtext, $section, $text ) {
4669 return $this->extractSections( $oldtext, $section, "replace", $text );
4673 * Get the timestamp associated with the current revision, adjusted for
4674 * the default server-local timestamp
4676 function getRevisionTimestamp() {
4677 if ( is_null( $this->mRevisionTimestamp
) ) {
4678 wfProfileIn( __METHOD__
);
4680 $dbr = wfGetDB( DB_SLAVE
);
4681 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4682 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4684 // Normalize timestamp to internal MW format for timezone processing.
4685 // This has the added side-effect of replacing a null value with
4686 // the current time, which gives us more sensible behavior for
4688 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4690 // The cryptic '' timezone parameter tells to use the site-default
4691 // timezone offset instead of the user settings.
4693 // Since this value will be saved into the parser cache, served
4694 // to other users, and potentially even used inside links and such,
4695 // it needs to be consistent for all visitors.
4696 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4698 wfProfileOut( __METHOD__
);
4700 return $this->mRevisionTimestamp
;
4704 * Mutator for $mDefaultSort
4706 * @param $sort New value
4708 public function setDefaultSort( $sort ) {
4709 $this->mDefaultSort
= $sort;
4713 * Accessor for $mDefaultSort
4714 * Will use the title/prefixed title if none is set
4718 public function getDefaultSort() {
4719 if( $this->mDefaultSort
!== false ) {
4720 return $this->mDefaultSort
;
4722 return $this->mTitle
->getNamespace() == NS_CATEGORY
4723 ?
$this->mTitle
->getText()
4724 : $this->mTitle
->getPrefixedText();
4729 * Try to guess the section anchor name based on a wikitext fragment
4730 * presumably extracted from a heading, for example "Header" from
4733 public function guessSectionNameFromWikiText( $text ) {
4734 # Strip out wikitext links(they break the anchor)
4735 $text = $this->stripSectionName( $text );
4736 $headline = Sanitizer
::decodeCharReferences( $text );
4738 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4739 $headline = trim( $headline );
4740 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4741 $replacearray = array(
4746 array_keys( $replacearray ),
4747 array_values( $replacearray ),
4752 * Strips a text string of wikitext for use in a section anchor
4754 * Accepts a text string and then removes all wikitext from the
4755 * string and leaves only the resultant text (i.e. the result of
4756 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4757 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4758 * to create valid section anchors by mimicing the output of the
4759 * parser when headings are parsed.
4761 * @param $text string Text string to be stripped of wikitext
4762 * for use in a Section anchor
4763 * @return Filtered text string
4765 public function stripSectionName( $text ) {
4766 # Strip internal link markup
4767 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4768 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4770 # Strip external link markup (FIXME: Not Tolerant to blank link text
4771 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4772 # on how many empty links there are on the page - need to figure that out.
4773 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4775 # Parse wikitext quotes (italics & bold)
4776 $text = $this->doQuotes($text);
4779 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4783 function srvus( $text ) {
4784 return $this->testSrvus( $text, $this->mOutputType
);
4788 * strip/replaceVariables/unstrip for preprocessor regression testing
4790 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4791 $this->clearState();
4792 if ( ! ( $title instanceof Title
) ) {
4793 $title = Title
::newFromText( $title );
4795 $this->mTitle
= $title;
4796 $this->mOptions
= $options;
4797 $this->setOutputType( $outputType );
4798 $text = $this->replaceVariables( $text );
4799 $text = $this->mStripState
->unstripBoth( $text );
4800 $text = Sanitizer
::removeHTMLtags( $text );
4804 function testPst( $text, $title, $options ) {
4806 if ( ! ( $title instanceof Title
) ) {
4807 $title = Title
::newFromText( $title );
4809 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4812 function testPreprocess( $text, $title, $options ) {
4813 if ( ! ( $title instanceof Title
) ) {
4814 $title = Title
::newFromText( $title );
4816 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4821 * @todo document, briefly.
4822 * @addtogroup Parser
4825 var $general, $nowiki;
4827 function __construct() {
4828 $this->general
= new ReplacementArray
;
4829 $this->nowiki
= new ReplacementArray
;
4832 function unstripGeneral( $text ) {
4833 wfProfileIn( __METHOD__
);
4836 $text = $this->general
->replace( $text );
4837 } while ( $text != $oldText );
4838 wfProfileOut( __METHOD__
);
4842 function unstripNoWiki( $text ) {
4843 wfProfileIn( __METHOD__
);
4846 $text = $this->nowiki
->replace( $text );
4847 } while ( $text != $oldText );
4848 wfProfileOut( __METHOD__
);
4852 function unstripBoth( $text ) {
4853 wfProfileIn( __METHOD__
);
4856 $text = $this->general
->replace( $text );
4857 $text = $this->nowiki
->replace( $text );
4858 } while ( $text != $oldText );
4859 wfProfileOut( __METHOD__
);
4865 * @todo document, briefly.
4866 * @addtogroup Parser
4868 class OnlyIncludeReplacer
{
4871 function replace( $matches ) {
4872 if ( substr( $matches[1], -1 ) == "\n" ) {
4873 $this->output
.= substr( $matches[1], 0, -1 );
4875 $this->output
.= $matches[1];