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, $mMarkerIndex,
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->mMarkerIndex
= 0;
137 $this->mFirstCall
= true;
141 * Do various kinds of initialisation on the first call of the parser
143 function firstCallInit() {
144 if ( !$this->mFirstCall
) {
147 $this->mFirstCall
= false;
149 wfProfileIn( __METHOD__
);
150 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
152 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
154 # Syntax for arguments (see self::setFunctionHook):
155 # "name for lookup in localized magic words array",
157 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
158 # instead of {{#int:...}})
159 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
174 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
175 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
176 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
177 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
178 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
179 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
180 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
181 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
182 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
183 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
184 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
185 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
186 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS
);
188 if ( $wgAllowDisplayTitle ) {
189 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
191 if ( $wgAllowSlowParserFunctions ) {
192 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
195 $this->initialiseVariables();
197 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
198 wfProfileOut( __METHOD__
);
206 function clearState() {
207 wfProfileIn( __METHOD__
);
208 if ( $this->mFirstCall
) {
209 $this->firstCallInit();
211 $this->mOutput
= new ParserOutput
;
212 $this->mAutonumber
= 0;
213 $this->mLastSection
= '';
214 $this->mDTopen
= false;
215 $this->mIncludeCount
= array();
216 $this->mStripState
= new StripState
;
217 $this->mArgStack
= false;
218 $this->mInPre
= false;
219 $this->mInterwikiLinkHolders
= array(
223 $this->mLinkHolders
= array(
224 'namespaces' => array(),
226 'queries' => array(),
230 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
233 * Prefix for temporary replacement strings for the multipass parser.
234 * \x07 should never appear in input as it's disallowed in XML.
235 * Using it at the front also gives us a little extra robustness
236 * since it shouldn't match when butted up against identifier-like
239 * Must not consist of all title characters, or else it will change
240 * the behaviour of <nowiki> in a link.
242 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
243 # Changed to \x7f to allow XML double-parsing -- TS
244 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
247 # Clear these on every parse, bug 4549
248 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
250 $this->mShowToc
= true;
251 $this->mForceTocPosition
= false;
252 $this->mIncludeSizes
= array(
256 $this->mPPNodeCount
= 0;
257 $this->mDefaultSort
= false;
258 $this->mHeadings
= array();
261 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
262 $this->mPreprocessor
= null;
265 wfRunHooks( 'ParserClearState', array( &$this ) );
266 wfProfileOut( __METHOD__
);
269 function setOutputType( $ot ) {
270 $this->mOutputType
= $ot;
273 'html' => $ot == self
::OT_HTML
,
274 'wiki' => $ot == self
::OT_WIKI
,
275 'pre' => $ot == self
::OT_PREPROCESS
,
280 * Set the context title
282 function setTitle( $t ) {
283 if ( !$t ||
$t instanceof FakeTitle
) {
284 $t = Title
::newFromText( 'NO TITLE' );
286 if ( strval( $t->getFragment() ) !== '' ) {
287 # Strip the fragment to avoid various odd effects
288 $this->mTitle
= clone $t;
289 $this->mTitle
->setFragment( '' );
296 * Accessor for mUniqPrefix.
300 function uniqPrefix() {
301 if( !isset( $this->mUniqPrefix
) ) {
302 // @fixme this is probably *horribly wrong*
303 // LanguageConverter seems to want $wgParser's uniqPrefix, however
304 // if this is called for a parser cache hit, the parser may not
305 // have ever been initialized in the first place.
306 // Not really sure what the heck is supposed to be going on here.
308 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
310 return $this->mUniqPrefix
;
314 * Convert wikitext to HTML
315 * Do not call this function recursively.
317 * @param string $text Text we want to parse
318 * @param Title &$title A title object
319 * @param array $options
320 * @param boolean $linestart
321 * @param boolean $clearState
322 * @param int $revid number to pass in {{REVISIONID}}
323 * @return ParserOutput a ParserOutput
325 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
327 * First pass--just handle <nowiki> sections, pass the rest off
328 * to internalParse() which does all the real work.
331 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
332 $fname = 'Parser::parse-' . wfGetCaller();
333 wfProfileIn( __METHOD__
);
334 wfProfileIn( $fname );
340 $this->mOptions
= $options;
341 $this->setTitle( $title );
342 $oldRevisionId = $this->mRevisionId
;
343 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
344 if( $revid !== null ) {
345 $this->mRevisionId
= $revid;
346 $this->mRevisionTimestamp
= null;
348 $this->setOutputType( self
::OT_HTML
);
349 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
351 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
352 $text = $this->internalParse( $text );
353 $text = $this->mStripState
->unstripGeneral( $text );
355 # Clean up special characters, only run once, next-to-last before doBlockLevels
357 # french spaces, last one Guillemet-left
358 # only if there is something before the space
359 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
360 # french spaces, Guillemet-right
361 '/(\\302\\253) /' => '\\1 ',
363 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
366 $text = $this->doBlockLevels( $text, $linestart );
368 $this->replaceLinkHolders( $text );
370 # the position of the parserConvert() call should not be changed. it
371 # assumes that the links are all replaced and the only thing left
372 # is the <nowiki> mark.
373 # Side-effects: this calls $this->mOutput->setTitleText()
374 $text = $wgContLang->parserConvert( $text, $this );
376 $text = $this->mStripState
->unstripNoWiki( $text );
378 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
380 //!JF Move to its own function
382 $uniq_prefix = $this->mUniqPrefix
;
384 $elements = array_keys( $this->mTransparentTagHooks
);
385 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
387 foreach( $matches as $marker => $data ) {
388 list( $element, $content, $params, $tag ) = $data;
389 $tagName = strtolower( $element );
390 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
391 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
392 array( $content, $params, $this ) );
396 $this->mStripState
->general
->setPair( $marker, $output );
398 $text = $this->mStripState
->unstripGeneral( $text );
400 $text = Sanitizer
::normalizeCharReferences( $text );
402 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
403 $text = Parser
::tidy($text);
405 # attempt to sanitize at least some nesting problems
406 # (bug #2702 and quite a few others)
408 # ''Something [http://www.cool.com cool''] -->
409 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
410 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
411 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
412 # fix up an anchor inside another anchor, only
413 # at least for a single single nested link (bug 3695)
414 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
415 '\\1\\2</a>\\3</a>\\1\\4</a>',
416 # fix div inside inline elements- doBlockLevels won't wrap a line which
417 # contains a div, so fix it up here; replace
418 # div with escaped text
419 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
420 '\\1\\3<div\\5>\\6</div>\\8\\9',
421 # remove empty italic or bold tag pairs, some
422 # introduced by rules above
423 '/<([bi])><\/\\1>/' => '',
426 $text = preg_replace(
427 array_keys( $tidyregs ),
428 array_values( $tidyregs ),
432 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
434 # Information on include size limits, for the benefit of users who try to skirt them
435 if ( $this->mOptions
->getEnableLimitReport() ) {
436 $max = $this->mOptions
->getMaxIncludeSize();
438 "NewPP limit report\n" .
439 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
440 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
441 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
442 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
443 $text .= "\n<!-- \n$limitReport-->\n";
445 $this->mOutput
->setText( $text );
446 $this->mRevisionId
= $oldRevisionId;
447 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
448 wfProfileOut( $fname );
449 wfProfileOut( __METHOD__
);
451 return $this->mOutput
;
455 * Recursive parser entry point that can be called from an extension tag
458 function recursiveTagParse( $text ) {
459 wfProfileIn( __METHOD__
);
460 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
461 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
462 $text = $this->internalParse( $text );
463 wfProfileOut( __METHOD__
);
468 * Expand templates and variables in the text, producing valid, static wikitext.
469 * Also removes comments.
471 function preprocess( $text, $title, $options, $revid = null ) {
472 wfProfileIn( __METHOD__
);
474 $this->setOutputType( self
::OT_PREPROCESS
);
475 $this->mOptions
= $options;
476 $this->setTitle( $title );
477 if( $revid !== null ) {
478 $this->mRevisionId
= $revid;
480 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
481 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
482 $text = $this->replaceVariables( $text );
483 $text = $this->mStripState
->unstripBoth( $text );
484 wfProfileOut( __METHOD__
);
489 * Get a random string
494 function getRandomString() {
495 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
498 function &getTitle() { return $this->mTitle
; }
499 function getOptions() { return $this->mOptions
; }
501 function getFunctionLang() {
502 global $wgLang, $wgContLang;
503 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
507 * Get a preprocessor object
509 function getPreprocessor() {
510 if ( !isset( $this->mPreprocessor
) ) {
511 $class = $this->mPreprocessorClass
;
512 $this->mPreprocessor
= new $class( $this );
514 return $this->mPreprocessor
;
518 * Replaces all occurrences of HTML-style comments and the given tags
519 * in the text with a random marker and returns teh next text. The output
520 * parameter $matches will be an associative array filled with data in
522 * 'UNIQ-xxxxx' => array(
525 * array( 'param' => 'x' ),
526 * '<element param="x">tag content</element>' ) )
528 * @param $elements list of element names. Comments are always extracted.
529 * @param $text Source text string.
530 * @param $uniq_prefix
535 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
540 $taglist = implode( '|', $elements );
541 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
543 while ( '' != $text ) {
544 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
546 if( count( $p ) < 5 ) {
549 if( count( $p ) > 5 ) {
563 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
564 $stripped .= $marker;
566 if ( $close === '/>' ) {
567 // Empty element tag, <tag />
572 if( $element == '!--' ) {
575 $end = "/(<\\/$element\\s*>)/i";
577 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
579 if( count( $q ) < 3 ) {
580 # No end tag -- let it run out to the end of the text.
589 $matches[$marker] = array( $element,
591 Sanitizer
::decodeTagAttributes( $attributes ),
592 "<$element$attributes$close$content$tail" );
598 * Get a list of strippable XML-like elements
600 function getStripList() {
602 $elements = $this->mStripList
;
604 $elements[] = 'html';
606 if( $this->mOptions
->getUseTeX() ) {
607 $elements[] = 'math';
613 * @deprecated use replaceVariables
615 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
620 * Restores pre, math, and other extensions removed by strip()
622 * always call unstripNoWiki() after this one
624 * @deprecated use $this->mStripState->unstrip()
626 function unstrip( $text, $state ) {
627 return $state->unstripGeneral( $text );
631 * Always call this after unstrip() to preserve the order
634 * @deprecated use $this->mStripState->unstrip()
636 function unstripNoWiki( $text, $state ) {
637 return $state->unstripNoWiki( $text );
641 * @deprecated use $this->mStripState->unstripBoth()
643 function unstripForHTML( $text ) {
644 return $this->mStripState
->unstripBoth( $text );
648 * Add an item to the strip state
649 * Returns the unique tag which must be inserted into the stripped text
650 * The tag will be replaced with the original text in unstrip()
654 function insertStripItem( $text ) {
655 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-{$this->mMarkerSuffix}";
656 $this->mMarkerIndex++
;
657 $this->mStripState
->general
->setPair( $rnd, $text );
662 * Interface with html tidy, used if $wgUseTidy = true.
663 * If tidy isn't able to correct the markup, the original will be
664 * returned in all its glory with a warning comment appended.
666 * Either the external tidy program or the in-process tidy extension
667 * will be used depending on availability. Override the default
668 * $wgTidyInternal setting to disable the internal if it's not working.
670 * @param string $text Hideous HTML input
671 * @return string Corrected HTML output
675 function tidy( $text ) {
676 global $wgTidyInternal;
677 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
678 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
679 '<head><title>test</title></head><body>'.$text.'</body></html>';
680 if( $wgTidyInternal ) {
681 $correctedtext = Parser
::internalTidy( $wrappedtext );
683 $correctedtext = Parser
::externalTidy( $wrappedtext );
685 if( is_null( $correctedtext ) ) {
686 wfDebug( "Tidy error detected!\n" );
687 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
689 return $correctedtext;
693 * Spawn an external HTML tidy process and get corrected markup back from it.
698 function externalTidy( $text ) {
699 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
700 $fname = 'Parser::externalTidy';
701 wfProfileIn( $fname );
706 $descriptorspec = array(
707 0 => array('pipe', 'r'),
708 1 => array('pipe', 'w'),
709 2 => array('file', wfGetNull(), 'a')
712 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
713 if (is_resource($process)) {
714 // Theoretically, this style of communication could cause a deadlock
715 // here. If the stdout buffer fills up, then writes to stdin could
716 // block. This doesn't appear to happen with tidy, because tidy only
717 // writes to stdout after it's finished reading from stdin. Search
718 // for tidyParseStdin and tidySaveStdout in console/tidy.c
719 fwrite($pipes[0], $text);
721 while (!feof($pipes[1])) {
722 $cleansource .= fgets($pipes[1], 1024);
725 proc_close($process);
728 wfProfileOut( $fname );
730 if( $cleansource == '' && $text != '') {
731 // Some kind of error happened, so we couldn't get the corrected text.
732 // Just give up; we'll use the source text and append a warning.
740 * Use the HTML tidy PECL extension to use the tidy library in-process,
741 * saving the overhead of spawning a new process.
743 * 'pear install tidy' should be able to compile the extension module.
748 function internalTidy( $text ) {
749 global $wgTidyConf, $IP, $wgDebugTidy;
750 $fname = 'Parser::internalTidy';
751 wfProfileIn( $fname );
754 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
755 $tidy->cleanRepair();
756 if( $tidy->getStatus() == 2 ) {
757 // 2 is magic number for fatal error
758 // http://www.php.net/manual/en/function.tidy-get-status.php
761 $cleansource = tidy_get_output( $tidy );
763 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
764 $cleansource .= "<!--\nTidy reports:\n" .
765 str_replace( '-->', '-->', $tidy->errorBuffer
) .
769 wfProfileOut( $fname );
774 * parse the wiki syntax used to render tables
778 function doTableStuff ( $text ) {
779 $fname = 'Parser::doTableStuff';
780 wfProfileIn( $fname );
782 $lines = explode ( "\n" , $text );
783 $td_history = array (); // Is currently a td tag open?
784 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
785 $tr_history = array (); // Is currently a tr tag open?
786 $tr_attributes = array (); // history of tr attributes
787 $has_opened_tr = array(); // Did this table open a <tr> element?
788 $indent_level = 0; // indent level of the table
789 foreach ( $lines as $key => $line )
791 $line = trim ( $line );
793 if( $line == '' ) { // empty line, go to next line
796 $first_character = $line{0};
799 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
800 // First check if we are starting a new table
801 $indent_level = strlen( $matches[1] );
803 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
804 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
806 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
807 array_push ( $td_history , false );
808 array_push ( $last_tag_history , '' );
809 array_push ( $tr_history , false );
810 array_push ( $tr_attributes , '' );
811 array_push ( $has_opened_tr , false );
812 } else if ( count ( $td_history ) == 0 ) {
813 // Don't do any of the following
815 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
816 // We are ending a table
817 $line = '</table>' . substr ( $line , 2 );
818 $last_tag = array_pop ( $last_tag_history );
820 if ( !array_pop ( $has_opened_tr ) ) {
821 $line = "<tr><td></td></tr>{$line}";
824 if ( array_pop ( $tr_history ) ) {
825 $line = "</tr>{$line}";
828 if ( array_pop ( $td_history ) ) {
829 $line = "</{$last_tag}>{$line}";
831 array_pop ( $tr_attributes );
832 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
833 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
834 // Now we have a table row
835 $line = preg_replace( '#^\|-+#', '', $line );
837 // Whats after the tag is now only attributes
838 $attributes = $this->mStripState
->unstripBoth( $line );
839 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
840 array_pop ( $tr_attributes );
841 array_push ( $tr_attributes , $attributes );
844 $last_tag = array_pop ( $last_tag_history );
845 array_pop ( $has_opened_tr );
846 array_push ( $has_opened_tr , true );
848 if ( array_pop ( $tr_history ) ) {
852 if ( array_pop ( $td_history ) ) {
853 $line = "</{$last_tag}>{$line}";
856 $lines[$key] = $line;
857 array_push ( $tr_history , false );
858 array_push ( $td_history , false );
859 array_push ( $last_tag_history , '' );
861 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
862 // This might be cell elements, td, th or captions
863 if ( substr ( $line , 0 , 2 ) == '|+' ) {
864 $first_character = '+';
865 $line = substr ( $line , 1 );
868 $line = substr ( $line , 1 );
870 if ( $first_character == '!' ) {
871 $line = str_replace ( '!!' , '||' , $line );
874 // Split up multiple cells on the same line.
875 // FIXME : This can result in improper nesting of tags processed
876 // by earlier parser steps, but should avoid splitting up eg
877 // attribute values containing literal "||".
878 $cells = StringUtils
::explodeMarkup( '||' , $line );
882 // Loop through each table cell
883 foreach ( $cells as $cell )
886 if ( $first_character != '+' )
888 $tr_after = array_pop ( $tr_attributes );
889 if ( !array_pop ( $tr_history ) ) {
890 $previous = "<tr{$tr_after}>\n";
892 array_push ( $tr_history , true );
893 array_push ( $tr_attributes , '' );
894 array_pop ( $has_opened_tr );
895 array_push ( $has_opened_tr , true );
898 $last_tag = array_pop ( $last_tag_history );
900 if ( array_pop ( $td_history ) ) {
901 $previous = "</{$last_tag}>{$previous}";
904 if ( $first_character == '|' ) {
906 } else if ( $first_character == '!' ) {
908 } else if ( $first_character == '+' ) {
909 $last_tag = 'caption';
914 array_push ( $last_tag_history , $last_tag );
916 // A cell could contain both parameters and data
917 $cell_data = explode ( '|' , $cell , 2 );
919 // Bug 553: Note that a '|' inside an invalid link should not
920 // be mistaken as delimiting cell parameters
921 if ( strpos( $cell_data[0], '[[' ) !== false ) {
922 $cell = "{$previous}<{$last_tag}>{$cell}";
923 } else if ( count ( $cell_data ) == 1 )
924 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
926 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
927 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
928 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
931 $lines[$key] .= $cell;
932 array_push ( $td_history , true );
937 // Closing open td, tr && table
938 while ( count ( $td_history ) > 0 )
940 if ( array_pop ( $td_history ) ) {
943 if ( array_pop ( $tr_history ) ) {
946 if ( !array_pop ( $has_opened_tr ) ) {
947 $lines[] = "<tr><td></td></tr>" ;
950 $lines[] = '</table>' ;
953 $output = implode ( "\n" , $lines ) ;
955 // special case: don't return empty table
956 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
960 wfProfileOut( $fname );
966 * Helper function for parse() that transforms wiki markup into
967 * HTML. Only called for $mOutputType == self::OT_HTML.
971 function internalParse( $text ) {
973 $fname = 'Parser::internalParse';
974 wfProfileIn( $fname );
976 # Hook to suspend the parser in this state
977 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
978 wfProfileOut( $fname );
982 $text = $this->replaceVariables( $text );
983 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
984 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
986 // Tables need to come after variable replacement for things to work
987 // properly; putting them before other transformations should keep
988 // exciting things like link expansions from showing up in surprising
990 $text = $this->doTableStuff( $text );
992 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
994 $text = $this->stripToc( $text );
995 $this->stripNoGallery( $text );
996 $text = $this->doHeadings( $text );
997 if($this->mOptions
->getUseDynamicDates()) {
998 $df =& DateFormatter
::getInstance();
999 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1001 $text = $this->doAllQuotes( $text );
1002 $text = $this->replaceInternalLinks( $text );
1003 $text = $this->replaceExternalLinks( $text );
1005 # replaceInternalLinks may sometimes leave behind
1006 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1007 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1009 $text = $this->doMagicLinks( $text );
1010 $text = $this->formatHeadings( $text, $isMain );
1012 wfProfileOut( $fname );
1017 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1018 * magic external links.
1022 function doMagicLinks( $text ) {
1023 wfProfileIn( __METHOD__
);
1024 $text = preg_replace_callback(
1026 <a.*?</a> | # Skip link text
1027 <.*?> | # Skip stuff inside HTML elements
1028 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1029 ISBN\s+(\b # ISBN, capture number as m[2]
1030 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1031 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1032 [0-9Xx] # check digit
1034 )!x', array( &$this, 'magicLinkCallback' ), $text );
1035 wfProfileOut( __METHOD__
);
1039 function magicLinkCallback( $m ) {
1040 if ( substr( $m[0], 0, 1 ) == '<' ) {
1043 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1045 $num = strtr( $isbn, array(
1050 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1051 $text = '<a href="' .
1052 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1053 "\" class=\"internal\">ISBN $isbn</a>";
1055 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1059 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1061 $urlmsg = 'pubmedurl';
1064 throw new MWException( __METHOD__
.': unrecognised match type "' .
1065 substr($m[0], 0, 20 ) . '"' );
1068 $url = wfMsg( $urlmsg, $id);
1069 $sk = $this->mOptions
->getSkin();
1070 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1071 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1077 * Parse headers and return html
1081 function doHeadings( $text ) {
1082 $fname = 'Parser::doHeadings';
1083 wfProfileIn( $fname );
1084 for ( $i = 6; $i >= 1; --$i ) {
1085 $h = str_repeat( '=', $i );
1086 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1087 "<h$i>\\1</h$i>", $text );
1089 wfProfileOut( $fname );
1094 * Replace single quotes with HTML markup
1096 * @return string the altered text
1098 function doAllQuotes( $text ) {
1099 $fname = 'Parser::doAllQuotes';
1100 wfProfileIn( $fname );
1102 $lines = explode( "\n", $text );
1103 foreach ( $lines as $line ) {
1104 $outtext .= $this->doQuotes ( $line ) . "\n";
1106 $outtext = substr($outtext, 0,-1);
1107 wfProfileOut( $fname );
1112 * Helper function for doAllQuotes()
1114 public function doQuotes( $text ) {
1115 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1116 if ( count( $arr ) == 1 )
1120 # First, do some preliminary work. This may shift some apostrophes from
1121 # being mark-up to being text. It also counts the number of occurrences
1122 # of bold and italics mark-ups.
1126 foreach ( $arr as $r )
1128 if ( ( $i %
2 ) == 1 )
1130 # If there are ever four apostrophes, assume the first is supposed to
1131 # be text, and the remaining three constitute mark-up for bold text.
1132 if ( strlen( $arr[$i] ) == 4 )
1137 # If there are more than 5 apostrophes in a row, assume they're all
1138 # text except for the last 5.
1139 else if ( strlen( $arr[$i] ) > 5 )
1141 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1144 # Count the number of occurrences of bold and italics mark-ups.
1145 # We are not counting sequences of five apostrophes.
1146 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1147 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1148 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1153 # If there is an odd number of both bold and italics, it is likely
1154 # that one of the bold ones was meant to be an apostrophe followed
1155 # by italics. Which one we cannot know for certain, but it is more
1156 # likely to be one that has a single-letter word before it.
1157 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1160 $firstsingleletterword = -1;
1161 $firstmultiletterword = -1;
1163 foreach ( $arr as $r )
1165 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1167 $x1 = substr ($arr[$i-1], -1);
1168 $x2 = substr ($arr[$i-1], -2, 1);
1170 if ($firstspace == -1) $firstspace = $i;
1171 } else if ($x2 == ' ') {
1172 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1174 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1180 # If there is a single-letter word, use it!
1181 if ($firstsingleletterword > -1)
1183 $arr [ $firstsingleletterword ] = "''";
1184 $arr [ $firstsingleletterword-1 ] .= "'";
1186 # If not, but there's a multi-letter word, use that one.
1187 else if ($firstmultiletterword > -1)
1189 $arr [ $firstmultiletterword ] = "''";
1190 $arr [ $firstmultiletterword-1 ] .= "'";
1192 # ... otherwise use the first one that has neither.
1193 # (notice that it is possible for all three to be -1 if, for example,
1194 # there is only one pentuple-apostrophe in the line)
1195 else if ($firstspace > -1)
1197 $arr [ $firstspace ] = "''";
1198 $arr [ $firstspace-1 ] .= "'";
1202 # Now let's actually convert our apostrophic mush to HTML!
1207 foreach ($arr as $r)
1211 if ($state == 'both')
1218 if (strlen ($r) == 2)
1221 { $output .= '</i>'; $state = ''; }
1222 else if ($state == 'bi')
1223 { $output .= '</i>'; $state = 'b'; }
1224 else if ($state == 'ib')
1225 { $output .= '</b></i><b>'; $state = 'b'; }
1226 else if ($state == 'both')
1227 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1228 else # $state can be 'b' or ''
1229 { $output .= '<i>'; $state .= 'i'; }
1231 else if (strlen ($r) == 3)
1234 { $output .= '</b>'; $state = ''; }
1235 else if ($state == 'bi')
1236 { $output .= '</i></b><i>'; $state = 'i'; }
1237 else if ($state == 'ib')
1238 { $output .= '</b>'; $state = 'i'; }
1239 else if ($state == 'both')
1240 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1241 else # $state can be 'i' or ''
1242 { $output .= '<b>'; $state .= 'b'; }
1244 else if (strlen ($r) == 5)
1247 { $output .= '</b><i>'; $state = 'i'; }
1248 else if ($state == 'i')
1249 { $output .= '</i><b>'; $state = 'b'; }
1250 else if ($state == 'bi')
1251 { $output .= '</i></b>'; $state = ''; }
1252 else if ($state == 'ib')
1253 { $output .= '</b></i>'; $state = ''; }
1254 else if ($state == 'both')
1255 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1256 else # ($state == '')
1257 { $buffer = ''; $state = 'both'; }
1262 # Now close all remaining tags. Notice that the order is important.
1263 if ($state == 'b' ||
$state == 'ib')
1265 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1269 # There might be lonely ''''', so make sure we have a buffer
1270 if ($state == 'both' && $buffer)
1271 $output .= '<b><i>'.$buffer.'</i></b>';
1277 * Replace external links
1279 * Note: this is all very hackish and the order of execution matters a lot.
1280 * Make sure to run maintenance/parserTests.php if you change this code.
1284 function replaceExternalLinks( $text ) {
1286 $fname = 'Parser::replaceExternalLinks';
1287 wfProfileIn( $fname );
1289 $sk = $this->mOptions
->getSkin();
1291 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1293 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1296 while ( $i<count( $bits ) ) {
1298 $protocol = $bits[$i++
];
1299 $text = $bits[$i++
];
1300 $trail = $bits[$i++
];
1302 # The characters '<' and '>' (which were escaped by
1303 # removeHTMLtags()) should not be included in
1304 # URLs, per RFC 2396.
1306 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1307 $text = substr($url, $m2[0][1]) . ' ' . $text;
1308 $url = substr($url, 0, $m2[0][1]);
1311 # If the link text is an image URL, replace it with an <img> tag
1312 # This happened by accident in the original parser, but some people used it extensively
1313 $img = $this->maybeMakeExternalImage( $text );
1314 if ( $img !== false ) {
1320 # Set linktype for CSS - if URL==text, link is essentially free
1321 $linktype = ($text == $url) ?
'free' : 'text';
1323 # No link text, e.g. [http://domain.tld/some.link]
1324 if ( $text == '' ) {
1325 # Autonumber if allowed. See bug #5918
1326 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1327 $text = '[' . ++
$this->mAutonumber
. ']';
1328 $linktype = 'autonumber';
1330 # Otherwise just use the URL
1331 $text = htmlspecialchars( $url );
1335 # Have link text, e.g. [http://domain.tld/some.link text]s
1337 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1340 $text = $wgContLang->markNoConversion($text);
1342 $url = Sanitizer
::cleanUrl( $url );
1344 # Process the trail (i.e. everything after this link up until start of the next link),
1345 # replacing any non-bracketed links
1346 $trail = $this->replaceFreeExternalLinks( $trail );
1348 # Use the encoded URL
1349 # This means that users can paste URLs directly into the text
1350 # Funny characters like ö aren't valid in URLs anyway
1351 # This was changed in August 2004
1352 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1354 # Register link in the output object.
1355 # Replace unnecessary URL escape codes with the referenced character
1356 # This prevents spammers from hiding links from the filters
1357 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1358 $this->mOutput
->addExternalLink( $pasteurized );
1361 wfProfileOut( $fname );
1366 * Replace anything that looks like a URL with a link
1369 function replaceFreeExternalLinks( $text ) {
1371 $fname = 'Parser::replaceFreeExternalLinks';
1372 wfProfileIn( $fname );
1374 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1375 $s = array_shift( $bits );
1378 $sk = $this->mOptions
->getSkin();
1380 while ( $i < count( $bits ) ){
1381 $protocol = $bits[$i++
];
1382 $remainder = $bits[$i++
];
1385 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1386 # Found some characters after the protocol that look promising
1387 $url = $protocol . $m[1];
1390 # special case: handle urls as url args:
1391 # http://www.example.com/foo?=http://www.example.com/bar
1392 if(strlen($trail) == 0 &&
1394 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1395 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1398 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1403 # The characters '<' and '>' (which were escaped by
1404 # removeHTMLtags()) should not be included in
1405 # URLs, per RFC 2396.
1407 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1408 $trail = substr($url, $m2[0][1]) . $trail;
1409 $url = substr($url, 0, $m2[0][1]);
1412 # Move trailing punctuation to $trail
1414 # If there is no left bracket, then consider right brackets fair game too
1415 if ( strpos( $url, '(' ) === false ) {
1419 $numSepChars = strspn( strrev( $url ), $sep );
1420 if ( $numSepChars ) {
1421 $trail = substr( $url, -$numSepChars ) . $trail;
1422 $url = substr( $url, 0, -$numSepChars );
1425 $url = Sanitizer
::cleanUrl( $url );
1427 # Is this an external image?
1428 $text = $this->maybeMakeExternalImage( $url );
1429 if ( $text === false ) {
1430 # Not an image, make a link
1431 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1432 # Register it in the output object...
1433 # Replace unnecessary URL escape codes with their equivalent characters
1434 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1435 $this->mOutput
->addExternalLink( $pasteurized );
1437 $s .= $text . $trail;
1439 $s .= $protocol . $remainder;
1442 wfProfileOut( $fname );
1447 * Replace unusual URL escape codes with their equivalent characters
1451 * @todo This can merge genuinely required bits in the path or query string,
1452 * breaking legit URLs. A proper fix would treat the various parts of
1453 * the URL differently; as a workaround, just use the output for
1454 * statistical records, not for actual linking/output.
1456 static function replaceUnusualEscapes( $url ) {
1457 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1458 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1462 * Callback function used in replaceUnusualEscapes().
1463 * Replaces unusual URL escape codes with their equivalent character
1467 private static function replaceUnusualEscapesCallback( $matches ) {
1468 $char = urldecode( $matches[0] );
1469 $ord = ord( $char );
1470 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1471 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1472 // No, shouldn't be escaped
1475 // Yes, leave it escaped
1481 * make an image if it's allowed, either through the global
1482 * option or through the exception
1485 function maybeMakeExternalImage( $url ) {
1486 $sk = $this->mOptions
->getSkin();
1487 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1488 $imagesexception = !empty($imagesfrom);
1490 if ( $this->mOptions
->getAllowExternalImages()
1491 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1492 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1494 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1501 * Process [[ ]] wikilinks
1505 function replaceInternalLinks( $s ) {
1507 static $fname = 'Parser::replaceInternalLinks' ;
1509 wfProfileIn( $fname );
1511 wfProfileIn( $fname.'-setup' );
1513 # the % is needed to support urlencoded titles as well
1514 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1516 $sk = $this->mOptions
->getSkin();
1518 #split the entire text string on occurences of [[
1519 $a = explode( '[[', ' ' . $s );
1520 #get the first element (all text up to first [[), and remove the space we added
1521 $s = array_shift( $a );
1522 $s = substr( $s, 1 );
1524 # Match a link having the form [[namespace:link|alternate]]trail
1526 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1527 # Match cases where there is no "]]", which might still be images
1528 static $e1_img = FALSE;
1529 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1531 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1533 if ( $useLinkPrefixExtension ) {
1534 # Match the end of a line for a word that's not followed by whitespace,
1535 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1536 $e2 = wfMsgForContent( 'linkprefix' );
1539 if( is_null( $this->mTitle
) ) {
1540 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1542 $nottalk = !$this->mTitle
->isTalkPage();
1544 if ( $useLinkPrefixExtension ) {
1546 if ( preg_match( $e2, $s, $m ) ) {
1547 $first_prefix = $m[2];
1549 $first_prefix = false;
1555 if($wgContLang->hasVariants()) {
1556 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1558 $selflink = array($this->mTitle
->getPrefixedText());
1560 $useSubpages = $this->areSubpagesAllowed();
1561 wfProfileOut( $fname.'-setup' );
1563 # Loop for each link
1564 for ($k = 0; isset( $a[$k] ); $k++
) {
1566 if ( $useLinkPrefixExtension ) {
1567 wfProfileIn( $fname.'-prefixhandling' );
1568 if ( preg_match( $e2, $s, $m ) ) {
1576 $prefix = $first_prefix;
1577 $first_prefix = false;
1579 wfProfileOut( $fname.'-prefixhandling' );
1582 $might_be_img = false;
1584 wfProfileIn( "$fname-e1" );
1585 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1587 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1588 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1589 # the real problem is with the $e1 regex
1592 # Still some problems for cases where the ] is meant to be outside punctuation,
1593 # and no image is in sight. See bug 2095.
1596 substr( $m[3], 0, 1 ) === ']' &&
1597 strpos($text, '[') !== false
1600 $text .= ']'; # so that replaceExternalLinks($text) works later
1601 $m[3] = substr( $m[3], 1 );
1603 # fix up urlencoded title texts
1604 if( strpos( $m[1], '%' ) !== false ) {
1605 # Should anchors '#' also be rejected?
1606 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1609 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1610 $might_be_img = true;
1612 if ( strpos( $m[1], '%' ) !== false ) {
1613 $m[1] = urldecode($m[1]);
1616 } else { # Invalid form; output directly
1617 $s .= $prefix . '[[' . $line ;
1618 wfProfileOut( "$fname-e1" );
1621 wfProfileOut( "$fname-e1" );
1622 wfProfileIn( "$fname-misc" );
1624 # Don't allow internal links to pages containing
1625 # PROTO: where PROTO is a valid URL protocol; these
1626 # should be external links.
1627 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1628 $s .= $prefix . '[[' . $line ;
1632 # Make subpage if necessary
1633 if( $useSubpages ) {
1634 $link = $this->maybeDoSubpageLink( $m[1], $text );
1639 $noforce = (substr($m[1], 0, 1) != ':');
1641 # Strip off leading ':'
1642 $link = substr($link, 1);
1645 wfProfileOut( "$fname-misc" );
1646 wfProfileIn( "$fname-title" );
1647 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1649 $s .= $prefix . '[[' . $line;
1650 wfProfileOut( "$fname-title" );
1654 $ns = $nt->getNamespace();
1655 $iw = $nt->getInterWiki();
1656 wfProfileOut( "$fname-title" );
1658 if ($might_be_img) { # if this is actually an invalid link
1659 wfProfileIn( "$fname-might_be_img" );
1660 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1662 while (isset ($a[$k+
1]) ) {
1663 #look at the next 'line' to see if we can close it there
1664 $spliced = array_splice( $a, $k +
1, 1 );
1665 $next_line = array_shift( $spliced );
1666 $m = explode( ']]', $next_line, 3 );
1667 if ( count( $m ) == 3 ) {
1668 # the first ]] closes the inner link, the second the image
1670 $text .= "[[{$m[0]}]]{$m[1]}";
1673 } elseif ( count( $m ) == 2 ) {
1674 #if there's exactly one ]] that's fine, we'll keep looking
1675 $text .= "[[{$m[0]}]]{$m[1]}";
1677 #if $next_line is invalid too, we need look no further
1678 $text .= '[[' . $next_line;
1683 # we couldn't find the end of this imageLink, so output it raw
1684 #but don't ignore what might be perfectly normal links in the text we've examined
1685 $text = $this->replaceInternalLinks($text);
1686 $s .= "{$prefix}[[$link|$text";
1687 # note: no $trail, because without an end, there *is* no trail
1688 wfProfileOut( "$fname-might_be_img" );
1691 } else { #it's not an image, so output it raw
1692 $s .= "{$prefix}[[$link|$text";
1693 # note: no $trail, because without an end, there *is* no trail
1694 wfProfileOut( "$fname-might_be_img" );
1697 wfProfileOut( "$fname-might_be_img" );
1700 $wasblank = ( '' == $text );
1701 if( $wasblank ) $text = $link;
1703 # Link not escaped by : , create the various objects
1707 wfProfileIn( "$fname-interwiki" );
1708 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1709 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1710 $s = rtrim($s . $prefix);
1711 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1712 wfProfileOut( "$fname-interwiki" );
1715 wfProfileOut( "$fname-interwiki" );
1717 if ( $ns == NS_IMAGE
) {
1718 wfProfileIn( "$fname-image" );
1719 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1720 # recursively parse links inside the image caption
1721 # actually, this will parse them in any other parameters, too,
1722 # but it might be hard to fix that, and it doesn't matter ATM
1723 $text = $this->replaceExternalLinks($text);
1724 $text = $this->replaceInternalLinks($text);
1726 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1727 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1728 $this->mOutput
->addImage( $nt->getDBkey() );
1730 wfProfileOut( "$fname-image" );
1733 # We still need to record the image's presence on the page
1734 $this->mOutput
->addImage( $nt->getDBkey() );
1736 wfProfileOut( "$fname-image" );
1740 if ( $ns == NS_CATEGORY
) {
1741 wfProfileIn( "$fname-category" );
1742 $s = rtrim($s . "\n"); # bug 87
1745 $sortkey = $this->getDefaultSort();
1749 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1750 $sortkey = str_replace( "\n", '', $sortkey );
1751 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1752 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1755 * Strip the whitespace Category links produce, see bug 87
1756 * @todo We might want to use trim($tmp, "\n") here.
1758 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1760 wfProfileOut( "$fname-category" );
1765 # Self-link checking
1766 if( $nt->getFragment() === '' ) {
1767 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1768 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1773 # Special and Media are pseudo-namespaces; no pages actually exist in them
1774 if( $ns == NS_MEDIA
) {
1775 $link = $sk->makeMediaLinkObj( $nt, $text );
1776 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1777 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1778 $this->mOutput
->addImage( $nt->getDBkey() );
1780 } elseif( $ns == NS_SPECIAL
) {
1781 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1782 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1784 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1787 } elseif( $ns == NS_IMAGE
) {
1788 $img = wfFindFile( $nt );
1790 // Force a blue link if the file exists; may be a remote
1791 // upload on the shared repository, and we want to see its
1792 // auto-generated page.
1793 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1794 $this->mOutput
->addLink( $nt );
1798 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1800 wfProfileOut( $fname );
1805 * Make a link placeholder. The text returned can be later resolved to a real link with
1806 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1807 * parsing of interwiki links, and secondly to allow all existence checks and
1808 * article length checks (for stub links) to be bundled into a single query.
1811 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1812 wfProfileIn( __METHOD__
);
1813 if ( ! is_object($nt) ) {
1815 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1817 # Separate the link trail from the rest of the link
1818 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1820 if ( $nt->isExternal() ) {
1821 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1822 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1823 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1825 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1826 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1827 $this->mLinkHolders
['queries'][] = $query;
1828 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1829 $this->mLinkHolders
['titles'][] = $nt;
1831 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1834 wfProfileOut( __METHOD__
);
1839 * Render a forced-blue link inline; protect against double expansion of
1840 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1841 * Since this little disaster has to split off the trail text to avoid
1842 * breaking URLs in the following text without breaking trails on the
1843 * wiki links, it's been made into a horrible function.
1846 * @param string $text
1847 * @param string $query
1848 * @param string $trail
1849 * @param string $prefix
1850 * @return string HTML-wikitext mix oh yuck
1852 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1853 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1854 $sk = $this->mOptions
->getSkin();
1855 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1856 return $this->armorLinks( $link ) . $trail;
1860 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1861 * going to go through further parsing steps before inline URL expansion.
1863 * In particular this is important when using action=render, which causes
1864 * full URLs to be included.
1866 * Oh man I hate our multi-layer parser!
1868 * @param string more-or-less HTML
1869 * @return string less-or-more HTML with NOPARSE bits
1871 function armorLinks( $text ) {
1872 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1873 "{$this->mUniqPrefix}NOPARSE$1", $text );
1877 * Return true if subpage links should be expanded on this page.
1880 function areSubpagesAllowed() {
1881 # Some namespaces don't allow subpages
1882 global $wgNamespacesWithSubpages;
1883 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1887 * Handle link to subpage if necessary
1888 * @param string $target the source of the link
1889 * @param string &$text the link text, modified as necessary
1890 * @return string the full name of the link
1893 function maybeDoSubpageLink($target, &$text) {
1896 # :Foobar -- override special treatment of prefix (images, language links)
1897 # /Foobar -- convert to CurrentPage/Foobar
1898 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1899 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1900 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1902 $fname = 'Parser::maybeDoSubpageLink';
1903 wfProfileIn( $fname );
1904 $ret = $target; # default return value is no change
1906 # Some namespaces don't allow subpages,
1907 # so only perform processing if subpages are allowed
1908 if( $this->areSubpagesAllowed() ) {
1909 $hash = strpos( $target, '#' );
1910 if( $hash !== false ) {
1911 $suffix = substr( $target, $hash );
1912 $target = substr( $target, 0, $hash );
1917 $target = trim( $target );
1918 # Look at the first character
1919 if( $target != '' && $target{0} == '/' ) {
1920 # / at end means we don't want the slash to be shown
1922 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1923 if( $trailingSlashes ) {
1924 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1926 $noslash = substr( $target, 1 );
1929 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1930 if( '' === $text ) {
1931 $text = $target . $suffix;
1932 } # this might be changed for ugliness reasons
1934 # check for .. subpage backlinks
1936 $nodotdot = $target;
1937 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1939 $nodotdot = substr( $nodotdot, 3 );
1941 if($dotdotcount > 0) {
1942 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1943 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1944 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1945 # / at the end means don't show full path
1946 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1947 $nodotdot = substr( $nodotdot, 0, -1 );
1948 if( '' === $text ) {
1949 $text = $nodotdot . $suffix;
1952 $nodotdot = trim( $nodotdot );
1953 if( $nodotdot != '' ) {
1954 $ret .= '/' . $nodotdot;
1962 wfProfileOut( $fname );
1967 * Used by doBlockLevels()
1970 /* private */ function closeParagraph() {
1972 if ( '' != $this->mLastSection
) {
1973 $result = '</' . $this->mLastSection
. ">\n";
1975 $this->mInPre
= false;
1976 $this->mLastSection
= '';
1979 # getCommon() returns the length of the longest common substring
1980 # of both arguments, starting at the beginning of both.
1982 /* private */ function getCommon( $st1, $st2 ) {
1983 $fl = strlen( $st1 );
1984 $shorter = strlen( $st2 );
1985 if ( $fl < $shorter ) { $shorter = $fl; }
1987 for ( $i = 0; $i < $shorter; ++
$i ) {
1988 if ( $st1{$i} != $st2{$i} ) { break; }
1992 # These next three functions open, continue, and close the list
1993 # element appropriate to the prefix character passed into them.
1995 /* private */ function openList( $char ) {
1996 $result = $this->closeParagraph();
1998 if ( '*' == $char ) { $result .= '<ul><li>'; }
1999 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2000 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2001 else if ( ';' == $char ) {
2002 $result .= '<dl><dt>';
2003 $this->mDTopen
= true;
2005 else { $result = '<!-- ERR 1 -->'; }
2010 /* private */ function nextItem( $char ) {
2011 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2012 else if ( ':' == $char ||
';' == $char ) {
2014 if ( $this->mDTopen
) { $close = '</dt>'; }
2015 if ( ';' == $char ) {
2016 $this->mDTopen
= true;
2017 return $close . '<dt>';
2019 $this->mDTopen
= false;
2020 return $close . '<dd>';
2023 return '<!-- ERR 2 -->';
2026 /* private */ function closeList( $char ) {
2027 if ( '*' == $char ) { $text = '</li></ul>'; }
2028 else if ( '#' == $char ) { $text = '</li></ol>'; }
2029 else if ( ':' == $char ) {
2030 if ( $this->mDTopen
) {
2031 $this->mDTopen
= false;
2032 $text = '</dt></dl>';
2034 $text = '</dd></dl>';
2037 else { return '<!-- ERR 3 -->'; }
2043 * Make lists from lines starting with ':', '*', '#', etc.
2046 * @return string the lists rendered as HTML
2048 function doBlockLevels( $text, $linestart ) {
2049 $fname = 'Parser::doBlockLevels';
2050 wfProfileIn( $fname );
2052 # Parsing through the text line by line. The main thing
2053 # happening here is handling of block-level elements p, pre,
2054 # and making lists from lines starting with * # : etc.
2056 $textLines = explode( "\n", $text );
2058 $lastPrefix = $output = '';
2059 $this->mDTopen
= $inBlockElem = false;
2061 $paragraphStack = false;
2063 if ( !$linestart ) {
2064 $output .= array_shift( $textLines );
2066 foreach ( $textLines as $oLine ) {
2067 $lastPrefixLength = strlen( $lastPrefix );
2068 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2069 $preOpenMatch = preg_match('/<pre/i', $oLine );
2070 if ( !$this->mInPre
) {
2071 # Multiple prefixes may abut each other for nested lists.
2072 $prefixLength = strspn( $oLine, '*#:;' );
2073 $pref = substr( $oLine, 0, $prefixLength );
2076 $pref2 = str_replace( ';', ':', $pref );
2077 $t = substr( $oLine, $prefixLength );
2078 $this->mInPre
= !empty($preOpenMatch);
2080 # Don't interpret any other prefixes in preformatted text
2082 $pref = $pref2 = '';
2087 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2088 # Same as the last item, so no need to deal with nesting or opening stuff
2089 $output .= $this->nextItem( substr( $pref, -1 ) );
2090 $paragraphStack = false;
2092 if ( substr( $pref, -1 ) == ';') {
2093 # The one nasty exception: definition lists work like this:
2094 # ; title : definition text
2095 # So we check for : in the remainder text to split up the
2096 # title and definition, without b0rking links.
2098 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2100 $output .= $term . $this->nextItem( ':' );
2103 } elseif( $prefixLength ||
$lastPrefixLength ) {
2104 # Either open or close a level...
2105 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2106 $paragraphStack = false;
2108 while( $commonPrefixLength < $lastPrefixLength ) {
2109 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2110 --$lastPrefixLength;
2112 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2113 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2115 while ( $prefixLength > $commonPrefixLength ) {
2116 $char = substr( $pref, $commonPrefixLength, 1 );
2117 $output .= $this->openList( $char );
2119 if ( ';' == $char ) {
2120 # FIXME: This is dupe of code above
2121 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2123 $output .= $term . $this->nextItem( ':' );
2126 ++
$commonPrefixLength;
2128 $lastPrefix = $pref2;
2130 if( 0 == $prefixLength ) {
2131 wfProfileIn( "$fname-paragraph" );
2132 # No prefix (not in list)--go to paragraph mode
2133 // XXX: use a stack for nestable elements like span, table and div
2134 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2135 $closematch = preg_match(
2136 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2137 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2138 if ( $openmatch or $closematch ) {
2139 $paragraphStack = false;
2140 #Â TODO bug 5718: paragraph closed
2141 $output .= $this->closeParagraph();
2142 if ( $preOpenMatch and !$preCloseMatch ) {
2143 $this->mInPre
= true;
2145 if ( $closematch ) {
2146 $inBlockElem = false;
2148 $inBlockElem = true;
2150 } else if ( !$inBlockElem && !$this->mInPre
) {
2151 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2153 if ($this->mLastSection
!= 'pre') {
2154 $paragraphStack = false;
2155 $output .= $this->closeParagraph().'<pre>';
2156 $this->mLastSection
= 'pre';
2158 $t = substr( $t, 1 );
2161 if ( '' == trim($t) ) {
2162 if ( $paragraphStack ) {
2163 $output .= $paragraphStack.'<br />';
2164 $paragraphStack = false;
2165 $this->mLastSection
= 'p';
2167 if ($this->mLastSection
!= 'p' ) {
2168 $output .= $this->closeParagraph();
2169 $this->mLastSection
= '';
2170 $paragraphStack = '<p>';
2172 $paragraphStack = '</p><p>';
2176 if ( $paragraphStack ) {
2177 $output .= $paragraphStack;
2178 $paragraphStack = false;
2179 $this->mLastSection
= 'p';
2180 } else if ($this->mLastSection
!= 'p') {
2181 $output .= $this->closeParagraph().'<p>';
2182 $this->mLastSection
= 'p';
2187 wfProfileOut( "$fname-paragraph" );
2189 // somewhere above we forget to get out of pre block (bug 785)
2190 if($preCloseMatch && $this->mInPre
) {
2191 $this->mInPre
= false;
2193 if ($paragraphStack === false) {
2197 while ( $prefixLength ) {
2198 $output .= $this->closeList( $pref2{$prefixLength-1} );
2201 if ( '' != $this->mLastSection
) {
2202 $output .= '</' . $this->mLastSection
. '>';
2203 $this->mLastSection
= '';
2206 wfProfileOut( $fname );
2211 * Split up a string on ':', ignoring any occurences inside tags
2212 * to prevent illegal overlapping.
2213 * @param string $str the string to split
2214 * @param string &$before set to everything before the ':'
2215 * @param string &$after set to everything after the ':'
2216 * return string the position of the ':', or false if none found
2218 function findColonNoLinks($str, &$before, &$after) {
2219 $fname = 'Parser::findColonNoLinks';
2220 wfProfileIn( $fname );
2222 $pos = strpos( $str, ':' );
2223 if( $pos === false ) {
2225 wfProfileOut( $fname );
2229 $lt = strpos( $str, '<' );
2230 if( $lt === false ||
$lt > $pos ) {
2231 // Easy; no tag nesting to worry about
2232 $before = substr( $str, 0, $pos );
2233 $after = substr( $str, $pos+
1 );
2234 wfProfileOut( $fname );
2238 // Ugly state machine to walk through avoiding tags.
2239 $state = self
::COLON_STATE_TEXT
;
2241 $len = strlen( $str );
2242 for( $i = 0; $i < $len; $i++
) {
2246 // (Using the number is a performance hack for common cases)
2247 case 0: // self::COLON_STATE_TEXT:
2250 // Could be either a <start> tag or an </end> tag
2251 $state = self
::COLON_STATE_TAGSTART
;
2256 $before = substr( $str, 0, $i );
2257 $after = substr( $str, $i +
1 );
2258 wfProfileOut( $fname );
2261 // Embedded in a tag; don't break it.
2264 // Skip ahead looking for something interesting
2265 $colon = strpos( $str, ':', $i );
2266 if( $colon === false ) {
2267 // Nothing else interesting
2268 wfProfileOut( $fname );
2271 $lt = strpos( $str, '<', $i );
2272 if( $stack === 0 ) {
2273 if( $lt === false ||
$colon < $lt ) {
2275 $before = substr( $str, 0, $colon );
2276 $after = substr( $str, $colon +
1 );
2277 wfProfileOut( $fname );
2281 if( $lt === false ) {
2282 // Nothing else interesting to find; abort!
2283 // We're nested, but there's no close tags left. Abort!
2286 // Skip ahead to next tag start
2288 $state = self
::COLON_STATE_TAGSTART
;
2291 case 1: // self::COLON_STATE_TAG:
2296 $state = self
::COLON_STATE_TEXT
;
2299 // Slash may be followed by >?
2300 $state = self
::COLON_STATE_TAGSLASH
;
2306 case 2: // self::COLON_STATE_TAGSTART:
2309 $state = self
::COLON_STATE_CLOSETAG
;
2312 $state = self
::COLON_STATE_COMMENT
;
2315 // Illegal early close? This shouldn't happen D:
2316 $state = self
::COLON_STATE_TEXT
;
2319 $state = self
::COLON_STATE_TAG
;
2322 case 3: // self::COLON_STATE_CLOSETAG:
2327 wfDebug( "Invalid input in $fname; too many close tags\n" );
2328 wfProfileOut( $fname );
2331 $state = self
::COLON_STATE_TEXT
;
2334 case self
::COLON_STATE_TAGSLASH
:
2336 // Yes, a self-closed tag <blah/>
2337 $state = self
::COLON_STATE_TEXT
;
2339 // Probably we're jumping the gun, and this is an attribute
2340 $state = self
::COLON_STATE_TAG
;
2343 case 5: // self::COLON_STATE_COMMENT:
2345 $state = self
::COLON_STATE_COMMENTDASH
;
2348 case self
::COLON_STATE_COMMENTDASH
:
2350 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2352 $state = self
::COLON_STATE_COMMENT
;
2355 case self
::COLON_STATE_COMMENTDASHDASH
:
2357 $state = self
::COLON_STATE_TEXT
;
2359 $state = self
::COLON_STATE_COMMENT
;
2363 throw new MWException( "State machine error in $fname" );
2367 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2370 wfProfileOut( $fname );
2375 * Return value of a magic variable (like PAGENAME)
2379 function getVariableValue( $index ) {
2380 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2383 * Some of these require message or data lookups and can be
2384 * expensive to check many times.
2386 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2387 if ( isset( $this->mVarCache
[$index] ) ) {
2388 return $this->mVarCache
[$index];
2392 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2393 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2396 global $wgLocaltimezone;
2397 if ( isset( $wgLocaltimezone ) ) {
2398 $oldtz = getenv( 'TZ' );
2399 putenv( 'TZ='.$wgLocaltimezone );
2402 wfSuppressWarnings(); // E_STRICT system time bitching
2403 $localTimestamp = date( 'YmdHis', $ts );
2404 $localMonth = date( 'm', $ts );
2405 $localMonthName = date( 'n', $ts );
2406 $localDay = date( 'j', $ts );
2407 $localDay2 = date( 'd', $ts );
2408 $localDayOfWeek = date( 'w', $ts );
2409 $localWeek = date( 'W', $ts );
2410 $localYear = date( 'Y', $ts );
2411 $localHour = date( 'H', $ts );
2412 if ( isset( $wgLocaltimezone ) ) {
2413 putenv( 'TZ='.$oldtz );
2415 wfRestoreWarnings();
2418 case 'currentmonth':
2419 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2420 case 'currentmonthname':
2421 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2422 case 'currentmonthnamegen':
2423 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2424 case 'currentmonthabbrev':
2425 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2427 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2429 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2431 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2432 case 'localmonthname':
2433 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2434 case 'localmonthnamegen':
2435 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2436 case 'localmonthabbrev':
2437 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2439 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2441 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2443 return wfEscapeWikiText( $this->mTitle
->getText() );
2445 return $this->mTitle
->getPartialURL();
2446 case 'fullpagename':
2447 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2448 case 'fullpagenamee':
2449 return $this->mTitle
->getPrefixedURL();
2451 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2452 case 'subpagenamee':
2453 return $this->mTitle
->getSubpageUrlForm();
2454 case 'basepagename':
2455 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2456 case 'basepagenamee':
2457 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2458 case 'talkpagename':
2459 if( $this->mTitle
->canTalk() ) {
2460 $talkPage = $this->mTitle
->getTalkPage();
2461 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2465 case 'talkpagenamee':
2466 if( $this->mTitle
->canTalk() ) {
2467 $talkPage = $this->mTitle
->getTalkPage();
2468 return $talkPage->getPrefixedUrl();
2472 case 'subjectpagename':
2473 $subjPage = $this->mTitle
->getSubjectPage();
2474 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2475 case 'subjectpagenamee':
2476 $subjPage = $this->mTitle
->getSubjectPage();
2477 return $subjPage->getPrefixedUrl();
2479 // Let the edit saving system know we should parse the page
2480 // *after* a revision ID has been assigned.
2481 $this->mOutput
->setFlag( 'vary-revision' );
2482 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2483 return $this->mRevisionId
;
2485 // Let the edit saving system know we should parse the page
2486 // *after* a revision ID has been assigned. This is for null edits.
2487 $this->mOutput
->setFlag( 'vary-revision' );
2488 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2489 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2490 case 'revisionday2':
2491 // Let the edit saving system know we should parse the page
2492 // *after* a revision ID has been assigned. This is for null edits.
2493 $this->mOutput
->setFlag( 'vary-revision' );
2494 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2495 return substr( $this->getRevisionTimestamp(), 6, 2 );
2496 case 'revisionmonth':
2497 // Let the edit saving system know we should parse the page
2498 // *after* a revision ID has been assigned. This is for null edits.
2499 $this->mOutput
->setFlag( 'vary-revision' );
2500 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2501 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2502 case 'revisionyear':
2503 // Let the edit saving system know we should parse the page
2504 // *after* a revision ID has been assigned. This is for null edits.
2505 $this->mOutput
->setFlag( 'vary-revision' );
2506 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2507 return substr( $this->getRevisionTimestamp(), 0, 4 );
2508 case 'revisiontimestamp':
2509 // Let the edit saving system know we should parse the page
2510 // *after* a revision ID has been assigned. This is for null edits.
2511 $this->mOutput
->setFlag( 'vary-revision' );
2512 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2513 return $this->getRevisionTimestamp();
2515 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2517 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2519 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2521 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2522 case 'subjectspace':
2523 return $this->mTitle
->getSubjectNsText();
2524 case 'subjectspacee':
2525 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2526 case 'currentdayname':
2527 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2531 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2535 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2536 // int to remove the padding
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2540 case 'localdayname':
2541 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2545 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2547 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2549 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2550 // int to remove the padding
2551 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2553 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2554 case 'numberofarticles':
2555 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2556 case 'numberoffiles':
2557 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2558 case 'numberofusers':
2559 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2560 case 'numberofpages':
2561 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2562 case 'numberofadmins':
2563 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2564 case 'numberofedits':
2565 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2566 case 'currenttimestamp':
2567 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2568 case 'localtimestamp':
2569 return $this->mVarCache
[$index] = $localTimestamp;
2570 case 'currentversion':
2571 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2577 return $wgServerName;
2579 return $wgScriptPath;
2580 case 'directionmark':
2581 return $wgContLang->getDirMark();
2582 case 'contentlanguage':
2583 global $wgContLanguageCode;
2584 return $wgContLanguageCode;
2587 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2595 * initialise the magic variables (like CURRENTMONTHNAME)
2599 function initialiseVariables() {
2600 $fname = 'Parser::initialiseVariables';
2601 wfProfileIn( $fname );
2602 $variableIDs = MagicWord
::getVariableIDs();
2604 $this->mVariables
= new MagicWordArray( $variableIDs );
2605 wfProfileOut( $fname );
2609 * Preprocess some wikitext and return the document tree.
2610 * This is the ghost of replace_variables().
2612 * @param string $text The text to parse
2613 * @param integer flags Bitwise combination of:
2614 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2615 * included. Default is to assume a direct page view.
2617 * The generated DOM tree must depend only on the input text and the flags.
2618 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2620 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2621 * change in the DOM tree for a given text, must be passed through the section identifier
2622 * in the section edit link and thus back to extractSections().
2624 * The output of this function is currently only cached in process memory, but a persistent
2625 * cache may be implemented at a later date which takes further advantage of these strict
2626 * dependency requirements.
2630 function preprocessToDom ( $text, $flags = 0 ) {
2631 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2636 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2638 public static function splitWhitespace( $s ) {
2639 $ltrimmed = ltrim( $s );
2640 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2641 $trimmed = rtrim( $ltrimmed );
2642 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2644 $w2 = substr( $ltrimmed, -$diff );
2648 return array( $w1, $trimmed, $w2 );
2652 * Replace magic variables, templates, and template arguments
2653 * with the appropriate text. Templates are substituted recursively,
2654 * taking care to avoid infinite loops.
2656 * Note that the substitution depends on value of $mOutputType:
2657 * self::OT_WIKI: only {{subst:}} templates
2658 * self::OT_PREPROCESS: templates but not extension tags
2659 * self::OT_HTML: all templates and extension tags
2661 * @param string $tex The text to transform
2662 * @param PPFrame $frame Object describing the arguments passed to the template
2663 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2666 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2667 # Prevent too big inclusions
2668 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2672 $fname = __METHOD__
;
2673 wfProfileIn( $fname );
2675 if ( $frame === false ) {
2676 $frame = $this->getPreprocessor()->newFrame();
2677 } elseif ( !( $frame instanceof PPFrame
) ) {
2678 throw new MWException( __METHOD__
. ' called using the old argument format' );
2681 $dom = $this->preprocessToDom( $text );
2682 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2683 $text = $frame->expand( $dom, $flags );
2685 wfProfileOut( $fname );
2689 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2690 static function createAssocArgs( $args ) {
2691 $assocArgs = array();
2693 foreach( $args as $arg ) {
2694 $eqpos = strpos( $arg, '=' );
2695 if ( $eqpos === false ) {
2696 $assocArgs[$index++
] = $arg;
2698 $name = trim( substr( $arg, 0, $eqpos ) );
2699 $value = trim( substr( $arg, $eqpos+
1 ) );
2700 if ( $value === false ) {
2703 if ( $name !== false ) {
2704 $assocArgs[$name] = $value;
2713 * Return the text of a template, after recursively
2714 * replacing any variables or templates within the template.
2716 * @param array $piece The parts of the template
2717 * $piece['title']: the title, i.e. the part before the |
2718 * $piece['parts']: the parameter array
2719 * $piece['lineStart']: whether the brace was at the start of a line
2720 * @param PPFrame The current frame, contains template arguments
2721 * @return string the text of the template
2724 function braceSubstitution( $piece, $frame ) {
2725 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2726 $fname = __METHOD__
;
2727 wfProfileIn( $fname );
2728 wfProfileIn( __METHOD__
.'-setup' );
2731 $found = false; # $text has been filled
2732 $nowiki = false; # wiki markup in $text should be escaped
2733 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2734 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2735 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2736 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2738 # Title object, where $text came from
2741 # $part1 is the bit before the first |, and must contain only title characters.
2742 # Various prefixes will be stripped from it later.
2743 $titleWithSpaces = $frame->expand( $piece['title'] );
2744 $part1 = trim( $titleWithSpaces );
2747 # Original title text preserved for various purposes
2748 $originalTitle = $part1;
2750 # $args is a list of argument nodes, starting from index 0, not including $part1
2751 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2752 wfProfileOut( __METHOD__
.'-setup' );
2755 wfProfileIn( __METHOD__
.'-modifiers' );
2757 $mwSubst =& MagicWord
::get( 'subst' );
2758 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2759 # One of two possibilities is true:
2760 # 1) Found SUBST but not in the PST phase
2761 # 2) Didn't find SUBST and in the PST phase
2762 # In either case, return without further processing
2763 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2770 if ( !$found && $args->getLength() == 0 ) {
2771 $id = $this->mVariables
->matchStartToEnd( $part1 );
2772 if ( $id !== false ) {
2773 $text = $this->getVariableValue( $id );
2774 if (MagicWord
::getCacheTTL($id)>-1)
2775 $this->mOutput
->mContainsOldMagic
= true;
2780 # MSG, MSGNW and RAW
2783 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2784 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2787 # Remove obsolete MSG:
2788 $mwMsg =& MagicWord
::get( 'msg' );
2789 $mwMsg->matchStartAndRemove( $part1 );
2793 $mwRaw =& MagicWord
::get( 'raw' );
2794 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2795 $forceRawInterwiki = true;
2798 wfProfileOut( __METHOD__
.'-modifiers' );
2802 wfProfileIn( __METHOD__
. '-pfunc' );
2804 $colonPos = strpos( $part1, ':' );
2805 if ( $colonPos !== false ) {
2806 # Case sensitive functions
2807 $function = substr( $part1, 0, $colonPos );
2808 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2809 $function = $this->mFunctionSynonyms
[1][$function];
2811 # Case insensitive functions
2812 $function = strtolower( $function );
2813 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2814 $function = $this->mFunctionSynonyms
[0][$function];
2820 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2821 $initialArgs = array( &$this );
2822 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2823 if ( $flags & SFH_OBJECT_ARGS
) {
2824 # Add a frame parameter, and pass the arguments as an array
2825 $allArgs = $initialArgs;
2826 $allArgs[] = $frame;
2827 for ( $i = 0; $i < $args->getLength(); $i++
) {
2828 $funcArgs[] = $args->item( $i );
2830 $allArgs[] = $funcArgs;
2832 # Convert arguments to plain text
2833 for ( $i = 0; $i < $args->getLength(); $i++
) {
2834 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2836 $allArgs = array_merge( $initialArgs, $funcArgs );
2839 # Workaround for PHP bug 35229 and similar
2840 if ( !is_callable( $callback ) ) {
2841 throw new MWException( "Tag hook for $name is not callable\n" );
2843 $result = call_user_func_array( $callback, $allArgs );
2846 if ( is_array( $result ) ) {
2847 if ( isset( $result[0] ) ) {
2849 unset( $result[0] );
2852 // Extract flags into the local scope
2853 // This allows callers to set flags such as nowiki, found, etc.
2860 wfProfileOut( __METHOD__
. '-pfunc' );
2863 # Finish mangling title and then check for loops.
2864 # Set $title to a Title object and $titleText to the PDBK
2867 # Split the title into page and subpage
2869 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2870 if ($subpage !== '') {
2871 $ns = $this->mTitle
->getNamespace();
2873 $title = Title
::newFromText( $part1, $ns );
2875 $titleText = $title->getPrefixedText();
2876 # Check for language variants if the template is not found
2877 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2878 $wgContLang->findVariantLink($part1, $title);
2880 # Do infinite loop check
2881 if ( !$frame->loopCheck( $title ) ) {
2883 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2884 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2886 # Do recursion depth check
2887 $limit = $this->mOptions
->getMaxTemplateDepth();
2888 if ( $frame->depth
>= $limit ) {
2890 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2895 # Load from database
2896 if ( !$found && $title ) {
2897 wfProfileIn( __METHOD__
. '-loadtpl' );
2898 if ( !$title->isExternal() ) {
2899 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2900 $text = SpecialPage
::capturePath( $title );
2901 if ( is_string( $text ) ) {
2904 $this->disableCache();
2906 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2907 $found = false; //access denied
2908 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2910 list( $text, $title ) = $this->getTemplateDom( $title );
2911 if ( $text !== false ) {
2917 # If the title is valid but undisplayable, make a link to it
2918 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2919 $text = "[[:$titleText]]";
2922 } elseif ( $title->isTrans() ) {
2923 // Interwiki transclusion
2924 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2925 $text = $this->interwikiTransclude( $title, 'render' );
2928 $text = $this->interwikiTransclude( $title, 'raw' );
2929 // Preprocess it like a template
2930 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2935 wfProfileOut( __METHOD__
. '-loadtpl' );
2938 # If we haven't found text to substitute by now, we're done
2939 # Recover the source wikitext and return it
2941 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2942 wfProfileOut( $fname );
2943 return array( 'object' => $text );
2946 # Expand DOM-style return values in a child frame
2947 if ( $isChildObj ) {
2948 # Clean up argument array
2949 $newFrame = $frame->newChild( $args, $title );
2952 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2953 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2954 # Expansion is eligible for the empty-frame cache
2955 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2956 $text = $this->mTplExpandCache
[$titleText];
2958 $text = $newFrame->expand( $text );
2959 $this->mTplExpandCache
[$titleText] = $text;
2962 # Uncached expansion
2963 $text = $newFrame->expand( $text );
2966 if ( $isLocalObj && $nowiki ) {
2967 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2968 $isLocalObj = false;
2971 # Replace raw HTML by a placeholder
2972 # Add a blank line preceding, to prevent it from mucking up
2973 # immediately preceding headings
2975 $text = "\n\n" . $this->insertStripItem( $text );
2977 # Escape nowiki-style return values
2978 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2979 $text = wfEscapeWikiText( $text );
2981 # Bug 529: if the template begins with a table or block-level
2982 # element, it should be treated as beginning a new line.
2983 # This behaviour is somewhat controversial.
2984 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2985 $text = "\n" . $text;
2988 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2989 # Error, oversize inclusion
2990 $text = "[[$originalTitle]]" .
2991 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2994 if ( $isLocalObj ) {
2995 $ret = array( 'object' => $text );
2997 $ret = array( 'text' => $text );
3000 wfProfileOut( $fname );
3005 * Get the semi-parsed DOM representation of a template with a given title,
3006 * and its redirect destination title. Cached.
3008 function getTemplateDom( $title ) {
3009 $cacheTitle = $title;
3010 $titleText = $title->getPrefixedDBkey();
3012 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3013 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3014 $title = Title
::makeTitle( $ns, $dbk );
3015 $titleText = $title->getPrefixedDBkey();
3017 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3018 return array( $this->mTplDomCache
[$titleText], $title );
3021 // Cache miss, go to the database
3022 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3024 if ( $text === false ) {
3025 $this->mTplDomCache
[$titleText] = false;
3026 return array( false, $title );
3029 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3030 $this->mTplDomCache
[ $titleText ] = $dom;
3032 if (! $title->equals($cacheTitle)) {
3033 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3034 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3037 return array( $dom, $title );
3041 * Fetch the unparsed text of a template and register a reference to it.
3043 function fetchTemplateAndTitle( $title ) {
3044 $templateCb = $this->mOptions
->getTemplateCallback();
3045 $stuff = call_user_func( $templateCb, $title );
3046 $text = $stuff['text'];
3047 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3048 if ( isset( $stuff['deps'] ) ) {
3049 foreach ( $stuff['deps'] as $dep ) {
3050 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3053 return array($text,$finalTitle);
3056 function fetchTemplate( $title ) {
3057 $rv = $this->fetchTemplateAndTitle($title);
3062 * Static function to get a template
3063 * Can be overridden via ParserOptions::setTemplateCallback().
3065 static function statelessFetchTemplate( $title ) {
3066 $text = $skip = false;
3067 $finalTitle = $title;
3070 // Loop to fetch the article, with up to 1 redirect
3071 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3072 # Give extensions a chance to select the revision instead
3073 $id = false; // Assume current
3074 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3080 'page_id' => $title->getArticleID(),
3084 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3085 $rev_id = $rev ?
$rev->getId() : 0;
3089 'page_id' => $title->getArticleID(),
3090 'rev_id' => $rev_id );
3093 $text = $rev->getText();
3094 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3096 $message = $wgLang->lcfirst( $title->getText() );
3097 $text = wfMsgForContentNoTrans( $message );
3098 if( wfEmptyMsg( $message, $text ) ) {
3105 if ( $text === false ) {
3109 $finalTitle = $title;
3110 $title = Title
::newFromRedirect( $text );
3114 'finalTitle' => $finalTitle,
3119 * Transclude an interwiki link.
3121 function interwikiTransclude( $title, $action ) {
3122 global $wgEnableScaryTranscluding;
3124 if (!$wgEnableScaryTranscluding)
3125 return wfMsg('scarytranscludedisabled');
3127 $url = $title->getFullUrl( "action=$action" );
3129 if (strlen($url) > 255)
3130 return wfMsg('scarytranscludetoolong');
3131 return $this->fetchScaryTemplateMaybeFromCache($url);
3134 function fetchScaryTemplateMaybeFromCache($url) {
3135 global $wgTranscludeCacheExpiry;
3136 $dbr = wfGetDB(DB_SLAVE
);
3137 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3138 array('tc_url' => $url));
3140 $time = $obj->tc_time
;
3141 $text = $obj->tc_contents
;
3142 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3147 $text = Http
::get($url);
3149 return wfMsg('scarytranscludefailed', $url);
3151 $dbw = wfGetDB(DB_MASTER
);
3152 $dbw->replace('transcache', array('tc_url'), array(
3154 'tc_time' => time(),
3155 'tc_contents' => $text));
3161 * Triple brace replacement -- used for template arguments
3164 function argSubstitution( $piece, $frame ) {
3165 wfProfileIn( __METHOD__
);
3168 $parts = $piece['parts'];
3169 $nameWithSpaces = $frame->expand( $piece['title'] );
3170 $argName = trim( $nameWithSpaces );
3172 $text = $frame->getArgument( $argName );
3173 if ( $text === false && $parts->getLength() > 0
3177 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3180 # No match in frame, use the supplied default
3181 $object = $parts->item( 0 )->getChildren();
3183 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3184 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3187 if ( $text === false && $object === false ) {
3189 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3191 if ( $error !== false ) {
3194 if ( $object !== false ) {
3195 $ret = array( 'object' => $object );
3197 $ret = array( 'text' => $text );
3200 wfProfileOut( __METHOD__
);
3205 * Return the text to be used for a given extension tag.
3206 * This is the ghost of strip().
3208 * @param array $params Associative array of parameters:
3209 * name PPNode for the tag name
3210 * attr PPNode for unparsed text where tag attributes are thought to be
3211 * attributes Optional associative array of parsed attributes
3212 * inner Contents of extension element
3213 * noClose Original text did not have a close tag
3214 * @param PPFrame $frame
3216 function extensionSubstitution( $params, $frame ) {
3217 global $wgRawHtml, $wgContLang;
3219 $name = $frame->expand( $params['name'] );
3220 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3221 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3223 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . $this->mMarkerSuffix
;
3225 if ( $this->ot
['html'] ) {
3226 $name = strtolower( $name );
3228 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3229 if ( isset( $params['attributes'] ) ) {
3230 $attributes = $attributes +
$params['attributes'];
3238 throw new MWException( '<html> extension tag encountered unexpectedly' );
3241 $output = Xml
::escapeTagsOnly( $content );
3244 $output = $wgContLang->armourMath(
3245 MathRenderer
::renderMath( $content, $attributes ) );
3248 $output = $this->renderImageGallery( $content, $attributes );
3251 if( isset( $this->mTagHooks
[$name] ) ) {
3252 # Workaround for PHP bug 35229 and similar
3253 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3254 throw new MWException( "Tag hook for $name is not callable\n" );
3256 $output = call_user_func_array( $this->mTagHooks
[$name],
3257 array( $content, $attributes, $this ) );
3259 throw new MWException( "Invalid call hook $name" );
3263 if ( is_null( $attrText ) ) {
3266 if ( isset( $params['attributes'] ) ) {
3267 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3268 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3269 htmlspecialchars( $attrValue ) . '"';
3272 if ( $content === null ) {
3273 $output = "<$name$attrText/>";
3275 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3276 $output = "<$name$attrText>$content$close";
3280 if ( $name == 'html' ||
$name == 'nowiki' ) {
3281 $this->mStripState
->nowiki
->setPair( $marker, $output );
3283 $this->mStripState
->general
->setPair( $marker, $output );
3289 * Increment an include size counter
3291 * @param string $type The type of expansion
3292 * @param integer $size The size of the text
3293 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3295 function incrementIncludeSize( $type, $size ) {
3296 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3299 $this->mIncludeSizes
[$type] +
= $size;
3305 * Detect __NOGALLERY__ magic word and set a placeholder
3307 function stripNoGallery( &$text ) {
3308 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3310 $mw = MagicWord
::get( 'nogallery' );
3311 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3315 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3316 * placeholder that will then be replaced by the real TOC in
3317 * ->formatHeadings, this works because at this points real
3318 * comments will have already been discarded by the sanitizer.
3320 * Any additional __TOC__ magic words left over will be discarded
3321 * as there can only be one TOC on the page.
3323 function stripToc( $text ) {
3324 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3326 $mw = MagicWord
::get( 'notoc' );
3327 if( $mw->matchAndRemove( $text ) ) {
3328 $this->mShowToc
= false;
3331 $mw = MagicWord
::get( 'toc' );
3332 if( $mw->match( $text ) ) {
3333 $this->mShowToc
= true;
3334 $this->mForceTocPosition
= true;
3336 // Set a placeholder. At the end we'll fill it in with the TOC.
3337 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3339 // Only keep the first one.
3340 $text = $mw->replace( '', $text );
3346 * This function accomplishes several tasks:
3347 * 1) Auto-number headings if that option is enabled
3348 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3349 * 3) Add a Table of contents on the top for users who have enabled the option
3350 * 4) Auto-anchor headings
3352 * It loops through all headlines, collects the necessary data, then splits up the
3353 * string and re-inserts the newly formatted headlines.
3355 * @param string $text
3356 * @param boolean $isMain
3359 function formatHeadings( $text, $isMain=true ) {
3360 global $wgMaxTocLevel, $wgContLang;
3362 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3363 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3366 $showEditLink = $this->mOptions
->getEditSection();
3369 # Inhibit editsection links if requested in the page
3370 $esw =& MagicWord
::get( 'noeditsection' );
3371 if( $esw->matchAndRemove( $text ) ) {
3375 # Get all headlines for numbering them and adding funky stuff like [edit]
3376 # links - this is for later, but we need the number of headlines right now
3378 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3380 # if there are fewer than 4 headlines in the article, do not show TOC
3381 # unless it's been explicitly enabled.
3382 $enoughToc = $this->mShowToc
&&
3383 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3385 # Allow user to stipulate that a page should have a "new section"
3386 # link added via __NEWSECTIONLINK__
3387 $mw =& MagicWord
::get( 'newsectionlink' );
3388 if( $mw->matchAndRemove( $text ) )
3389 $this->mOutput
->setNewSection( true );
3391 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3392 # override above conditions and always show TOC above first header
3393 $mw =& MagicWord
::get( 'forcetoc' );
3394 if ($mw->matchAndRemove( $text ) ) {
3395 $this->mShowToc
= true;
3399 # We need this to perform operations on the HTML
3400 $sk = $this->mOptions
->getSkin();
3406 # Ugh .. the TOC should have neat indentation levels which can be
3407 # passed to the skin functions. These are determined here
3411 $sublevelCount = array();
3412 $levelCount = array();
3418 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3419 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3422 foreach( $matches[3] as $headline ) {
3423 $isTemplate = false;
3425 $sectionIndex = false;
3427 $markerMatches = array();
3428 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3429 $serial = $markerMatches[1];
3430 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3431 $isTemplate = ($titleText != $baseTitleText);
3432 $headline = preg_replace("/^$markerRegex/", "", $headline);
3436 $prevlevel = $level;
3437 $prevtoclevel = $toclevel;
3439 $level = $matches[1][$headlineCount];
3441 if( $doNumberHeadings ||
$enoughToc ) {
3443 if ( $level > $prevlevel ) {
3444 # Increase TOC level
3446 $sublevelCount[$toclevel] = 0;
3447 if( $toclevel<$wgMaxTocLevel ) {
3448 $prevtoclevel = $toclevel;
3449 $toc .= $sk->tocIndent();
3453 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3454 # Decrease TOC level, find level to jump to
3456 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3457 # Can only go down to level 1
3460 for ($i = $toclevel; $i > 0; $i--) {
3461 if ( $levelCount[$i] == $level ) {
3462 # Found last matching level
3466 elseif ( $levelCount[$i] < $level ) {
3467 # Found first matching level below current level
3473 if( $toclevel<$wgMaxTocLevel ) {
3474 if($prevtoclevel < $wgMaxTocLevel) {
3475 # Unindent only if the previous toc level was shown :p
3476 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3478 $toc .= $sk->tocLineEnd();
3483 # No change in level, end TOC line
3484 if( $toclevel<$wgMaxTocLevel ) {
3485 $toc .= $sk->tocLineEnd();
3489 $levelCount[$toclevel] = $level;
3491 # count number of headlines for each level
3492 @$sublevelCount[$toclevel]++
;
3494 for( $i = 1; $i <= $toclevel; $i++
) {
3495 if( !empty( $sublevelCount[$i] ) ) {
3499 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3505 # The safe header is a version of the header text safe to use for links
3506 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3507 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3509 # Remove link placeholders by the link text.
3510 # <!--LINK number-->
3512 # link text with suffix
3513 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3514 "\$this->mLinkHolders['texts'][\$1]",
3516 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3517 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3520 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3521 $tocline = preg_replace(
3522 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3526 $tocline = trim( $tocline );
3528 # For the anchor, strip out HTML-y stuff period
3529 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3530 $safeHeadline = trim( $safeHeadline );
3532 # Save headline for section edit hint before it's escaped
3533 $headlineHint = $safeHeadline;
3534 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3535 $refers[$headlineCount] = $safeHeadline;
3537 # count how many in assoc. array so we can track dupes in anchors
3538 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3539 $refcount[$headlineCount] = $refers[$safeHeadline];
3541 # Don't number the heading if it is the only one (looks silly)
3542 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3543 # the two are different if the line contains a link
3544 $headline=$numbering . ' ' . $headline;
3547 # Create the anchor for linking from the TOC to the section
3548 $anchor = $safeHeadline;
3549 if($refcount[$headlineCount] > 1 ) {
3550 $anchor .= '_' . $refcount[$headlineCount];
3552 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3553 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3554 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3556 # give headline the correct <h#> tag
3557 if( $showEditLink && $sectionIndex !== false ) {
3559 # Put a T flag in the section identifier, to indicate to extractSections()
3560 # that sections inside <includeonly> should be counted.
3561 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3563 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3568 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3573 $this->mOutput
->setSections( $tocraw );
3575 # Never ever show TOC if no headers
3576 if( $numVisible < 1 ) {
3581 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3582 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3584 $toc = $sk->tocList( $toc );
3587 # split up and insert constructed headlines
3589 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3592 foreach( $blocks as $block ) {
3593 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3594 # This is the [edit] link that appears for the top block of text when
3595 # section editing is enabled
3597 # Disabled because it broke block formatting
3598 # For example, a bullet point in the top line
3599 # $full .= $sk->editSectionLink(0);
3602 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3603 # Top anchor now in skin
3607 if( !empty( $head[$i] ) ) {
3612 if( $this->mForceTocPosition
) {
3613 return str_replace( '<!--MWTOC-->', $toc, $full );
3620 * Transform wiki markup when saving a page by doing \r\n -> \n
3621 * conversion, substitting signatures, {{subst:}} templates, etc.
3623 * @param string $text the text to transform
3624 * @param Title &$title the Title object for the current article
3625 * @param User &$user the User object describing the current user
3626 * @param ParserOptions $options parsing options
3627 * @param bool $clearState whether to clear the parser state first
3628 * @return string the altered wiki markup
3631 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3632 $this->mOptions
= $options;
3633 $this->setTitle( $title );
3634 $this->setOutputType( self
::OT_WIKI
);
3636 if ( $clearState ) {
3637 $this->clearState();
3643 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3644 $text = $this->pstPass2( $text, $user );
3645 $text = $this->mStripState
->unstripBoth( $text );
3650 * Pre-save transform helper function
3653 function pstPass2( $text, $user ) {
3654 global $wgContLang, $wgLocaltimezone;
3656 /* Note: This is the timestamp saved as hardcoded wikitext to
3657 * the database, we use $wgContLang here in order to give
3658 * everyone the same signature and use the default one rather
3659 * than the one selected in each user's preferences.
3661 if ( isset( $wgLocaltimezone ) ) {
3662 $oldtz = getenv( 'TZ' );
3663 putenv( 'TZ='.$wgLocaltimezone );
3665 $d = $wgContLang->timeanddate( $this->mOptions
->getTimestamp(), false, false) .
3666 ' (' . date( 'T' ) . ')';
3667 if ( isset( $wgLocaltimezone ) ) {
3668 putenv( 'TZ='.$oldtz );
3671 # Variable replacement
3672 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3673 $text = $this->replaceVariables( $text );
3676 $sigText = $this->getUserSig( $user );
3677 $text = strtr( $text, array(
3679 '~~~~' => "$sigText $d",
3683 # Context links: [[|name]] and [[name (context)|]]
3685 global $wgLegalTitleChars;
3686 $tc = "[$wgLegalTitleChars]";
3687 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3689 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3690 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3691 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3693 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3694 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3695 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3697 $t = $this->mTitle
->getText();
3699 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3700 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3701 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3702 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3704 # if there's no context, don't bother duplicating the title
3705 $text = preg_replace( $p2, '[[\\1]]', $text );
3708 # Trim trailing whitespace
3709 $text = rtrim( $text );
3715 * Fetch the user's signature text, if any, and normalize to
3716 * validated, ready-to-insert wikitext.
3722 function getUserSig( &$user ) {
3723 global $wgMaxSigChars;
3725 $username = $user->getName();
3726 $nickname = $user->getOption( 'nickname' );
3727 $nickname = $nickname === '' ?
$username : $nickname;
3729 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3730 $nickname = $username;
3731 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3732 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3733 # Sig. might contain markup; validate this
3734 if( $this->validateSig( $nickname ) !== false ) {
3735 # Validated; clean up (if needed) and return it
3736 return $this->cleanSig( $nickname, true );
3738 # Failed to validate; fall back to the default
3739 $nickname = $username;
3740 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3744 // Make sure nickname doesnt get a sig in a sig
3745 $nickname = $this->cleanSigInSig( $nickname );
3747 # If we're still here, make it a link to the user page
3748 $userText = wfEscapeWikiText( $username );
3749 $nickText = wfEscapeWikiText( $nickname );
3750 if ( $user->isAnon() ) {
3751 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3753 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3758 * Check that the user's signature contains no bad XML
3760 * @param string $text
3761 * @return mixed An expanded string, or false if invalid.
3763 function validateSig( $text ) {
3764 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3768 * Clean up signature text
3770 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3771 * 2) Substitute all transclusions
3773 * @param string $text
3774 * @param $parsing Whether we're cleaning (preferences save) or parsing
3775 * @return string Signature text
3777 function cleanSig( $text, $parsing = false ) {
3780 $this->clearState();
3781 $this->setTitle( $wgTitle );
3782 $this->mOptions
= new ParserOptions
;
3783 $this->setOutputType
= self
::OT_PREPROCESS
;
3786 # FIXME: regex doesn't respect extension tags or nowiki
3787 # => Move this logic to braceSubstitution()
3788 $substWord = MagicWord
::get( 'subst' );
3789 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3790 $substText = '{{' . $substWord->getSynonym( 0 );
3792 $text = preg_replace( $substRegex, $substText, $text );
3793 $text = $this->cleanSigInSig( $text );
3794 $dom = $this->preprocessToDom( $text );
3795 $frame = $this->getPreprocessor()->newFrame();
3796 $text = $frame->expand( $dom );
3799 $text = $this->mStripState
->unstripBoth( $text );
3806 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3807 * @param string $text
3808 * @return string Signature text with /~{3,5}/ removed
3810 function cleanSigInSig( $text ) {
3811 $text = preg_replace( '/~{3,5}/', '', $text );
3816 * Set up some variables which are usually set up in parse()
3817 * so that an external function can call some class members with confidence
3820 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3821 $this->setTitle( $title );
3822 $this->mOptions
= $options;
3823 $this->setOutputType( $outputType );
3824 if ( $clearState ) {
3825 $this->clearState();
3830 * Wrapper for preprocess()
3832 * @param string $text the text to preprocess
3833 * @param ParserOptions $options options
3837 function transformMsg( $text, $options ) {
3839 static $executing = false;
3841 $fname = "Parser::transformMsg";
3843 # Guard against infinite recursion
3849 wfProfileIn($fname);
3850 $text = $this->preprocess( $text, $wgTitle, $options );
3853 wfProfileOut($fname);
3858 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3859 * The callback should have the following form:
3860 * function myParserHook( $text, $params, &$parser ) { ... }
3862 * Transform and return $text. Use $parser for any required context, e.g. use
3863 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3867 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3868 * @param mixed $callback The callback function (and object) to use for the tag
3870 * @return The old value of the mTagHooks array associated with the hook
3872 function setHook( $tag, $callback ) {
3873 $tag = strtolower( $tag );
3874 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3875 $this->mTagHooks
[$tag] = $callback;
3876 $this->mStripList
[] = $tag;
3881 function setTransparentTagHook( $tag, $callback ) {
3882 $tag = strtolower( $tag );
3883 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3884 $this->mTransparentTagHooks
[$tag] = $callback;
3890 * Remove all tag hooks
3892 function clearTagHooks() {
3893 $this->mTagHooks
= array();
3894 $this->mStripList
= $this->mDefaultStripList
;
3898 * Create a function, e.g. {{sum:1|2|3}}
3899 * The callback function should have the form:
3900 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3902 * The callback may either return the text result of the function, or an array with the text
3903 * in element 0, and a number of flags in the other elements. The names of the flags are
3904 * specified in the keys. Valid flags are:
3905 * found The text returned is valid, stop processing the template. This
3907 * nowiki Wiki markup in the return value should be escaped
3908 * isHTML The returned text is HTML, armour it against wikitext transformation
3912 * @param string $id The magic word ID
3913 * @param mixed $callback The callback function (and object) to use
3914 * @param integer $flags a combination of the following flags:
3915 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3917 * @return The old callback function for this name, if any
3919 function setFunctionHook( $id, $callback, $flags = 0 ) {
3920 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3921 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3923 # Add to function cache
3924 $mw = MagicWord
::get( $id );
3926 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3928 $synonyms = $mw->getSynonyms();
3929 $sensitive = intval( $mw->isCaseSensitive() );
3931 foreach ( $synonyms as $syn ) {
3933 if ( !$sensitive ) {
3934 $syn = strtolower( $syn );
3937 if ( !( $flags & SFH_NO_HASH
) ) {
3940 # Remove trailing colon
3941 if ( substr( $syn, -1, 1 ) == ':' ) {
3942 $syn = substr( $syn, 0, -1 );
3944 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3950 * Get all registered function hook identifiers
3954 function getFunctionHooks() {
3955 return array_keys( $this->mFunctionHooks
);
3959 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3960 * Placeholders created in Skin::makeLinkObj()
3961 * Returns an array of link CSS classes, indexed by PDBK.
3962 * $options is a bit field, RLH_FOR_UPDATE to select for update
3964 function replaceLinkHolders( &$text, $options = 0 ) {
3968 $fname = 'Parser::replaceLinkHolders';
3969 wfProfileIn( $fname );
3973 $linkcolour_ids = array();
3974 $sk = $this->mOptions
->getSkin();
3975 $linkCache =& LinkCache
::singleton();
3977 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3978 wfProfileIn( $fname.'-check' );
3979 $dbr = wfGetDB( DB_SLAVE
);
3980 $page = $dbr->tableName( 'page' );
3981 $threshold = $wgUser->getOption('stubthreshold');
3984 asort( $this->mLinkHolders
['namespaces'] );
3989 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3991 $title = $this->mLinkHolders
['titles'][$key];
3993 # Skip invalid entries.
3994 # Result will be ugly, but prevents crash.
3995 if ( is_null( $title ) ) {
3998 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4000 # Check if it's a static known link, e.g. interwiki
4001 if ( $title->isAlwaysKnown() ) {
4002 $colours[$pdbk] = '';
4003 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4004 $colours[$pdbk] = '';
4005 $this->mOutput
->addLink( $title, $id );
4006 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4007 $colours[$pdbk] = 'new';
4008 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4009 $colours[$pdbk] = 'new';
4011 # Not in the link cache, add it to the query
4012 if ( !isset( $current ) ) {
4014 $query = "SELECT page_id, page_namespace, page_title";
4015 if ( $threshold > 0 ) {
4016 $query .= ', page_len, page_is_redirect';
4018 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4019 } elseif ( $current != $ns ) {
4021 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4026 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4031 if ( $options & RLH_FOR_UPDATE
) {
4032 $query .= ' FOR UPDATE';
4035 $res = $dbr->query( $query, $fname );
4037 # Fetch data and form into an associative array
4038 # non-existent = broken
4039 while ( $s = $dbr->fetchObject($res) ) {
4040 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4041 $pdbk = $title->getPrefixedDBkey();
4042 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4043 $this->mOutput
->addLink( $title, $s->page_id
);
4044 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4045 //add id to the extension todolist
4046 $linkcolour_ids[$s->page_id
] = $pdbk;
4048 //pass an array of page_ids to an extension
4049 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4051 wfProfileOut( $fname.'-check' );
4053 # Do a second query for different language variants of links and categories
4054 if($wgContLang->hasVariants()){
4055 $linkBatch = new LinkBatch();
4056 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4057 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4058 $varCategories = array(); // category replacements oldDBkey => newDBkey
4060 $categories = $this->mOutput
->getCategoryLinks();
4062 // Add variants of links to link batch
4063 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4064 $title = $this->mLinkHolders
['titles'][$key];
4065 if ( is_null( $title ) )
4068 $pdbk = $title->getPrefixedDBkey();
4069 $titleText = $title->getText();
4071 // generate all variants of the link title text
4072 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4074 // if link was not found (in first query), add all variants to query
4075 if ( !isset($colours[$pdbk]) ){
4076 foreach($allTextVariants as $textVariant){
4077 if($textVariant != $titleText){
4078 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4079 if(is_null($variantTitle)) continue;
4080 $linkBatch->addObj( $variantTitle );
4081 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4087 // process categories, check if a category exists in some variant
4088 foreach( $categories as $category ){
4089 $variants = $wgContLang->convertLinkToAllVariants($category);
4090 foreach($variants as $variant){
4091 if($variant != $category){
4092 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4093 if(is_null($variantTitle)) continue;
4094 $linkBatch->addObj( $variantTitle );
4095 $categoryMap[$variant] = $category;
4101 if(!$linkBatch->isEmpty()){
4103 $titleClause = $linkBatch->constructSet('page', $dbr);
4105 $variantQuery = "SELECT page_id, page_namespace, page_title";
4106 if ( $threshold > 0 ) {
4107 $variantQuery .= ', page_len, page_is_redirect';
4110 $variantQuery .= " FROM $page WHERE $titleClause";
4111 if ( $options & RLH_FOR_UPDATE
) {
4112 $variantQuery .= ' FOR UPDATE';
4115 $varRes = $dbr->query( $variantQuery, $fname );
4117 // for each found variants, figure out link holders and replace
4118 while ( $s = $dbr->fetchObject($varRes) ) {
4120 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4121 $varPdbk = $variantTitle->getPrefixedDBkey();
4122 $vardbk = $variantTitle->getDBkey();
4124 $holderKeys = array();
4125 if(isset($variantMap[$varPdbk])){
4126 $holderKeys = $variantMap[$varPdbk];
4127 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4128 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4131 // loop over link holders
4132 foreach($holderKeys as $key){
4133 $title = $this->mLinkHolders
['titles'][$key];
4134 if ( is_null( $title ) ) continue;
4136 $pdbk = $title->getPrefixedDBkey();
4138 if(!isset($colours[$pdbk])){
4139 // found link in some of the variants, replace the link holder data
4140 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4141 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4143 // set pdbk and colour
4144 $pdbks[$key] = $varPdbk;
4145 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4146 $linkcolour_ids[$s->page_id
] = $pdbk;
4148 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4151 // check if the object is a variant of a category
4152 if(isset($categoryMap[$vardbk])){
4153 $oldkey = $categoryMap[$vardbk];
4154 if($oldkey != $vardbk)
4155 $varCategories[$oldkey]=$vardbk;
4159 // rebuild the categories in original order (if there are replacements)
4160 if(count($varCategories)>0){
4162 $originalCats = $this->mOutput
->getCategories();
4163 foreach($originalCats as $cat => $sortkey){
4164 // make the replacement
4165 if( array_key_exists($cat,$varCategories) )
4166 $newCats[$varCategories[$cat]] = $sortkey;
4167 else $newCats[$cat] = $sortkey;
4169 $this->mOutput
->setCategoryLinks($newCats);
4174 # Construct search and replace arrays
4175 wfProfileIn( $fname.'-construct' );
4176 $replacePairs = array();
4177 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4178 $pdbk = $pdbks[$key];
4179 $searchkey = "<!--LINK $key-->";
4180 $title = $this->mLinkHolders
['titles'][$key];
4181 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4182 $linkCache->addBadLinkObj( $title );
4183 $colours[$pdbk] = 'new';
4184 $this->mOutput
->addLink( $title, 0 );
4185 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4186 $this->mLinkHolders
['texts'][$key],
4187 $this->mLinkHolders
['queries'][$key] );
4189 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4190 $this->mLinkHolders
['texts'][$key],
4191 $this->mLinkHolders
['queries'][$key] );
4194 $replacer = new HashtableReplacer( $replacePairs, 1 );
4195 wfProfileOut( $fname.'-construct' );
4198 wfProfileIn( $fname.'-replace' );
4199 $text = preg_replace_callback(
4200 '/(<!--LINK .*?-->)/',
4204 wfProfileOut( $fname.'-replace' );
4207 # Now process interwiki link holders
4208 # This is quite a bit simpler than internal links
4209 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4210 wfProfileIn( $fname.'-interwiki' );
4211 # Make interwiki link HTML
4212 $replacePairs = array();
4213 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4214 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4215 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4217 $replacer = new HashtableReplacer( $replacePairs, 1 );
4219 $text = preg_replace_callback(
4220 '/<!--IWLINK (.*?)-->/',
4223 wfProfileOut( $fname.'-interwiki' );
4226 wfProfileOut( $fname );
4231 * Replace <!--LINK--> link placeholders with plain text of links
4232 * (not HTML-formatted).
4233 * @param string $text
4236 function replaceLinkHoldersText( $text ) {
4237 $fname = 'Parser::replaceLinkHoldersText';
4238 wfProfileIn( $fname );
4240 $text = preg_replace_callback(
4241 '/<!--(LINK|IWLINK) (.*?)-->/',
4242 array( &$this, 'replaceLinkHoldersTextCallback' ),
4245 wfProfileOut( $fname );
4250 * @param array $matches
4254 function replaceLinkHoldersTextCallback( $matches ) {
4255 $type = $matches[1];
4257 if( $type == 'LINK' ) {
4258 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4259 return $this->mLinkHolders
['texts'][$key];
4261 } elseif( $type == 'IWLINK' ) {
4262 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4263 return $this->mInterwikiLinkHolders
['texts'][$key];
4270 * Tag hook handler for 'pre'.
4272 function renderPreTag( $text, $attribs ) {
4273 // Backwards-compatibility hack
4274 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4276 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4277 return wfOpenElement( 'pre', $attribs ) .
4278 Xml
::escapeTagsOnly( $content ) .
4283 * Renders an image gallery from a text with one line per image.
4284 * text labels may be given by using |-style alternative text. E.g.
4285 * Image:one.jpg|The number "1"
4286 * Image:tree.jpg|A tree
4287 * given as text will return the HTML of a gallery with two images,
4288 * labeled 'The number "1"' and
4291 function renderImageGallery( $text, $params ) {
4292 $ig = new ImageGallery();
4293 $ig->setContextTitle( $this->mTitle
);
4294 $ig->setShowBytes( false );
4295 $ig->setShowFilename( false );
4296 $ig->setParser( $this );
4297 $ig->setHideBadImages();
4298 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4299 $ig->useSkin( $this->mOptions
->getSkin() );
4300 $ig->mRevisionId
= $this->mRevisionId
;
4302 if( isset( $params['caption'] ) ) {
4303 $caption = $params['caption'];
4304 $caption = htmlspecialchars( $caption );
4305 $caption = $this->replaceInternalLinks( $caption );
4306 $ig->setCaptionHtml( $caption );
4308 if( isset( $params['perrow'] ) ) {
4309 $ig->setPerRow( $params['perrow'] );
4311 if( isset( $params['widths'] ) ) {
4312 $ig->setWidths( $params['widths'] );
4314 if( isset( $params['heights'] ) ) {
4315 $ig->setHeights( $params['heights'] );
4318 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4320 $lines = explode( "\n", $text );
4321 foreach ( $lines as $line ) {
4322 # match lines like these:
4323 # Image:someimage.jpg|This is some image
4325 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4327 if ( count( $matches ) == 0 ) {
4330 $tp = Title
::newFromText( $matches[1] );
4332 if( is_null( $nt ) ) {
4333 # Bogus title. Ignore these so we don't bomb out later.
4336 if ( isset( $matches[3] ) ) {
4337 $label = $matches[3];
4342 $html = $this->recursiveTagParse( trim( $label ) );
4344 $ig->add( $nt, $html );
4346 # Only add real images (bug #5586)
4347 if ( $nt->getNamespace() == NS_IMAGE
) {
4348 $this->mOutput
->addImage( $nt->getDBkey() );
4351 return $ig->toHTML();
4354 function getImageParams( $handler ) {
4356 $handlerClass = get_class( $handler );
4360 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4361 // Initialise static lists
4362 static $internalParamNames = array(
4363 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4364 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4365 'bottom', 'text-bottom' ),
4366 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4367 'upright', 'border' ),
4369 static $internalParamMap;
4370 if ( !$internalParamMap ) {
4371 $internalParamMap = array();
4372 foreach ( $internalParamNames as $type => $names ) {
4373 foreach ( $names as $name ) {
4374 $magicName = str_replace( '-', '_', "img_$name" );
4375 $internalParamMap[$magicName] = array( $type, $name );
4380 // Add handler params
4381 $paramMap = $internalParamMap;
4383 $handlerParamMap = $handler->getParamMap();
4384 foreach ( $handlerParamMap as $magic => $paramName ) {
4385 $paramMap[$magic] = array( 'handler', $paramName );
4388 $this->mImageParams
[$handlerClass] = $paramMap;
4389 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4391 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4395 * Parse image options text and use it to make an image
4397 function makeImage( $title, $options ) {
4398 # @TODO: let the MediaHandler specify its transform parameters
4400 # Check if the options text is of the form "options|alt text"
4402 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4403 # * left no resizing, just left align. label is used for alt= only
4404 # * right same, but right aligned
4405 # * none same, but not aligned
4406 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4407 # * center center the image
4408 # * framed Keep original image size, no magnify-button.
4409 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4410 # * upright reduce width for upright images, rounded to full __0 px
4411 # * border draw a 1px border around the image
4412 # vertical-align values (no % or length right now):
4422 $parts = array_map( 'trim', explode( '|', $options) );
4423 $sk = $this->mOptions
->getSkin();
4425 # Give extensions a chance to select the file revision for us
4426 $skip = $time = false;
4427 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4430 return $sk->makeLinkObj( $title );
4434 $file = wfFindFile( $title, $time );
4435 $handler = $file ?
$file->getHandler() : false;
4437 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4439 # Process the input parameters
4441 $params = array( 'frame' => array(), 'handler' => array(),
4442 'horizAlign' => array(), 'vertAlign' => array() );
4443 foreach( $parts as $part ) {
4444 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4445 if ( isset( $paramMap[$magicName] ) ) {
4446 list( $type, $paramName ) = $paramMap[$magicName];
4447 $params[$type][$paramName] = $value;
4449 // Special case; width and height come in one variable together
4450 if( $type == 'handler' && $paramName == 'width' ) {
4452 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4453 $params[$type]['width'] = intval( $m[1] );
4454 $params[$type]['height'] = intval( $m[2] );
4456 $params[$type]['width'] = intval( $value );
4464 # Process alignment parameters
4465 if ( $params['horizAlign'] ) {
4466 $params['frame']['align'] = key( $params['horizAlign'] );
4468 if ( $params['vertAlign'] ) {
4469 $params['frame']['valign'] = key( $params['vertAlign'] );
4472 # Validate the handler parameters
4474 foreach ( $params['handler'] as $name => $value ) {
4475 if ( !$handler->validateParam( $name, $value ) ) {
4476 unset( $params['handler'][$name] );
4481 # Strip bad stuff out of the alt text
4482 $alt = $this->replaceLinkHoldersText( $caption );
4484 # make sure there are no placeholders in thumbnail attributes
4485 # that are later expanded to html- so expand them now and
4487 $alt = $this->mStripState
->unstripBoth( $alt );
4488 $alt = Sanitizer
::stripAllTags( $alt );
4490 $params['frame']['alt'] = $alt;
4491 $params['frame']['caption'] = $caption;
4493 # Linker does the rest
4494 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4496 # Give the handler a chance to modify the parser object
4498 $handler->parserTransformHook( $this, $file );
4505 * Set a flag in the output object indicating that the content is dynamic and
4506 * shouldn't be cached.
4508 function disableCache() {
4509 wfDebug( "Parser output marked as uncacheable.\n" );
4510 $this->mOutput
->mCacheTime
= -1;
4514 * Callback from the Sanitizer for expanding items found in HTML attribute
4515 * values, so they can be safely tested and escaped.
4516 * @param string $text
4517 * @param PPFrame $frame
4521 function attributeStripCallback( &$text, $frame = false ) {
4522 $text = $this->replaceVariables( $text, $frame );
4523 $text = $this->mStripState
->unstripBoth( $text );
4532 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4533 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4534 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4540 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4545 * Break wikitext input into sections, and either pull or replace
4546 * some particular section's text.
4548 * External callers should use the getSection and replaceSection methods.
4550 * @param string $text Page wikitext
4551 * @param string $section A section identifier string of the form:
4552 * <flag1> - <flag2> - ... - <section number>
4554 * Currently the only recognised flag is "T", which means the target section number
4555 * was derived during a template inclusion parse, in other words this is a template
4556 * section edit link. If no flags are given, it was an ordinary section edit link.
4557 * This flag is required to avoid a section numbering mismatch when a section is
4558 * enclosed by <includeonly> (bug 6563).
4560 * The section number 0 pulls the text before the first heading; other numbers will
4561 * pull the given section along with its lower-level subsections. If the section is
4562 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4564 * @param string $mode One of "get" or "replace"
4565 * @param string $newText Replacement text for section data.
4566 * @return string for "get", the extracted section text.
4567 * for "replace", the whole page with the section replaced.
4569 private function extractSections( $text, $section, $mode, $newText='' ) {
4571 $this->clearState();
4572 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4573 $this->mOptions
= new ParserOptions
;
4574 $this->setOutputType( self
::OT_WIKI
);
4576 $frame = $this->getPreprocessor()->newFrame();
4578 // Process section extraction flags
4580 $sectionParts = explode( '-', $section );
4581 $sectionIndex = array_pop( $sectionParts );
4582 foreach ( $sectionParts as $part ) {
4583 if ( $part == 'T' ) {
4584 $flags |
= self
::PTD_FOR_INCLUSION
;
4587 // Preprocess the text
4588 $root = $this->preprocessToDom( $text, $flags );
4590 // <h> nodes indicate section breaks
4591 // They can only occur at the top level, so we can find them by iterating the root's children
4592 $node = $root->getFirstChild();
4594 // Find the target section
4595 if ( $sectionIndex == 0 ) {
4596 // Section zero doesn't nest, level=big
4597 $targetLevel = 1000;
4600 if ( $node->getName() == 'h' ) {
4601 $bits = $node->splitHeading();
4602 if ( $bits['i'] == $sectionIndex ) {
4603 $targetLevel = $bits['level'];
4607 if ( $mode == 'replace' ) {
4608 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4610 $node = $node->getNextSibling();
4616 if ( $mode == 'get' ) {
4623 // Find the end of the section, including nested sections
4625 if ( $node->getName() == 'h' ) {
4626 $bits = $node->splitHeading();
4627 $curLevel = $bits['level'];
4628 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4632 if ( $mode == 'get' ) {
4633 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4635 $node = $node->getNextSibling();
4638 // Write out the remainder (in replace mode only)
4639 if ( $mode == 'replace' ) {
4640 // Output the replacement text
4641 // Add two newlines on -- trailing whitespace in $newText is conventionally
4642 // stripped by the editor, so we need both newlines to restore the paragraph gap
4643 $outText .= $newText . "\n\n";
4645 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4646 $node = $node->getNextSibling();
4650 if ( is_string( $outText ) ) {
4651 // Re-insert stripped tags
4652 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4659 * This function returns the text of a section, specified by a number ($section).
4660 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4661 * the first section before any such heading (section 0).
4663 * If a section contains subsections, these are also returned.
4665 * @param string $text text to look in
4666 * @param string $section section identifier
4667 * @param string $deftext default to return if section is not found
4668 * @return string text of the requested section
4670 public function getSection( $text, $section, $deftext='' ) {
4671 return $this->extractSections( $text, $section, "get", $deftext );
4674 public function replaceSection( $oldtext, $section, $text ) {
4675 return $this->extractSections( $oldtext, $section, "replace", $text );
4679 * Get the timestamp associated with the current revision, adjusted for
4680 * the default server-local timestamp
4682 function getRevisionTimestamp() {
4683 if ( is_null( $this->mRevisionTimestamp
) ) {
4684 wfProfileIn( __METHOD__
);
4686 $dbr = wfGetDB( DB_SLAVE
);
4687 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4688 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4690 // Normalize timestamp to internal MW format for timezone processing.
4691 // This has the added side-effect of replacing a null value with
4692 // the current time, which gives us more sensible behavior for
4694 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4696 // The cryptic '' timezone parameter tells to use the site-default
4697 // timezone offset instead of the user settings.
4699 // Since this value will be saved into the parser cache, served
4700 // to other users, and potentially even used inside links and such,
4701 // it needs to be consistent for all visitors.
4702 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4704 wfProfileOut( __METHOD__
);
4706 return $this->mRevisionTimestamp
;
4710 * Mutator for $mDefaultSort
4712 * @param $sort New value
4714 public function setDefaultSort( $sort ) {
4715 $this->mDefaultSort
= $sort;
4719 * Accessor for $mDefaultSort
4720 * Will use the title/prefixed title if none is set
4724 public function getDefaultSort() {
4725 if( $this->mDefaultSort
!== false ) {
4726 return $this->mDefaultSort
;
4728 return $this->mTitle
->getNamespace() == NS_CATEGORY
4729 ?
$this->mTitle
->getText()
4730 : $this->mTitle
->getPrefixedText();
4735 * Try to guess the section anchor name based on a wikitext fragment
4736 * presumably extracted from a heading, for example "Header" from
4739 public function guessSectionNameFromWikiText( $text ) {
4740 # Strip out wikitext links(they break the anchor)
4741 $text = $this->stripSectionName( $text );
4742 $headline = Sanitizer
::decodeCharReferences( $text );
4744 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4745 $headline = trim( $headline );
4746 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4747 $replacearray = array(
4752 array_keys( $replacearray ),
4753 array_values( $replacearray ),
4758 * Strips a text string of wikitext for use in a section anchor
4760 * Accepts a text string and then removes all wikitext from the
4761 * string and leaves only the resultant text (i.e. the result of
4762 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4763 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4764 * to create valid section anchors by mimicing the output of the
4765 * parser when headings are parsed.
4767 * @param $text string Text string to be stripped of wikitext
4768 * for use in a Section anchor
4769 * @return Filtered text string
4771 public function stripSectionName( $text ) {
4772 # Strip internal link markup
4773 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4774 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4776 # Strip external link markup (FIXME: Not Tolerant to blank link text
4777 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4778 # on how many empty links there are on the page - need to figure that out.
4779 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4781 # Parse wikitext quotes (italics & bold)
4782 $text = $this->doQuotes($text);
4785 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4789 function srvus( $text ) {
4790 return $this->testSrvus( $text, $this->mOutputType
);
4794 * strip/replaceVariables/unstrip for preprocessor regression testing
4796 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4797 $this->clearState();
4798 if ( ! ( $title instanceof Title
) ) {
4799 $title = Title
::newFromText( $title );
4801 $this->mTitle
= $title;
4802 $this->mOptions
= $options;
4803 $this->setOutputType( $outputType );
4804 $text = $this->replaceVariables( $text );
4805 $text = $this->mStripState
->unstripBoth( $text );
4806 $text = Sanitizer
::removeHTMLtags( $text );
4810 function testPst( $text, $title, $options ) {
4812 if ( ! ( $title instanceof Title
) ) {
4813 $title = Title
::newFromText( $title );
4815 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4818 function testPreprocess( $text, $title, $options ) {
4819 if ( ! ( $title instanceof Title
) ) {
4820 $title = Title
::newFromText( $title );
4822 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4825 function markerSkipCallback( $s, $callback ) {
4828 while ( $i < strlen( $s ) ) {
4829 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4830 if ( $markerStart === false ) {
4831 $out .= call_user_func( $callback, substr( $s, $i ) );
4834 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4835 $markerEnd = strpos( $s, $this->mMarkerSuffix
, $markerStart );
4836 if ( $markerEnd === false ) {
4837 $out .= substr( $s, $markerStart );
4840 $markerEnd +
= strlen( $this->mMarkerSuffix
);
4841 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4851 * @todo document, briefly.
4852 * @addtogroup Parser
4855 var $general, $nowiki;
4857 function __construct() {
4858 $this->general
= new ReplacementArray
;
4859 $this->nowiki
= new ReplacementArray
;
4862 function unstripGeneral( $text ) {
4863 wfProfileIn( __METHOD__
);
4866 $text = $this->general
->replace( $text );
4867 } while ( $text != $oldText );
4868 wfProfileOut( __METHOD__
);
4872 function unstripNoWiki( $text ) {
4873 wfProfileIn( __METHOD__
);
4876 $text = $this->nowiki
->replace( $text );
4877 } while ( $text != $oldText );
4878 wfProfileOut( __METHOD__
);
4882 function unstripBoth( $text ) {
4883 wfProfileIn( __METHOD__
);
4886 $text = $this->general
->replace( $text );
4887 $text = $this->nowiki
->replace( $text );
4888 } while ( $text != $oldText );
4889 wfProfileOut( __METHOD__
);
4895 * @todo document, briefly.
4896 * @addtogroup Parser
4898 class OnlyIncludeReplacer
{
4901 function replace( $matches ) {
4902 if ( substr( $matches[1], -1 ) == "\n" ) {
4903 $this->output
.= substr( $matches[1], 0, -1 );
4905 $this->output
.= $matches[1];