5 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
90 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
91 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
92 $mExtLinkBracketedRegex, $mPreprocessor, $mDefaultStripList;
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->mTagHooks
= array();
122 $this->mTransparentTagHooks
= array();
123 $this->mFunctionHooks
= array();
124 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
125 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
126 $this->mMarkerSuffix
= "-QINU\x7f";
127 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
128 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
129 if ( isset( $conf['preprocessorClass'] ) ) {
130 $this->mPreprocessorClass
= $conf['preprocessorClass'];
132 $this->mPreprocessorClass
= 'Preprocessor_DOM';
134 $this->mFirstCall
= true;
138 * Do various kinds of initialisation on the first call of the parser
140 function firstCallInit() {
141 if ( !$this->mFirstCall
) {
144 $this->mFirstCall
= false;
146 wfProfileIn( __METHOD__
);
147 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
149 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
151 # Syntax for arguments (see self::setFunctionHook):
152 # "name for lookup in localized magic words array",
154 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
155 # instead of {{#int:...}})
156 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
174 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
175 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
176 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
177 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
178 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
179 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
180 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
181 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
182 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
183 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS
);
185 if ( $wgAllowDisplayTitle ) {
186 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
188 if ( $wgAllowSlowParserFunctions ) {
189 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
192 $this->initialiseVariables();
194 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
195 wfProfileOut( __METHOD__
);
203 function clearState() {
204 wfProfileIn( __METHOD__
);
205 if ( $this->mFirstCall
) {
206 $this->firstCallInit();
208 $this->mOutput
= new ParserOutput
;
209 $this->mAutonumber
= 0;
210 $this->mLastSection
= '';
211 $this->mDTopen
= false;
212 $this->mIncludeCount
= array();
213 $this->mStripState
= new StripState
;
214 $this->mArgStack
= false;
215 $this->mInPre
= false;
216 $this->mInterwikiLinkHolders
= array(
220 $this->mLinkHolders
= array(
221 'namespaces' => array(),
223 'queries' => array(),
227 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
230 * Prefix for temporary replacement strings for the multipass parser.
231 * \x07 should never appear in input as it's disallowed in XML.
232 * Using it at the front also gives us a little extra robustness
233 * since it shouldn't match when butted up against identifier-like
236 * Must not consist of all title characters, or else it will change
237 * the behaviour of <nowiki> in a link.
239 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
240 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
242 # Clear these on every parse, bug 4549
243 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
245 $this->mShowToc
= true;
246 $this->mForceTocPosition
= false;
247 $this->mIncludeSizes
= array(
251 $this->mPPNodeCount
= 0;
252 $this->mDefaultSort
= false;
253 $this->mHeadings
= array();
255 wfRunHooks( 'ParserClearState', array( &$this ) );
256 wfProfileOut( __METHOD__
);
259 function setOutputType( $ot ) {
260 $this->mOutputType
= $ot;
263 'html' => $ot == self
::OT_HTML
,
264 'wiki' => $ot == self
::OT_WIKI
,
265 'pre' => $ot == self
::OT_PREPROCESS
,
270 * Set the context title
272 function setTitle( $t ) {
273 if ( !$t ||
$t instanceof FakeTitle
) {
274 $t = Title
::newFromText( 'NO TITLE' );
276 if ( strval( $t->getFragment() ) !== '' ) {
277 # Strip the fragment to avoid various odd effects
278 $this->mTitle
= clone $t;
279 $this->mTitle
->setFragment( '' );
286 * Accessor for mUniqPrefix.
290 function uniqPrefix() {
291 if( !isset( $this->mUniqPrefix
) ) {
292 // @fixme this is probably *horribly wrong*
293 // LanguageConverter seems to want $wgParser's uniqPrefix, however
294 // if this is called for a parser cache hit, the parser may not
295 // have ever been initialized in the first place.
296 // Not really sure what the heck is supposed to be going on here.
298 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
300 return $this->mUniqPrefix
;
304 * Convert wikitext to HTML
305 * Do not call this function recursively.
307 * @param string $text Text we want to parse
308 * @param Title &$title A title object
309 * @param array $options
310 * @param boolean $linestart
311 * @param boolean $clearState
312 * @param int $revid number to pass in {{REVISIONID}}
313 * @return ParserOutput a ParserOutput
315 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
317 * First pass--just handle <nowiki> sections, pass the rest off
318 * to internalParse() which does all the real work.
321 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
322 $fname = 'Parser::parse-' . wfGetCaller();
323 wfProfileIn( __METHOD__
);
324 wfProfileIn( $fname );
330 $this->mOptions
= $options;
331 $this->setTitle( $title );
332 $oldRevisionId = $this->mRevisionId
;
333 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
334 if( $revid !== null ) {
335 $this->mRevisionId
= $revid;
336 $this->mRevisionTimestamp
= null;
338 $this->setOutputType( self
::OT_HTML
);
339 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
341 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
342 $text = $this->internalParse( $text );
343 $text = $this->mStripState
->unstripGeneral( $text );
345 # Clean up special characters, only run once, next-to-last before doBlockLevels
347 # french spaces, last one Guillemet-left
348 # only if there is something before the space
349 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
350 # french spaces, Guillemet-right
351 '/(\\302\\253) /' => '\\1 ',
353 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
356 $text = $this->doBlockLevels( $text, $linestart );
358 $this->replaceLinkHolders( $text );
360 # the position of the parserConvert() call should not be changed. it
361 # assumes that the links are all replaced and the only thing left
362 # is the <nowiki> mark.
363 # Side-effects: this calls $this->mOutput->setTitleText()
364 $text = $wgContLang->parserConvert( $text, $this );
366 $text = $this->mStripState
->unstripNoWiki( $text );
368 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
370 //!JF Move to its own function
372 $uniq_prefix = $this->mUniqPrefix
;
374 $elements = array_keys( $this->mTransparentTagHooks
);
375 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
377 foreach( $matches as $marker => $data ) {
378 list( $element, $content, $params, $tag ) = $data;
379 $tagName = strtolower( $element );
380 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
381 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
382 array( $content, $params, $this ) );
386 $this->mStripState
->general
->setPair( $marker, $output );
388 $text = $this->mStripState
->unstripGeneral( $text );
390 $text = Sanitizer
::normalizeCharReferences( $text );
392 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
393 $text = Parser
::tidy($text);
395 # attempt to sanitize at least some nesting problems
396 # (bug #2702 and quite a few others)
398 # ''Something [http://www.cool.com cool''] -->
399 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
400 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
401 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
402 # fix up an anchor inside another anchor, only
403 # at least for a single single nested link (bug 3695)
404 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
405 '\\1\\2</a>\\3</a>\\1\\4</a>',
406 # fix div inside inline elements- doBlockLevels won't wrap a line which
407 # contains a div, so fix it up here; replace
408 # div with escaped text
409 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
410 '\\1\\3<div\\5>\\6</div>\\8\\9',
411 # remove empty italic or bold tag pairs, some
412 # introduced by rules above
413 '/<([bi])><\/\\1>/' => '',
416 $text = preg_replace(
417 array_keys( $tidyregs ),
418 array_values( $tidyregs ),
422 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
424 # Information on include size limits, for the benefit of users who try to skirt them
425 if ( $this->mOptions
->getEnableLimitReport() ) {
426 $max = $this->mOptions
->getMaxIncludeSize();
428 "NewPP limit report\n" .
429 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
430 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
431 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
432 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
433 $text .= "\n<!-- \n$limitReport-->\n";
435 $this->mOutput
->setText( $text );
436 $this->mRevisionId
= $oldRevisionId;
437 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
438 wfProfileOut( $fname );
439 wfProfileOut( __METHOD__
);
441 return $this->mOutput
;
445 * Recursive parser entry point that can be called from an extension tag
448 function recursiveTagParse( $text ) {
449 wfProfileIn( __METHOD__
);
450 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
451 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
452 $text = $this->internalParse( $text );
453 wfProfileOut( __METHOD__
);
458 * Expand templates and variables in the text, producing valid, static wikitext.
459 * Also removes comments.
461 function preprocess( $text, $title, $options, $revid = null ) {
462 wfProfileIn( __METHOD__
);
464 $this->setOutputType( self
::OT_PREPROCESS
);
465 $this->mOptions
= $options;
466 $this->setTitle( $title );
467 if( $revid !== null ) {
468 $this->mRevisionId
= $revid;
470 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
471 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
472 $text = $this->replaceVariables( $text );
473 $text = $this->mStripState
->unstripBoth( $text );
474 wfProfileOut( __METHOD__
);
479 * Get a random string
484 function getRandomString() {
485 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
488 function &getTitle() { return $this->mTitle
; }
489 function getOptions() { return $this->mOptions
; }
491 function getFunctionLang() {
492 global $wgLang, $wgContLang;
493 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
497 * Get a preprocessor object
499 function getPreprocessor() {
500 if ( !isset( $this->mPreprocessor
) ) {
501 $class = $this->mPreprocessorClass
;
502 $this->mPreprocessor
= new $class( $this );
504 return $this->mPreprocessor
;
508 * Replaces all occurrences of HTML-style comments and the given tags
509 * in the text with a random marker and returns teh next text. The output
510 * parameter $matches will be an associative array filled with data in
512 * 'UNIQ-xxxxx' => array(
515 * array( 'param' => 'x' ),
516 * '<element param="x">tag content</element>' ) )
518 * @param $elements list of element names. Comments are always extracted.
519 * @param $text Source text string.
520 * @param $uniq_prefix
525 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
530 $taglist = implode( '|', $elements );
531 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
533 while ( '' != $text ) {
534 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
536 if( count( $p ) < 5 ) {
539 if( count( $p ) > 5 ) {
553 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
554 $stripped .= $marker;
556 if ( $close === '/>' ) {
557 // Empty element tag, <tag />
562 if( $element == '!--' ) {
565 $end = "/(<\\/$element\\s*>)/i";
567 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
569 if( count( $q ) < 3 ) {
570 # No end tag -- let it run out to the end of the text.
579 $matches[$marker] = array( $element,
581 Sanitizer
::decodeTagAttributes( $attributes ),
582 "<$element$attributes$close$content$tail" );
588 * Get a list of strippable XML-like elements
590 function getStripList() {
592 $elements = $this->mStripList
;
594 $elements[] = 'html';
596 if( $this->mOptions
->getUseTeX() ) {
597 $elements[] = 'math';
603 * @deprecated use replaceVariables
605 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
610 * Restores pre, math, and other extensions removed by strip()
612 * always call unstripNoWiki() after this one
614 * @deprecated use $this->mStripState->unstrip()
616 function unstrip( $text, $state ) {
617 return $state->unstripGeneral( $text );
621 * Always call this after unstrip() to preserve the order
624 * @deprecated use $this->mStripState->unstrip()
626 function unstripNoWiki( $text, $state ) {
627 return $state->unstripNoWiki( $text );
631 * @deprecated use $this->mStripState->unstripBoth()
633 function unstripForHTML( $text ) {
634 return $this->mStripState
->unstripBoth( $text );
638 * Add an item to the strip state
639 * Returns the unique tag which must be inserted into the stripped text
640 * The tag will be replaced with the original text in unstrip()
644 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
648 $this->mStripState
->general
->setPair( $rnd, $text );
653 * Interface with html tidy, used if $wgUseTidy = true.
654 * If tidy isn't able to correct the markup, the original will be
655 * returned in all its glory with a warning comment appended.
657 * Either the external tidy program or the in-process tidy extension
658 * will be used depending on availability. Override the default
659 * $wgTidyInternal setting to disable the internal if it's not working.
661 * @param string $text Hideous HTML input
662 * @return string Corrected HTML output
666 function tidy( $text ) {
667 global $wgTidyInternal;
668 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
669 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
670 '<head><title>test</title></head><body>'.$text.'</body></html>';
671 if( $wgTidyInternal ) {
672 $correctedtext = Parser
::internalTidy( $wrappedtext );
674 $correctedtext = Parser
::externalTidy( $wrappedtext );
676 if( is_null( $correctedtext ) ) {
677 wfDebug( "Tidy error detected!\n" );
678 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
680 return $correctedtext;
684 * Spawn an external HTML tidy process and get corrected markup back from it.
689 function externalTidy( $text ) {
690 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
691 $fname = 'Parser::externalTidy';
692 wfProfileIn( $fname );
697 $descriptorspec = array(
698 0 => array('pipe', 'r'),
699 1 => array('pipe', 'w'),
700 2 => array('file', wfGetNull(), 'a')
703 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
704 if (is_resource($process)) {
705 // Theoretically, this style of communication could cause a deadlock
706 // here. If the stdout buffer fills up, then writes to stdin could
707 // block. This doesn't appear to happen with tidy, because tidy only
708 // writes to stdout after it's finished reading from stdin. Search
709 // for tidyParseStdin and tidySaveStdout in console/tidy.c
710 fwrite($pipes[0], $text);
712 while (!feof($pipes[1])) {
713 $cleansource .= fgets($pipes[1], 1024);
716 proc_close($process);
719 wfProfileOut( $fname );
721 if( $cleansource == '' && $text != '') {
722 // Some kind of error happened, so we couldn't get the corrected text.
723 // Just give up; we'll use the source text and append a warning.
731 * Use the HTML tidy PECL extension to use the tidy library in-process,
732 * saving the overhead of spawning a new process.
734 * 'pear install tidy' should be able to compile the extension module.
739 function internalTidy( $text ) {
740 global $wgTidyConf, $IP, $wgDebugTidy;
741 $fname = 'Parser::internalTidy';
742 wfProfileIn( $fname );
745 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
746 $tidy->cleanRepair();
747 if( $tidy->getStatus() == 2 ) {
748 // 2 is magic number for fatal error
749 // http://www.php.net/manual/en/function.tidy-get-status.php
752 $cleansource = tidy_get_output( $tidy );
754 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
755 $cleansource .= "<!--\nTidy reports:\n" .
756 str_replace( '-->', '-->', $tidy->errorBuffer
) .
760 wfProfileOut( $fname );
765 * parse the wiki syntax used to render tables
769 function doTableStuff ( $text ) {
770 $fname = 'Parser::doTableStuff';
771 wfProfileIn( $fname );
773 $lines = explode ( "\n" , $text );
774 $td_history = array (); // Is currently a td tag open?
775 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
776 $tr_history = array (); // Is currently a tr tag open?
777 $tr_attributes = array (); // history of tr attributes
778 $has_opened_tr = array(); // Did this table open a <tr> element?
779 $indent_level = 0; // indent level of the table
780 foreach ( $lines as $key => $line )
782 $line = trim ( $line );
784 if( $line == '' ) { // empty line, go to next line
787 $first_character = $line{0};
790 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
791 // First check if we are starting a new table
792 $indent_level = strlen( $matches[1] );
794 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
795 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
797 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
798 array_push ( $td_history , false );
799 array_push ( $last_tag_history , '' );
800 array_push ( $tr_history , false );
801 array_push ( $tr_attributes , '' );
802 array_push ( $has_opened_tr , false );
803 } else if ( count ( $td_history ) == 0 ) {
804 // Don't do any of the following
806 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
807 // We are ending a table
808 $line = '</table>' . substr ( $line , 2 );
809 $last_tag = array_pop ( $last_tag_history );
811 if ( !array_pop ( $has_opened_tr ) ) {
812 $line = "<tr><td></td></tr>{$line}";
815 if ( array_pop ( $tr_history ) ) {
816 $line = "</tr>{$line}";
819 if ( array_pop ( $td_history ) ) {
820 $line = "</{$last_tag}>{$line}";
822 array_pop ( $tr_attributes );
823 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
824 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
825 // Now we have a table row
826 $line = preg_replace( '#^\|-+#', '', $line );
828 // Whats after the tag is now only attributes
829 $attributes = $this->mStripState
->unstripBoth( $line );
830 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
831 array_pop ( $tr_attributes );
832 array_push ( $tr_attributes , $attributes );
835 $last_tag = array_pop ( $last_tag_history );
836 array_pop ( $has_opened_tr );
837 array_push ( $has_opened_tr , true );
839 if ( array_pop ( $tr_history ) ) {
843 if ( array_pop ( $td_history ) ) {
844 $line = "</{$last_tag}>{$line}";
847 $lines[$key] = $line;
848 array_push ( $tr_history , false );
849 array_push ( $td_history , false );
850 array_push ( $last_tag_history , '' );
852 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
853 // This might be cell elements, td, th or captions
854 if ( substr ( $line , 0 , 2 ) == '|+' ) {
855 $first_character = '+';
856 $line = substr ( $line , 1 );
859 $line = substr ( $line , 1 );
861 if ( $first_character == '!' ) {
862 $line = str_replace ( '!!' , '||' , $line );
865 // Split up multiple cells on the same line.
866 // FIXME : This can result in improper nesting of tags processed
867 // by earlier parser steps, but should avoid splitting up eg
868 // attribute values containing literal "||".
869 $cells = StringUtils
::explodeMarkup( '||' , $line );
873 // Loop through each table cell
874 foreach ( $cells as $cell )
877 if ( $first_character != '+' )
879 $tr_after = array_pop ( $tr_attributes );
880 if ( !array_pop ( $tr_history ) ) {
881 $previous = "<tr{$tr_after}>\n";
883 array_push ( $tr_history , true );
884 array_push ( $tr_attributes , '' );
885 array_pop ( $has_opened_tr );
886 array_push ( $has_opened_tr , true );
889 $last_tag = array_pop ( $last_tag_history );
891 if ( array_pop ( $td_history ) ) {
892 $previous = "</{$last_tag}>{$previous}";
895 if ( $first_character == '|' ) {
897 } else if ( $first_character == '!' ) {
899 } else if ( $first_character == '+' ) {
900 $last_tag = 'caption';
905 array_push ( $last_tag_history , $last_tag );
907 // A cell could contain both parameters and data
908 $cell_data = explode ( '|' , $cell , 2 );
910 // Bug 553: Note that a '|' inside an invalid link should not
911 // be mistaken as delimiting cell parameters
912 if ( strpos( $cell_data[0], '[[' ) !== false ) {
913 $cell = "{$previous}<{$last_tag}>{$cell}";
914 } else if ( count ( $cell_data ) == 1 )
915 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
917 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
918 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
919 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
922 $lines[$key] .= $cell;
923 array_push ( $td_history , true );
928 // Closing open td, tr && table
929 while ( count ( $td_history ) > 0 )
931 if ( array_pop ( $td_history ) ) {
934 if ( array_pop ( $tr_history ) ) {
937 if ( !array_pop ( $has_opened_tr ) ) {
938 $lines[] = "<tr><td></td></tr>" ;
941 $lines[] = '</table>' ;
944 $output = implode ( "\n" , $lines ) ;
946 // special case: don't return empty table
947 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
951 wfProfileOut( $fname );
957 * Helper function for parse() that transforms wiki markup into
958 * HTML. Only called for $mOutputType == self::OT_HTML.
962 function internalParse( $text ) {
964 $fname = 'Parser::internalParse';
965 wfProfileIn( $fname );
967 # Hook to suspend the parser in this state
968 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
969 wfProfileOut( $fname );
973 $text = $this->replaceVariables( $text );
974 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
975 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
977 // Tables need to come after variable replacement for things to work
978 // properly; putting them before other transformations should keep
979 // exciting things like link expansions from showing up in surprising
981 $text = $this->doTableStuff( $text );
983 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
985 $text = $this->stripToc( $text );
986 $this->stripNoGallery( $text );
987 $text = $this->doHeadings( $text );
988 if($this->mOptions
->getUseDynamicDates()) {
989 $df =& DateFormatter
::getInstance();
990 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
992 $text = $this->doAllQuotes( $text );
993 $text = $this->replaceInternalLinks( $text );
994 $text = $this->replaceExternalLinks( $text );
996 # replaceInternalLinks may sometimes leave behind
997 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
998 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1000 $text = $this->doMagicLinks( $text );
1001 $text = $this->formatHeadings( $text, $isMain );
1003 wfProfileOut( $fname );
1008 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1009 * magic external links.
1013 function doMagicLinks( $text ) {
1014 wfProfileIn( __METHOD__
);
1015 $text = preg_replace_callback(
1017 <a.*?</a> | # Skip link text
1018 <.*?> | # Skip stuff inside HTML elements
1019 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1020 ISBN\s+(\b # ISBN, capture number as m[2]
1021 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1022 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1023 [0-9Xx] # check digit
1025 )!x', array( &$this, 'magicLinkCallback' ), $text );
1026 wfProfileOut( __METHOD__
);
1030 function magicLinkCallback( $m ) {
1031 if ( substr( $m[0], 0, 1 ) == '<' ) {
1034 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1036 $num = strtr( $isbn, array(
1041 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1042 $text = '<a href="' .
1043 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1044 "\" class=\"internal\">ISBN $isbn</a>";
1046 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1050 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1052 $urlmsg = 'pubmedurl';
1055 throw new MWException( __METHOD__
.': unrecognised match type "' .
1056 substr($m[0], 0, 20 ) . '"' );
1059 $url = wfMsg( $urlmsg, $id);
1060 $sk = $this->mOptions
->getSkin();
1061 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1062 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1068 * Parse headers and return html
1072 function doHeadings( $text ) {
1073 $fname = 'Parser::doHeadings';
1074 wfProfileIn( $fname );
1075 for ( $i = 6; $i >= 1; --$i ) {
1076 $h = str_repeat( '=', $i );
1077 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1078 "<h$i>\\1</h$i>", $text );
1080 wfProfileOut( $fname );
1085 * Replace single quotes with HTML markup
1087 * @return string the altered text
1089 function doAllQuotes( $text ) {
1090 $fname = 'Parser::doAllQuotes';
1091 wfProfileIn( $fname );
1093 $lines = explode( "\n", $text );
1094 foreach ( $lines as $line ) {
1095 $outtext .= $this->doQuotes ( $line ) . "\n";
1097 $outtext = substr($outtext, 0,-1);
1098 wfProfileOut( $fname );
1103 * Helper function for doAllQuotes()
1105 public function doQuotes( $text ) {
1106 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1107 if ( count( $arr ) == 1 )
1111 # First, do some preliminary work. This may shift some apostrophes from
1112 # being mark-up to being text. It also counts the number of occurrences
1113 # of bold and italics mark-ups.
1117 foreach ( $arr as $r )
1119 if ( ( $i %
2 ) == 1 )
1121 # If there are ever four apostrophes, assume the first is supposed to
1122 # be text, and the remaining three constitute mark-up for bold text.
1123 if ( strlen( $arr[$i] ) == 4 )
1128 # If there are more than 5 apostrophes in a row, assume they're all
1129 # text except for the last 5.
1130 else if ( strlen( $arr[$i] ) > 5 )
1132 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1135 # Count the number of occurrences of bold and italics mark-ups.
1136 # We are not counting sequences of five apostrophes.
1137 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1138 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1139 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1144 # If there is an odd number of both bold and italics, it is likely
1145 # that one of the bold ones was meant to be an apostrophe followed
1146 # by italics. Which one we cannot know for certain, but it is more
1147 # likely to be one that has a single-letter word before it.
1148 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1151 $firstsingleletterword = -1;
1152 $firstmultiletterword = -1;
1154 foreach ( $arr as $r )
1156 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1158 $x1 = substr ($arr[$i-1], -1);
1159 $x2 = substr ($arr[$i-1], -2, 1);
1161 if ($firstspace == -1) $firstspace = $i;
1162 } else if ($x2 == ' ') {
1163 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1165 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1171 # If there is a single-letter word, use it!
1172 if ($firstsingleletterword > -1)
1174 $arr [ $firstsingleletterword ] = "''";
1175 $arr [ $firstsingleletterword-1 ] .= "'";
1177 # If not, but there's a multi-letter word, use that one.
1178 else if ($firstmultiletterword > -1)
1180 $arr [ $firstmultiletterword ] = "''";
1181 $arr [ $firstmultiletterword-1 ] .= "'";
1183 # ... otherwise use the first one that has neither.
1184 # (notice that it is possible for all three to be -1 if, for example,
1185 # there is only one pentuple-apostrophe in the line)
1186 else if ($firstspace > -1)
1188 $arr [ $firstspace ] = "''";
1189 $arr [ $firstspace-1 ] .= "'";
1193 # Now let's actually convert our apostrophic mush to HTML!
1198 foreach ($arr as $r)
1202 if ($state == 'both')
1209 if (strlen ($r) == 2)
1212 { $output .= '</i>'; $state = ''; }
1213 else if ($state == 'bi')
1214 { $output .= '</i>'; $state = 'b'; }
1215 else if ($state == 'ib')
1216 { $output .= '</b></i><b>'; $state = 'b'; }
1217 else if ($state == 'both')
1218 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1219 else # $state can be 'b' or ''
1220 { $output .= '<i>'; $state .= 'i'; }
1222 else if (strlen ($r) == 3)
1225 { $output .= '</b>'; $state = ''; }
1226 else if ($state == 'bi')
1227 { $output .= '</i></b><i>'; $state = 'i'; }
1228 else if ($state == 'ib')
1229 { $output .= '</b>'; $state = 'i'; }
1230 else if ($state == 'both')
1231 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1232 else # $state can be 'i' or ''
1233 { $output .= '<b>'; $state .= 'b'; }
1235 else if (strlen ($r) == 5)
1238 { $output .= '</b><i>'; $state = 'i'; }
1239 else if ($state == 'i')
1240 { $output .= '</i><b>'; $state = 'b'; }
1241 else if ($state == 'bi')
1242 { $output .= '</i></b>'; $state = ''; }
1243 else if ($state == 'ib')
1244 { $output .= '</b></i>'; $state = ''; }
1245 else if ($state == 'both')
1246 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1247 else # ($state == '')
1248 { $buffer = ''; $state = 'both'; }
1253 # Now close all remaining tags. Notice that the order is important.
1254 if ($state == 'b' ||
$state == 'ib')
1256 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1260 # There might be lonely ''''', so make sure we have a buffer
1261 if ($state == 'both' && $buffer)
1262 $output .= '<b><i>'.$buffer.'</i></b>';
1268 * Replace external links
1270 * Note: this is all very hackish and the order of execution matters a lot.
1271 * Make sure to run maintenance/parserTests.php if you change this code.
1275 function replaceExternalLinks( $text ) {
1277 $fname = 'Parser::replaceExternalLinks';
1278 wfProfileIn( $fname );
1280 $sk = $this->mOptions
->getSkin();
1282 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1284 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1287 while ( $i<count( $bits ) ) {
1289 $protocol = $bits[$i++
];
1290 $text = $bits[$i++
];
1291 $trail = $bits[$i++
];
1293 # The characters '<' and '>' (which were escaped by
1294 # removeHTMLtags()) should not be included in
1295 # URLs, per RFC 2396.
1297 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1298 $text = substr($url, $m2[0][1]) . ' ' . $text;
1299 $url = substr($url, 0, $m2[0][1]);
1302 # If the link text is an image URL, replace it with an <img> tag
1303 # This happened by accident in the original parser, but some people used it extensively
1304 $img = $this->maybeMakeExternalImage( $text );
1305 if ( $img !== false ) {
1311 # Set linktype for CSS - if URL==text, link is essentially free
1312 $linktype = ($text == $url) ?
'free' : 'text';
1314 # No link text, e.g. [http://domain.tld/some.link]
1315 if ( $text == '' ) {
1316 # Autonumber if allowed. See bug #5918
1317 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1318 $text = '[' . ++
$this->mAutonumber
. ']';
1319 $linktype = 'autonumber';
1321 # Otherwise just use the URL
1322 $text = htmlspecialchars( $url );
1326 # Have link text, e.g. [http://domain.tld/some.link text]s
1328 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1331 $text = $wgContLang->markNoConversion($text);
1333 $url = Sanitizer
::cleanUrl( $url );
1335 # Process the trail (i.e. everything after this link up until start of the next link),
1336 # replacing any non-bracketed links
1337 $trail = $this->replaceFreeExternalLinks( $trail );
1339 # Use the encoded URL
1340 # This means that users can paste URLs directly into the text
1341 # Funny characters like ö aren't valid in URLs anyway
1342 # This was changed in August 2004
1343 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1345 # Register link in the output object.
1346 # Replace unnecessary URL escape codes with the referenced character
1347 # This prevents spammers from hiding links from the filters
1348 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1349 $this->mOutput
->addExternalLink( $pasteurized );
1352 wfProfileOut( $fname );
1357 * Replace anything that looks like a URL with a link
1360 function replaceFreeExternalLinks( $text ) {
1362 $fname = 'Parser::replaceFreeExternalLinks';
1363 wfProfileIn( $fname );
1365 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1366 $s = array_shift( $bits );
1369 $sk = $this->mOptions
->getSkin();
1371 while ( $i < count( $bits ) ){
1372 $protocol = $bits[$i++
];
1373 $remainder = $bits[$i++
];
1376 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1377 # Found some characters after the protocol that look promising
1378 $url = $protocol . $m[1];
1381 # special case: handle urls as url args:
1382 # http://www.example.com/foo?=http://www.example.com/bar
1383 if(strlen($trail) == 0 &&
1385 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1386 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1389 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1394 # The characters '<' and '>' (which were escaped by
1395 # removeHTMLtags()) should not be included in
1396 # URLs, per RFC 2396.
1398 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1399 $trail = substr($url, $m2[0][1]) . $trail;
1400 $url = substr($url, 0, $m2[0][1]);
1403 # Move trailing punctuation to $trail
1405 # If there is no left bracket, then consider right brackets fair game too
1406 if ( strpos( $url, '(' ) === false ) {
1410 $numSepChars = strspn( strrev( $url ), $sep );
1411 if ( $numSepChars ) {
1412 $trail = substr( $url, -$numSepChars ) . $trail;
1413 $url = substr( $url, 0, -$numSepChars );
1416 $url = Sanitizer
::cleanUrl( $url );
1418 # Is this an external image?
1419 $text = $this->maybeMakeExternalImage( $url );
1420 if ( $text === false ) {
1421 # Not an image, make a link
1422 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1423 # Register it in the output object...
1424 # Replace unnecessary URL escape codes with their equivalent characters
1425 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1426 $this->mOutput
->addExternalLink( $pasteurized );
1428 $s .= $text . $trail;
1430 $s .= $protocol . $remainder;
1433 wfProfileOut( $fname );
1438 * Replace unusual URL escape codes with their equivalent characters
1442 * @todo This can merge genuinely required bits in the path or query string,
1443 * breaking legit URLs. A proper fix would treat the various parts of
1444 * the URL differently; as a workaround, just use the output for
1445 * statistical records, not for actual linking/output.
1447 static function replaceUnusualEscapes( $url ) {
1448 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1449 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1453 * Callback function used in replaceUnusualEscapes().
1454 * Replaces unusual URL escape codes with their equivalent character
1458 private static function replaceUnusualEscapesCallback( $matches ) {
1459 $char = urldecode( $matches[0] );
1460 $ord = ord( $char );
1461 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1462 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1463 // No, shouldn't be escaped
1466 // Yes, leave it escaped
1472 * make an image if it's allowed, either through the global
1473 * option or through the exception
1476 function maybeMakeExternalImage( $url ) {
1477 $sk = $this->mOptions
->getSkin();
1478 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1479 $imagesexception = !empty($imagesfrom);
1481 if ( $this->mOptions
->getAllowExternalImages()
1482 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1483 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1485 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1492 * Process [[ ]] wikilinks
1496 function replaceInternalLinks( $s ) {
1498 static $fname = 'Parser::replaceInternalLinks' ;
1500 wfProfileIn( $fname );
1502 wfProfileIn( $fname.'-setup' );
1504 # the % is needed to support urlencoded titles as well
1505 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1507 $sk = $this->mOptions
->getSkin();
1509 #split the entire text string on occurences of [[
1510 $a = explode( '[[', ' ' . $s );
1511 #get the first element (all text up to first [[), and remove the space we added
1512 $s = array_shift( $a );
1513 $s = substr( $s, 1 );
1515 # Match a link having the form [[namespace:link|alternate]]trail
1517 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1518 # Match cases where there is no "]]", which might still be images
1519 static $e1_img = FALSE;
1520 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1522 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1524 if ( $useLinkPrefixExtension ) {
1525 # Match the end of a line for a word that's not followed by whitespace,
1526 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1527 $e2 = wfMsgForContent( 'linkprefix' );
1530 if( is_null( $this->mTitle
) ) {
1531 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1533 $nottalk = !$this->mTitle
->isTalkPage();
1535 if ( $useLinkPrefixExtension ) {
1537 if ( preg_match( $e2, $s, $m ) ) {
1538 $first_prefix = $m[2];
1540 $first_prefix = false;
1546 if($wgContLang->hasVariants()) {
1547 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1549 $selflink = array($this->mTitle
->getPrefixedText());
1551 $useSubpages = $this->areSubpagesAllowed();
1552 wfProfileOut( $fname.'-setup' );
1554 # Loop for each link
1555 for ($k = 0; isset( $a[$k] ); $k++
) {
1557 if ( $useLinkPrefixExtension ) {
1558 wfProfileIn( $fname.'-prefixhandling' );
1559 if ( preg_match( $e2, $s, $m ) ) {
1567 $prefix = $first_prefix;
1568 $first_prefix = false;
1570 wfProfileOut( $fname.'-prefixhandling' );
1573 $might_be_img = false;
1575 wfProfileIn( "$fname-e1" );
1576 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1578 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1579 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1580 # the real problem is with the $e1 regex
1583 # Still some problems for cases where the ] is meant to be outside punctuation,
1584 # and no image is in sight. See bug 2095.
1587 substr( $m[3], 0, 1 ) === ']' &&
1588 strpos($text, '[') !== false
1591 $text .= ']'; # so that replaceExternalLinks($text) works later
1592 $m[3] = substr( $m[3], 1 );
1594 # fix up urlencoded title texts
1595 if( strpos( $m[1], '%' ) !== false ) {
1596 # Should anchors '#' also be rejected?
1597 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1600 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1601 $might_be_img = true;
1603 if ( strpos( $m[1], '%' ) !== false ) {
1604 $m[1] = urldecode($m[1]);
1607 } else { # Invalid form; output directly
1608 $s .= $prefix . '[[' . $line ;
1609 wfProfileOut( "$fname-e1" );
1612 wfProfileOut( "$fname-e1" );
1613 wfProfileIn( "$fname-misc" );
1615 # Don't allow internal links to pages containing
1616 # PROTO: where PROTO is a valid URL protocol; these
1617 # should be external links.
1618 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1619 $s .= $prefix . '[[' . $line ;
1623 # Make subpage if necessary
1624 if( $useSubpages ) {
1625 $link = $this->maybeDoSubpageLink( $m[1], $text );
1630 $noforce = (substr($m[1], 0, 1) != ':');
1632 # Strip off leading ':'
1633 $link = substr($link, 1);
1636 wfProfileOut( "$fname-misc" );
1637 wfProfileIn( "$fname-title" );
1638 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1640 $s .= $prefix . '[[' . $line;
1641 wfProfileOut( "$fname-title" );
1645 $ns = $nt->getNamespace();
1646 $iw = $nt->getInterWiki();
1647 wfProfileOut( "$fname-title" );
1649 if ($might_be_img) { # if this is actually an invalid link
1650 wfProfileIn( "$fname-might_be_img" );
1651 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1653 while (isset ($a[$k+
1]) ) {
1654 #look at the next 'line' to see if we can close it there
1655 $spliced = array_splice( $a, $k +
1, 1 );
1656 $next_line = array_shift( $spliced );
1657 $m = explode( ']]', $next_line, 3 );
1658 if ( count( $m ) == 3 ) {
1659 # the first ]] closes the inner link, the second the image
1661 $text .= "[[{$m[0]}]]{$m[1]}";
1664 } elseif ( count( $m ) == 2 ) {
1665 #if there's exactly one ]] that's fine, we'll keep looking
1666 $text .= "[[{$m[0]}]]{$m[1]}";
1668 #if $next_line is invalid too, we need look no further
1669 $text .= '[[' . $next_line;
1674 # we couldn't find the end of this imageLink, so output it raw
1675 #but don't ignore what might be perfectly normal links in the text we've examined
1676 $text = $this->replaceInternalLinks($text);
1677 $s .= "{$prefix}[[$link|$text";
1678 # note: no $trail, because without an end, there *is* no trail
1679 wfProfileOut( "$fname-might_be_img" );
1682 } else { #it's not an image, so output it raw
1683 $s .= "{$prefix}[[$link|$text";
1684 # note: no $trail, because without an end, there *is* no trail
1685 wfProfileOut( "$fname-might_be_img" );
1688 wfProfileOut( "$fname-might_be_img" );
1691 $wasblank = ( '' == $text );
1692 if( $wasblank ) $text = $link;
1694 # Link not escaped by : , create the various objects
1698 wfProfileIn( "$fname-interwiki" );
1699 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1700 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1701 $s = rtrim($s . $prefix);
1702 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1703 wfProfileOut( "$fname-interwiki" );
1706 wfProfileOut( "$fname-interwiki" );
1708 if ( $ns == NS_IMAGE
) {
1709 wfProfileIn( "$fname-image" );
1710 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1711 # recursively parse links inside the image caption
1712 # actually, this will parse them in any other parameters, too,
1713 # but it might be hard to fix that, and it doesn't matter ATM
1714 $text = $this->replaceExternalLinks($text);
1715 $text = $this->replaceInternalLinks($text);
1717 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1718 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1719 $this->mOutput
->addImage( $nt->getDBkey() );
1721 wfProfileOut( "$fname-image" );
1724 # We still need to record the image's presence on the page
1725 $this->mOutput
->addImage( $nt->getDBkey() );
1727 wfProfileOut( "$fname-image" );
1731 if ( $ns == NS_CATEGORY
) {
1732 wfProfileIn( "$fname-category" );
1733 $s = rtrim($s . "\n"); # bug 87
1736 $sortkey = $this->getDefaultSort();
1740 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1741 $sortkey = str_replace( "\n", '', $sortkey );
1742 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1743 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1746 * Strip the whitespace Category links produce, see bug 87
1747 * @todo We might want to use trim($tmp, "\n") here.
1749 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1751 wfProfileOut( "$fname-category" );
1756 # Self-link checking
1757 if( $nt->getFragment() === '' ) {
1758 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1759 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1764 # Special and Media are pseudo-namespaces; no pages actually exist in them
1765 if( $ns == NS_MEDIA
) {
1766 $link = $sk->makeMediaLinkObj( $nt, $text );
1767 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1768 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1771 } elseif( $ns == NS_SPECIAL
) {
1772 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1773 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1775 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1778 } elseif( $ns == NS_IMAGE
) {
1779 $img = wfFindFile( $nt );
1781 // Force a blue link if the file exists; may be a remote
1782 // upload on the shared repository, and we want to see its
1783 // auto-generated page.
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1785 $this->mOutput
->addLink( $nt );
1789 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1791 wfProfileOut( $fname );
1796 * Make a link placeholder. The text returned can be later resolved to a real link with
1797 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1798 * parsing of interwiki links, and secondly to allow all existence checks and
1799 * article length checks (for stub links) to be bundled into a single query.
1802 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1803 wfProfileIn( __METHOD__
);
1804 if ( ! is_object($nt) ) {
1806 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1808 # Separate the link trail from the rest of the link
1809 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1811 if ( $nt->isExternal() ) {
1812 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1813 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1814 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1816 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1817 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1818 $this->mLinkHolders
['queries'][] = $query;
1819 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1820 $this->mLinkHolders
['titles'][] = $nt;
1822 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1825 wfProfileOut( __METHOD__
);
1830 * Render a forced-blue link inline; protect against double expansion of
1831 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1832 * Since this little disaster has to split off the trail text to avoid
1833 * breaking URLs in the following text without breaking trails on the
1834 * wiki links, it's been made into a horrible function.
1837 * @param string $text
1838 * @param string $query
1839 * @param string $trail
1840 * @param string $prefix
1841 * @return string HTML-wikitext mix oh yuck
1843 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1844 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1845 $sk = $this->mOptions
->getSkin();
1846 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1847 return $this->armorLinks( $link ) . $trail;
1851 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1852 * going to go through further parsing steps before inline URL expansion.
1854 * In particular this is important when using action=render, which causes
1855 * full URLs to be included.
1857 * Oh man I hate our multi-layer parser!
1859 * @param string more-or-less HTML
1860 * @return string less-or-more HTML with NOPARSE bits
1862 function armorLinks( $text ) {
1863 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1864 "{$this->mUniqPrefix}NOPARSE$1", $text );
1868 * Return true if subpage links should be expanded on this page.
1871 function areSubpagesAllowed() {
1872 # Some namespaces don't allow subpages
1873 global $wgNamespacesWithSubpages;
1874 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1878 * Handle link to subpage if necessary
1879 * @param string $target the source of the link
1880 * @param string &$text the link text, modified as necessary
1881 * @return string the full name of the link
1884 function maybeDoSubpageLink($target, &$text) {
1887 # :Foobar -- override special treatment of prefix (images, language links)
1888 # /Foobar -- convert to CurrentPage/Foobar
1889 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1890 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1891 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1893 $fname = 'Parser::maybeDoSubpageLink';
1894 wfProfileIn( $fname );
1895 $ret = $target; # default return value is no change
1897 # Some namespaces don't allow subpages,
1898 # so only perform processing if subpages are allowed
1899 if( $this->areSubpagesAllowed() ) {
1900 $hash = strpos( $target, '#' );
1901 if( $hash !== false ) {
1902 $suffix = substr( $target, $hash );
1903 $target = substr( $target, 0, $hash );
1908 $target = trim( $target );
1909 # Look at the first character
1910 if( $target != '' && $target{0} == '/' ) {
1911 # / at end means we don't want the slash to be shown
1913 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1914 if( $trailingSlashes ) {
1915 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1917 $noslash = substr( $target, 1 );
1920 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1921 if( '' === $text ) {
1922 $text = $target . $suffix;
1923 } # this might be changed for ugliness reasons
1925 # check for .. subpage backlinks
1927 $nodotdot = $target;
1928 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1930 $nodotdot = substr( $nodotdot, 3 );
1932 if($dotdotcount > 0) {
1933 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1934 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1935 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1936 # / at the end means don't show full path
1937 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1938 $nodotdot = substr( $nodotdot, 0, -1 );
1939 if( '' === $text ) {
1940 $text = $nodotdot . $suffix;
1943 $nodotdot = trim( $nodotdot );
1944 if( $nodotdot != '' ) {
1945 $ret .= '/' . $nodotdot;
1953 wfProfileOut( $fname );
1958 * Used by doBlockLevels()
1961 /* private */ function closeParagraph() {
1963 if ( '' != $this->mLastSection
) {
1964 $result = '</' . $this->mLastSection
. ">\n";
1966 $this->mInPre
= false;
1967 $this->mLastSection
= '';
1970 # getCommon() returns the length of the longest common substring
1971 # of both arguments, starting at the beginning of both.
1973 /* private */ function getCommon( $st1, $st2 ) {
1974 $fl = strlen( $st1 );
1975 $shorter = strlen( $st2 );
1976 if ( $fl < $shorter ) { $shorter = $fl; }
1978 for ( $i = 0; $i < $shorter; ++
$i ) {
1979 if ( $st1{$i} != $st2{$i} ) { break; }
1983 # These next three functions open, continue, and close the list
1984 # element appropriate to the prefix character passed into them.
1986 /* private */ function openList( $char ) {
1987 $result = $this->closeParagraph();
1989 if ( '*' == $char ) { $result .= '<ul><li>'; }
1990 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1991 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1992 else if ( ';' == $char ) {
1993 $result .= '<dl><dt>';
1994 $this->mDTopen
= true;
1996 else { $result = '<!-- ERR 1 -->'; }
2001 /* private */ function nextItem( $char ) {
2002 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2003 else if ( ':' == $char ||
';' == $char ) {
2005 if ( $this->mDTopen
) { $close = '</dt>'; }
2006 if ( ';' == $char ) {
2007 $this->mDTopen
= true;
2008 return $close . '<dt>';
2010 $this->mDTopen
= false;
2011 return $close . '<dd>';
2014 return '<!-- ERR 2 -->';
2017 /* private */ function closeList( $char ) {
2018 if ( '*' == $char ) { $text = '</li></ul>'; }
2019 else if ( '#' == $char ) { $text = '</li></ol>'; }
2020 else if ( ':' == $char ) {
2021 if ( $this->mDTopen
) {
2022 $this->mDTopen
= false;
2023 $text = '</dt></dl>';
2025 $text = '</dd></dl>';
2028 else { return '<!-- ERR 3 -->'; }
2034 * Make lists from lines starting with ':', '*', '#', etc.
2037 * @return string the lists rendered as HTML
2039 function doBlockLevels( $text, $linestart ) {
2040 $fname = 'Parser::doBlockLevels';
2041 wfProfileIn( $fname );
2043 # Parsing through the text line by line. The main thing
2044 # happening here is handling of block-level elements p, pre,
2045 # and making lists from lines starting with * # : etc.
2047 $textLines = explode( "\n", $text );
2049 $lastPrefix = $output = '';
2050 $this->mDTopen
= $inBlockElem = false;
2052 $paragraphStack = false;
2054 if ( !$linestart ) {
2055 $output .= array_shift( $textLines );
2057 foreach ( $textLines as $oLine ) {
2058 $lastPrefixLength = strlen( $lastPrefix );
2059 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2060 $preOpenMatch = preg_match('/<pre/i', $oLine );
2061 if ( !$this->mInPre
) {
2062 # Multiple prefixes may abut each other for nested lists.
2063 $prefixLength = strspn( $oLine, '*#:;' );
2064 $pref = substr( $oLine, 0, $prefixLength );
2067 $pref2 = str_replace( ';', ':', $pref );
2068 $t = substr( $oLine, $prefixLength );
2069 $this->mInPre
= !empty($preOpenMatch);
2071 # Don't interpret any other prefixes in preformatted text
2073 $pref = $pref2 = '';
2078 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2079 # Same as the last item, so no need to deal with nesting or opening stuff
2080 $output .= $this->nextItem( substr( $pref, -1 ) );
2081 $paragraphStack = false;
2083 if ( substr( $pref, -1 ) == ';') {
2084 # The one nasty exception: definition lists work like this:
2085 # ; title : definition text
2086 # So we check for : in the remainder text to split up the
2087 # title and definition, without b0rking links.
2089 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2091 $output .= $term . $this->nextItem( ':' );
2094 } elseif( $prefixLength ||
$lastPrefixLength ) {
2095 # Either open or close a level...
2096 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2097 $paragraphStack = false;
2099 while( $commonPrefixLength < $lastPrefixLength ) {
2100 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2101 --$lastPrefixLength;
2103 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2104 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2106 while ( $prefixLength > $commonPrefixLength ) {
2107 $char = substr( $pref, $commonPrefixLength, 1 );
2108 $output .= $this->openList( $char );
2110 if ( ';' == $char ) {
2111 # FIXME: This is dupe of code above
2112 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2114 $output .= $term . $this->nextItem( ':' );
2117 ++
$commonPrefixLength;
2119 $lastPrefix = $pref2;
2121 if( 0 == $prefixLength ) {
2122 wfProfileIn( "$fname-paragraph" );
2123 # No prefix (not in list)--go to paragraph mode
2124 // XXX: use a stack for nestable elements like span, table and div
2125 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2126 $closematch = preg_match(
2127 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2128 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2129 if ( $openmatch or $closematch ) {
2130 $paragraphStack = false;
2131 #Â TODO bug 5718: paragraph closed
2132 $output .= $this->closeParagraph();
2133 if ( $preOpenMatch and !$preCloseMatch ) {
2134 $this->mInPre
= true;
2136 if ( $closematch ) {
2137 $inBlockElem = false;
2139 $inBlockElem = true;
2141 } else if ( !$inBlockElem && !$this->mInPre
) {
2142 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2144 if ($this->mLastSection
!= 'pre') {
2145 $paragraphStack = false;
2146 $output .= $this->closeParagraph().'<pre>';
2147 $this->mLastSection
= 'pre';
2149 $t = substr( $t, 1 );
2152 if ( '' == trim($t) ) {
2153 if ( $paragraphStack ) {
2154 $output .= $paragraphStack.'<br />';
2155 $paragraphStack = false;
2156 $this->mLastSection
= 'p';
2158 if ($this->mLastSection
!= 'p' ) {
2159 $output .= $this->closeParagraph();
2160 $this->mLastSection
= '';
2161 $paragraphStack = '<p>';
2163 $paragraphStack = '</p><p>';
2167 if ( $paragraphStack ) {
2168 $output .= $paragraphStack;
2169 $paragraphStack = false;
2170 $this->mLastSection
= 'p';
2171 } else if ($this->mLastSection
!= 'p') {
2172 $output .= $this->closeParagraph().'<p>';
2173 $this->mLastSection
= 'p';
2178 wfProfileOut( "$fname-paragraph" );
2180 // somewhere above we forget to get out of pre block (bug 785)
2181 if($preCloseMatch && $this->mInPre
) {
2182 $this->mInPre
= false;
2184 if ($paragraphStack === false) {
2188 while ( $prefixLength ) {
2189 $output .= $this->closeList( $pref2{$prefixLength-1} );
2192 if ( '' != $this->mLastSection
) {
2193 $output .= '</' . $this->mLastSection
. '>';
2194 $this->mLastSection
= '';
2197 wfProfileOut( $fname );
2202 * Split up a string on ':', ignoring any occurences inside tags
2203 * to prevent illegal overlapping.
2204 * @param string $str the string to split
2205 * @param string &$before set to everything before the ':'
2206 * @param string &$after set to everything after the ':'
2207 * return string the position of the ':', or false if none found
2209 function findColonNoLinks($str, &$before, &$after) {
2210 $fname = 'Parser::findColonNoLinks';
2211 wfProfileIn( $fname );
2213 $pos = strpos( $str, ':' );
2214 if( $pos === false ) {
2216 wfProfileOut( $fname );
2220 $lt = strpos( $str, '<' );
2221 if( $lt === false ||
$lt > $pos ) {
2222 // Easy; no tag nesting to worry about
2223 $before = substr( $str, 0, $pos );
2224 $after = substr( $str, $pos+
1 );
2225 wfProfileOut( $fname );
2229 // Ugly state machine to walk through avoiding tags.
2230 $state = self
::COLON_STATE_TEXT
;
2232 $len = strlen( $str );
2233 for( $i = 0; $i < $len; $i++
) {
2237 // (Using the number is a performance hack for common cases)
2238 case 0: // self::COLON_STATE_TEXT:
2241 // Could be either a <start> tag or an </end> tag
2242 $state = self
::COLON_STATE_TAGSTART
;
2247 $before = substr( $str, 0, $i );
2248 $after = substr( $str, $i +
1 );
2249 wfProfileOut( $fname );
2252 // Embedded in a tag; don't break it.
2255 // Skip ahead looking for something interesting
2256 $colon = strpos( $str, ':', $i );
2257 if( $colon === false ) {
2258 // Nothing else interesting
2259 wfProfileOut( $fname );
2262 $lt = strpos( $str, '<', $i );
2263 if( $stack === 0 ) {
2264 if( $lt === false ||
$colon < $lt ) {
2266 $before = substr( $str, 0, $colon );
2267 $after = substr( $str, $colon +
1 );
2268 wfProfileOut( $fname );
2272 if( $lt === false ) {
2273 // Nothing else interesting to find; abort!
2274 // We're nested, but there's no close tags left. Abort!
2277 // Skip ahead to next tag start
2279 $state = self
::COLON_STATE_TAGSTART
;
2282 case 1: // self::COLON_STATE_TAG:
2287 $state = self
::COLON_STATE_TEXT
;
2290 // Slash may be followed by >?
2291 $state = self
::COLON_STATE_TAGSLASH
;
2297 case 2: // self::COLON_STATE_TAGSTART:
2300 $state = self
::COLON_STATE_CLOSETAG
;
2303 $state = self
::COLON_STATE_COMMENT
;
2306 // Illegal early close? This shouldn't happen D:
2307 $state = self
::COLON_STATE_TEXT
;
2310 $state = self
::COLON_STATE_TAG
;
2313 case 3: // self::COLON_STATE_CLOSETAG:
2318 wfDebug( "Invalid input in $fname; too many close tags\n" );
2319 wfProfileOut( $fname );
2322 $state = self
::COLON_STATE_TEXT
;
2325 case self
::COLON_STATE_TAGSLASH
:
2327 // Yes, a self-closed tag <blah/>
2328 $state = self
::COLON_STATE_TEXT
;
2330 // Probably we're jumping the gun, and this is an attribute
2331 $state = self
::COLON_STATE_TAG
;
2334 case 5: // self::COLON_STATE_COMMENT:
2336 $state = self
::COLON_STATE_COMMENTDASH
;
2339 case self
::COLON_STATE_COMMENTDASH
:
2341 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2343 $state = self
::COLON_STATE_COMMENT
;
2346 case self
::COLON_STATE_COMMENTDASHDASH
:
2348 $state = self
::COLON_STATE_TEXT
;
2350 $state = self
::COLON_STATE_COMMENT
;
2354 throw new MWException( "State machine error in $fname" );
2358 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2361 wfProfileOut( $fname );
2366 * Return value of a magic variable (like PAGENAME)
2370 function getVariableValue( $index ) {
2371 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2374 * Some of these require message or data lookups and can be
2375 * expensive to check many times.
2377 static $varCache = array();
2378 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2379 if ( isset( $varCache[$index] ) ) {
2380 return $varCache[$index];
2385 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2388 global $wgLocaltimezone;
2389 if ( isset( $wgLocaltimezone ) ) {
2390 $oldtz = getenv( 'TZ' );
2391 putenv( 'TZ='.$wgLocaltimezone );
2394 wfSuppressWarnings(); // E_STRICT system time bitching
2395 $localTimestamp = date( 'YmdHis', $ts );
2396 $localMonth = date( 'm', $ts );
2397 $localMonthName = date( 'n', $ts );
2398 $localDay = date( 'j', $ts );
2399 $localDay2 = date( 'd', $ts );
2400 $localDayOfWeek = date( 'w', $ts );
2401 $localWeek = date( 'W', $ts );
2402 $localYear = date( 'Y', $ts );
2403 $localHour = date( 'H', $ts );
2404 if ( isset( $wgLocaltimezone ) ) {
2405 putenv( 'TZ='.$oldtz );
2407 wfRestoreWarnings();
2410 case 'currentmonth':
2411 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2412 case 'currentmonthname':
2413 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2414 case 'currentmonthnamegen':
2415 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2416 case 'currentmonthabbrev':
2417 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2419 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2421 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2423 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2424 case 'localmonthname':
2425 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2426 case 'localmonthnamegen':
2427 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2428 case 'localmonthabbrev':
2429 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2431 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2433 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2435 return wfEscapeWikiText( $this->mTitle
->getText() );
2437 return $this->mTitle
->getPartialURL();
2438 case 'fullpagename':
2439 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2440 case 'fullpagenamee':
2441 return $this->mTitle
->getPrefixedURL();
2443 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2444 case 'subpagenamee':
2445 return $this->mTitle
->getSubpageUrlForm();
2446 case 'basepagename':
2447 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2448 case 'basepagenamee':
2449 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2450 case 'talkpagename':
2451 if( $this->mTitle
->canTalk() ) {
2452 $talkPage = $this->mTitle
->getTalkPage();
2453 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2457 case 'talkpagenamee':
2458 if( $this->mTitle
->canTalk() ) {
2459 $talkPage = $this->mTitle
->getTalkPage();
2460 return $talkPage->getPrefixedUrl();
2464 case 'subjectpagename':
2465 $subjPage = $this->mTitle
->getSubjectPage();
2466 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2467 case 'subjectpagenamee':
2468 $subjPage = $this->mTitle
->getSubjectPage();
2469 return $subjPage->getPrefixedUrl();
2471 // Let the edit saving system know we should parse the page
2472 // *after* a revision ID has been assigned.
2473 $this->mOutput
->setFlag( 'vary-revision' );
2474 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2475 return $this->mRevisionId
;
2477 // Let the edit saving system know we should parse the page
2478 // *after* a revision ID has been assigned. This is for null edits.
2479 $this->mOutput
->setFlag( 'vary-revision' );
2480 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2481 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2482 case 'revisionday2':
2483 // Let the edit saving system know we should parse the page
2484 // *after* a revision ID has been assigned. This is for null edits.
2485 $this->mOutput
->setFlag( 'vary-revision' );
2486 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2487 return substr( $this->getRevisionTimestamp(), 6, 2 );
2488 case 'revisionmonth':
2489 // Let the edit saving system know we should parse the page
2490 // *after* a revision ID has been assigned. This is for null edits.
2491 $this->mOutput
->setFlag( 'vary-revision' );
2492 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2493 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2494 case 'revisionyear':
2495 // Let the edit saving system know we should parse the page
2496 // *after* a revision ID has been assigned. This is for null edits.
2497 $this->mOutput
->setFlag( 'vary-revision' );
2498 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2499 return substr( $this->getRevisionTimestamp(), 0, 4 );
2500 case 'revisiontimestamp':
2501 // Let the edit saving system know we should parse the page
2502 // *after* a revision ID has been assigned. This is for null edits.
2503 $this->mOutput
->setFlag( 'vary-revision' );
2504 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2505 return $this->getRevisionTimestamp();
2507 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2509 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2511 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2513 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2514 case 'subjectspace':
2515 return $this->mTitle
->getSubjectNsText();
2516 case 'subjectspacee':
2517 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2518 case 'currentdayname':
2519 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2521 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2523 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2525 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2527 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2528 // int to remove the padding
2529 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2531 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2532 case 'localdayname':
2533 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2535 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2537 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2539 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2541 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2542 // int to remove the padding
2543 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2545 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2546 case 'numberofarticles':
2547 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2548 case 'numberoffiles':
2549 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2550 case 'numberofusers':
2551 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2552 case 'numberofpages':
2553 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2554 case 'numberofadmins':
2555 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2556 case 'numberofedits':
2557 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2558 case 'currenttimestamp':
2559 return $varCache[$index] = wfTimestampNow();
2560 case 'localtimestamp':
2561 return $varCache[$index] = $localTimestamp;
2562 case 'currentversion':
2563 return $varCache[$index] = SpecialVersion
::getVersion();
2569 return $wgServerName;
2571 return $wgScriptPath;
2572 case 'directionmark':
2573 return $wgContLang->getDirMark();
2574 case 'contentlanguage':
2575 global $wgContLanguageCode;
2576 return $wgContLanguageCode;
2579 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2587 * initialise the magic variables (like CURRENTMONTHNAME)
2591 function initialiseVariables() {
2592 $fname = 'Parser::initialiseVariables';
2593 wfProfileIn( $fname );
2594 $variableIDs = MagicWord
::getVariableIDs();
2596 $this->mVariables
= new MagicWordArray( $variableIDs );
2597 wfProfileOut( $fname );
2601 * Preprocess some wikitext and return the document tree.
2602 * This is the ghost of replace_variables().
2604 * @param string $text The text to parse
2605 * @param integer flags Bitwise combination of:
2606 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2607 * included. Default is to assume a direct page view.
2609 * The generated DOM tree must depend only on the input text and the flags.
2610 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2612 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2613 * change in the DOM tree for a given text, must be passed through the section identifier
2614 * in the section edit link and thus back to extractSections().
2616 * The output of this function is currently only cached in process memory, but a persistent
2617 * cache may be implemented at a later date which takes further advantage of these strict
2618 * dependency requirements.
2622 function preprocessToDom ( $text, $flags = 0 ) {
2623 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2628 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2630 public static function splitWhitespace( $s ) {
2631 $ltrimmed = ltrim( $s );
2632 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2633 $trimmed = rtrim( $ltrimmed );
2634 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2636 $w2 = substr( $ltrimmed, -$diff );
2640 return array( $w1, $trimmed, $w2 );
2644 * Replace magic variables, templates, and template arguments
2645 * with the appropriate text. Templates are substituted recursively,
2646 * taking care to avoid infinite loops.
2648 * Note that the substitution depends on value of $mOutputType:
2649 * self::OT_WIKI: only {{subst:}} templates
2650 * self::OT_PREPROCESS: templates but not extension tags
2651 * self::OT_HTML: all templates and extension tags
2653 * @param string $tex The text to transform
2654 * @param PPFrame $frame Object describing the arguments passed to the template
2655 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2658 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2659 # Prevent too big inclusions
2660 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2664 $fname = __METHOD__
;
2665 wfProfileIn( $fname );
2667 if ( $frame === false ) {
2668 $frame = $this->getPreprocessor()->newFrame();
2669 } elseif ( !( $frame instanceof PPFrame
) ) {
2670 throw new MWException( __METHOD__
. ' called using the old argument format' );
2673 $dom = $this->preprocessToDom( $text );
2674 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2675 $text = $frame->expand( $dom, $flags );
2677 wfProfileOut( $fname );
2681 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2682 static function createAssocArgs( $args ) {
2683 $assocArgs = array();
2685 foreach( $args as $arg ) {
2686 $eqpos = strpos( $arg, '=' );
2687 if ( $eqpos === false ) {
2688 $assocArgs[$index++
] = $arg;
2690 $name = trim( substr( $arg, 0, $eqpos ) );
2691 $value = trim( substr( $arg, $eqpos+
1 ) );
2692 if ( $value === false ) {
2695 if ( $name !== false ) {
2696 $assocArgs[$name] = $value;
2705 * Return the text of a template, after recursively
2706 * replacing any variables or templates within the template.
2708 * @param array $piece The parts of the template
2709 * $piece['title']: the title, i.e. the part before the |
2710 * $piece['parts']: the parameter array
2711 * $piece['lineStart']: whether the brace was at the start of a line
2712 * @param PPFrame The current frame, contains template arguments
2713 * @return string the text of the template
2716 function braceSubstitution( $piece, $frame ) {
2717 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2718 $fname = __METHOD__
;
2719 wfProfileIn( $fname );
2720 wfProfileIn( __METHOD__
.'-setup' );
2723 $found = false; # $text has been filled
2724 $nowiki = false; # wiki markup in $text should be escaped
2725 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2726 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2727 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2728 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2730 # Title object, where $text came from
2733 # $part1 is the bit before the first |, and must contain only title characters.
2734 # Various prefixes will be stripped from it later.
2735 $titleWithSpaces = $frame->expand( $piece['title'] );
2736 $part1 = trim( $titleWithSpaces );
2739 # Original title text preserved for various purposes
2740 $originalTitle = $part1;
2742 # $args is a list of argument nodes, starting from index 0, not including $part1
2743 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2744 wfProfileOut( __METHOD__
.'-setup' );
2747 wfProfileIn( __METHOD__
.'-modifiers' );
2749 $mwSubst =& MagicWord
::get( 'subst' );
2750 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2751 # One of two possibilities is true:
2752 # 1) Found SUBST but not in the PST phase
2753 # 2) Didn't find SUBST and in the PST phase
2754 # In either case, return without further processing
2755 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2762 if ( !$found && $args->getLength() == 0 ) {
2763 $id = $this->mVariables
->matchStartToEnd( $part1 );
2764 if ( $id !== false ) {
2765 $text = $this->getVariableValue( $id );
2766 if (MagicWord
::getCacheTTL($id)>-1)
2767 $this->mOutput
->mContainsOldMagic
= true;
2772 # MSG, MSGNW and RAW
2775 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2776 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2779 # Remove obsolete MSG:
2780 $mwMsg =& MagicWord
::get( 'msg' );
2781 $mwMsg->matchStartAndRemove( $part1 );
2785 $mwRaw =& MagicWord
::get( 'raw' );
2786 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2787 $forceRawInterwiki = true;
2790 wfProfileOut( __METHOD__
.'-modifiers' );
2794 wfProfileIn( __METHOD__
. '-pfunc' );
2796 $colonPos = strpos( $part1, ':' );
2797 if ( $colonPos !== false ) {
2798 # Case sensitive functions
2799 $function = substr( $part1, 0, $colonPos );
2800 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2801 $function = $this->mFunctionSynonyms
[1][$function];
2803 # Case insensitive functions
2804 $function = strtolower( $function );
2805 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2806 $function = $this->mFunctionSynonyms
[0][$function];
2812 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2813 $initialArgs = array( &$this );
2814 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2815 if ( $flags & SFH_OBJECT_ARGS
) {
2816 # Add a frame parameter, and pass the arguments as an array
2817 $allArgs = $initialArgs;
2818 $allArgs[] = $frame;
2819 for ( $i = 0; $i < $args->getLength(); $i++
) {
2820 $funcArgs[] = $args->item( $i );
2822 $allArgs[] = $funcArgs;
2824 # Convert arguments to plain text
2825 for ( $i = 0; $i < $args->getLength(); $i++
) {
2826 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2828 $allArgs = array_merge( $initialArgs, $funcArgs );
2831 $result = call_user_func_array( $callback, $allArgs );
2834 if ( is_array( $result ) ) {
2835 if ( isset( $result[0] ) ) {
2837 unset( $result[0] );
2840 // Extract flags into the local scope
2841 // This allows callers to set flags such as nowiki, found, etc.
2848 wfProfileOut( __METHOD__
. '-pfunc' );
2851 # Finish mangling title and then check for loops.
2852 # Set $title to a Title object and $titleText to the PDBK
2855 # Split the title into page and subpage
2857 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2858 if ($subpage !== '') {
2859 $ns = $this->mTitle
->getNamespace();
2861 $title = Title
::newFromText( $part1, $ns );
2863 $titleText = $title->getPrefixedText();
2864 # Check for language variants if the template is not found
2865 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2866 $wgContLang->findVariantLink($part1, $title);
2868 # Do infinite loop check
2869 if ( !$frame->loopCheck( $title ) ) {
2871 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2872 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2874 # Do recursion depth check
2875 $limit = $this->mOptions
->getMaxTemplateDepth();
2876 if ( $frame->depth
>= $limit ) {
2878 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2883 # Load from database
2884 if ( !$found && $title ) {
2885 wfProfileIn( __METHOD__
. '-loadtpl' );
2886 if ( !$title->isExternal() ) {
2887 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2888 $text = SpecialPage
::capturePath( $title );
2889 if ( is_string( $text ) ) {
2892 $this->disableCache();
2894 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2895 $found = false; //access denied
2896 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2898 list( $text, $title ) = $this->getTemplateDom( $title );
2899 if ( $text !== false ) {
2905 # If the title is valid but undisplayable, make a link to it
2906 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2907 $text = "[[:$titleText]]";
2910 } elseif ( $title->isTrans() ) {
2911 // Interwiki transclusion
2912 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2913 $text = $this->interwikiTransclude( $title, 'render' );
2916 $text = $this->interwikiTransclude( $title, 'raw' );
2917 // Preprocess it like a template
2918 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2923 wfProfileOut( __METHOD__
. '-loadtpl' );
2926 # If we haven't found text to substitute by now, we're done
2927 # Recover the source wikitext and return it
2929 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2930 wfProfileOut( $fname );
2931 return array( 'object' => $text );
2934 # Expand DOM-style return values in a child frame
2935 if ( $isChildObj ) {
2936 # Clean up argument array
2937 $newFrame = $frame->newChild( $args, $title );
2939 if ( $titleText !== false && $newFrame->isEmpty() ) {
2940 # Expansion is eligible for the empty-frame cache
2941 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2942 $text = $this->mTplExpandCache
[$titleText];
2944 $text = $newFrame->expand( $text );
2945 $this->mTplExpandCache
[$titleText] = $text;
2948 # Uncached expansion
2949 $text = $newFrame->expand( $text );
2953 # Replace raw HTML by a placeholder
2954 # Add a blank line preceding, to prevent it from mucking up
2955 # immediately preceding headings
2957 $text = "\n\n" . $this->insertStripItem( $text );
2959 # Escape nowiki-style return values
2960 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2961 $text = wfEscapeWikiText( $text );
2963 # Bug 529: if the template begins with a table or block-level
2964 # element, it should be treated as beginning a new line.
2965 # This behaviour is somewhat controversial.
2966 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2967 $text = "\n" . $text;
2970 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2971 # Error, oversize inclusion
2972 $text = "[[$originalTitle]]" .
2973 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2976 if ( $isLocalObj ) {
2977 $ret = array( 'object' => $text );
2979 $ret = array( 'text' => $text );
2982 wfProfileOut( $fname );
2987 * Get the semi-parsed DOM representation of a template with a given title,
2988 * and its redirect destination title. Cached.
2990 function getTemplateDom( $title ) {
2991 $cacheTitle = $title;
2992 $titleText = $title->getPrefixedDBkey();
2994 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2995 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2996 $title = Title
::makeTitle( $ns, $dbk );
2997 $titleText = $title->getPrefixedDBkey();
2999 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3000 return array( $this->mTplDomCache
[$titleText], $title );
3003 // Cache miss, go to the database
3004 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3006 if ( $text === false ) {
3007 $this->mTplDomCache
[$titleText] = false;
3008 return array( false, $title );
3011 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3012 $this->mTplDomCache
[ $titleText ] = $dom;
3014 if (! $title->equals($cacheTitle)) {
3015 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3016 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3019 return array( $dom, $title );
3023 * Fetch the unparsed text of a template and register a reference to it.
3025 function fetchTemplateAndTitle( $title ) {
3026 $templateCb = $this->mOptions
->getTemplateCallback();
3027 $stuff = call_user_func( $templateCb, $title );
3028 $text = $stuff['text'];
3029 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3030 if ( isset( $stuff['deps'] ) ) {
3031 foreach ( $stuff['deps'] as $dep ) {
3032 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3035 return array($text,$finalTitle);
3038 function fetchTemplate( $title ) {
3039 $rv = $this->fetchTemplateAndTitle($title);
3044 * Static function to get a template
3045 * Can be overridden via ParserOptions::setTemplateCallback().
3047 static function statelessFetchTemplate( $title ) {
3048 $text = $skip = false;
3049 $finalTitle = $title;
3052 // Loop to fetch the article, with up to 1 redirect
3053 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3054 # Give extensions a chance to select the revision instead
3055 $id = false; // Assume current
3056 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3062 'page_id' => $title->getArticleID(),
3066 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3067 $rev_id = $rev ?
$rev->getId() : 0;
3071 'page_id' => $title->getArticleID(),
3072 'rev_id' => $rev_id );
3075 $text = $rev->getText();
3076 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3078 $message = $wgLang->lcfirst( $title->getText() );
3079 $text = wfMsgForContentNoTrans( $message );
3080 if( wfEmptyMsg( $message, $text ) ) {
3087 if ( $text === false ) {
3091 $finalTitle = $title;
3092 $title = Title
::newFromRedirect( $text );
3096 'finalTitle' => $finalTitle,
3101 * Transclude an interwiki link.
3103 function interwikiTransclude( $title, $action ) {
3104 global $wgEnableScaryTranscluding;
3106 if (!$wgEnableScaryTranscluding)
3107 return wfMsg('scarytranscludedisabled');
3109 $url = $title->getFullUrl( "action=$action" );
3111 if (strlen($url) > 255)
3112 return wfMsg('scarytranscludetoolong');
3113 return $this->fetchScaryTemplateMaybeFromCache($url);
3116 function fetchScaryTemplateMaybeFromCache($url) {
3117 global $wgTranscludeCacheExpiry;
3118 $dbr = wfGetDB(DB_SLAVE
);
3119 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3120 array('tc_url' => $url));
3122 $time = $obj->tc_time
;
3123 $text = $obj->tc_contents
;
3124 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3129 $text = Http
::get($url);
3131 return wfMsg('scarytranscludefailed', $url);
3133 $dbw = wfGetDB(DB_MASTER
);
3134 $dbw->replace('transcache', array('tc_url'), array(
3136 'tc_time' => time(),
3137 'tc_contents' => $text));
3143 * Triple brace replacement -- used for template arguments
3146 function argSubstitution( $piece, $frame ) {
3147 wfProfileIn( __METHOD__
);
3150 $parts = $piece['parts'];
3151 $nameWithSpaces = $frame->expand( $piece['title'] );
3152 $argName = trim( $nameWithSpaces );
3154 $text = $frame->getArgument( $argName );
3155 if ( $text === false && ( $this->ot
['html'] ||
$this->ot
['pre'] ) && $parts->getLength() > 0 ) {
3156 # No match in frame, use the supplied default
3157 $object = $parts->item( 0 )->getChildren();
3159 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3160 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3163 if ( $text === false && $object === false ) {
3165 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3167 if ( $error !== false ) {
3170 if ( $object !== false ) {
3171 $ret = array( 'object' => $object );
3173 $ret = array( 'text' => $text );
3176 wfProfileOut( __METHOD__
);
3181 * Return the text to be used for a given extension tag.
3182 * This is the ghost of strip().
3184 * @param array $params Associative array of parameters:
3185 * name PPNode for the tag name
3186 * attr PPNode for unparsed text where tag attributes are thought to be
3187 * attributes Optional associative array of parsed attributes
3188 * inner Contents of extension element
3189 * noClose Original text did not have a close tag
3190 * @param PPFrame $frame
3192 function extensionSubstitution( $params, $frame ) {
3193 global $wgRawHtml, $wgContLang;
3196 $name = $frame->expand( $params['name'] );
3197 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3198 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3200 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
3202 if ( $this->ot
['html'] ) {
3203 $name = strtolower( $name );
3205 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3206 if ( isset( $params['attributes'] ) ) {
3207 $attributes = $attributes +
$params['attributes'];
3215 throw new MWException( '<html> extension tag encountered unexpectedly' );
3218 $output = Xml
::escapeTagsOnly( $content );
3221 $output = $wgContLang->armourMath(
3222 MathRenderer
::renderMath( $content, $attributes ) );
3225 $output = $this->renderImageGallery( $content, $attributes );
3228 if( isset( $this->mTagHooks
[$name] ) ) {
3229 $output = call_user_func_array( $this->mTagHooks
[$name],
3230 array( $content, $attributes, $this ) );
3232 throw new MWException( "Invalid call hook $name" );
3236 if ( is_null( $attrText ) ) {
3239 if ( isset( $params['attributes'] ) ) {
3240 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3241 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3242 htmlspecialchars( $attrValue ) . '"';
3245 if ( $content === null ) {
3246 $output = "<$name$attrText/>";
3248 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3249 $output = "<$name$attrText>$content$close";
3253 if ( $name == 'html' ||
$name == 'nowiki' ) {
3254 $this->mStripState
->nowiki
->setPair( $marker, $output );
3256 $this->mStripState
->general
->setPair( $marker, $output );
3262 * Increment an include size counter
3264 * @param string $type The type of expansion
3265 * @param integer $size The size of the text
3266 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3268 function incrementIncludeSize( $type, $size ) {
3269 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3272 $this->mIncludeSizes
[$type] +
= $size;
3278 * Detect __NOGALLERY__ magic word and set a placeholder
3280 function stripNoGallery( &$text ) {
3281 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3283 $mw = MagicWord
::get( 'nogallery' );
3284 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3288 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3289 * placeholder that will then be replaced by the real TOC in
3290 * ->formatHeadings, this works because at this points real
3291 * comments will have already been discarded by the sanitizer.
3293 * Any additional __TOC__ magic words left over will be discarded
3294 * as there can only be one TOC on the page.
3296 function stripToc( $text ) {
3297 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3299 $mw = MagicWord
::get( 'notoc' );
3300 if( $mw->matchAndRemove( $text ) ) {
3301 $this->mShowToc
= false;
3304 $mw = MagicWord
::get( 'toc' );
3305 if( $mw->match( $text ) ) {
3306 $this->mShowToc
= true;
3307 $this->mForceTocPosition
= true;
3309 // Set a placeholder. At the end we'll fill it in with the TOC.
3310 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3312 // Only keep the first one.
3313 $text = $mw->replace( '', $text );
3319 * This function accomplishes several tasks:
3320 * 1) Auto-number headings if that option is enabled
3321 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3322 * 3) Add a Table of contents on the top for users who have enabled the option
3323 * 4) Auto-anchor headings
3325 * It loops through all headlines, collects the necessary data, then splits up the
3326 * string and re-inserts the newly formatted headlines.
3328 * @param string $text
3329 * @param boolean $isMain
3332 function formatHeadings( $text, $isMain=true ) {
3333 global $wgMaxTocLevel, $wgContLang;
3335 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3336 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3339 $showEditLink = $this->mOptions
->getEditSection();
3342 # Inhibit editsection links if requested in the page
3343 $esw =& MagicWord
::get( 'noeditsection' );
3344 if( $esw->matchAndRemove( $text ) ) {
3348 # Get all headlines for numbering them and adding funky stuff like [edit]
3349 # links - this is for later, but we need the number of headlines right now
3351 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3353 # if there are fewer than 4 headlines in the article, do not show TOC
3354 # unless it's been explicitly enabled.
3355 $enoughToc = $this->mShowToc
&&
3356 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3358 # Allow user to stipulate that a page should have a "new section"
3359 # link added via __NEWSECTIONLINK__
3360 $mw =& MagicWord
::get( 'newsectionlink' );
3361 if( $mw->matchAndRemove( $text ) )
3362 $this->mOutput
->setNewSection( true );
3364 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3365 # override above conditions and always show TOC above first header
3366 $mw =& MagicWord
::get( 'forcetoc' );
3367 if ($mw->matchAndRemove( $text ) ) {
3368 $this->mShowToc
= true;
3372 # We need this to perform operations on the HTML
3373 $sk = $this->mOptions
->getSkin();
3379 # Ugh .. the TOC should have neat indentation levels which can be
3380 # passed to the skin functions. These are determined here
3384 $sublevelCount = array();
3385 $levelCount = array();
3391 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3392 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3395 foreach( $matches[3] as $headline ) {
3396 $isTemplate = false;
3398 $sectionIndex = false;
3400 $markerMatches = array();
3401 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3402 $serial = $markerMatches[1];
3403 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3404 $isTemplate = ($titleText != $baseTitleText);
3405 $headline = preg_replace("/^$markerRegex/", "", $headline);
3409 $prevlevel = $level;
3410 $prevtoclevel = $toclevel;
3412 $level = $matches[1][$headlineCount];
3414 if( $doNumberHeadings ||
$enoughToc ) {
3416 if ( $level > $prevlevel ) {
3417 # Increase TOC level
3419 $sublevelCount[$toclevel] = 0;
3420 if( $toclevel<$wgMaxTocLevel ) {
3421 $prevtoclevel = $toclevel;
3422 $toc .= $sk->tocIndent();
3426 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3427 # Decrease TOC level, find level to jump to
3429 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3430 # Can only go down to level 1
3433 for ($i = $toclevel; $i > 0; $i--) {
3434 if ( $levelCount[$i] == $level ) {
3435 # Found last matching level
3439 elseif ( $levelCount[$i] < $level ) {
3440 # Found first matching level below current level
3446 if( $toclevel<$wgMaxTocLevel ) {
3447 if($prevtoclevel < $wgMaxTocLevel) {
3448 # Unindent only if the previous toc level was shown :p
3449 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3451 $toc .= $sk->tocLineEnd();
3456 # No change in level, end TOC line
3457 if( $toclevel<$wgMaxTocLevel ) {
3458 $toc .= $sk->tocLineEnd();
3462 $levelCount[$toclevel] = $level;
3464 # count number of headlines for each level
3465 @$sublevelCount[$toclevel]++
;
3467 for( $i = 1; $i <= $toclevel; $i++
) {
3468 if( !empty( $sublevelCount[$i] ) ) {
3472 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3478 # The safe header is a version of the header text safe to use for links
3479 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3480 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3482 # Remove link placeholders by the link text.
3483 # <!--LINK number-->
3485 # link text with suffix
3486 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3487 "\$this->mLinkHolders['texts'][\$1]",
3489 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3490 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3493 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3494 $tocline = preg_replace(
3495 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3499 $tocline = trim( $tocline );
3501 # For the anchor, strip out HTML-y stuff period
3502 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3503 $safeHeadline = trim( $safeHeadline );
3505 # Save headline for section edit hint before it's escaped
3506 $headlineHint = $safeHeadline;
3507 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3508 $refers[$headlineCount] = $safeHeadline;
3510 # count how many in assoc. array so we can track dupes in anchors
3511 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3512 $refcount[$headlineCount] = $refers[$safeHeadline];
3514 # Don't number the heading if it is the only one (looks silly)
3515 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3516 # the two are different if the line contains a link
3517 $headline=$numbering . ' ' . $headline;
3520 # Create the anchor for linking from the TOC to the section
3521 $anchor = $safeHeadline;
3522 if($refcount[$headlineCount] > 1 ) {
3523 $anchor .= '_' . $refcount[$headlineCount];
3525 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3526 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3527 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3529 # give headline the correct <h#> tag
3530 if( $showEditLink && $sectionIndex !== false ) {
3532 # Put a T flag in the section identifier, to indicate to extractSections()
3533 # that sections inside <includeonly> should be counted.
3534 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3536 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3541 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3546 $this->mOutput
->setSections( $tocraw );
3548 # Never ever show TOC if no headers
3549 if( $numVisible < 1 ) {
3554 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3555 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3557 $toc = $sk->tocList( $toc );
3560 # split up and insert constructed headlines
3562 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3565 foreach( $blocks as $block ) {
3566 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3567 # This is the [edit] link that appears for the top block of text when
3568 # section editing is enabled
3570 # Disabled because it broke block formatting
3571 # For example, a bullet point in the top line
3572 # $full .= $sk->editSectionLink(0);
3575 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3576 # Top anchor now in skin
3580 if( !empty( $head[$i] ) ) {
3585 if( $this->mForceTocPosition
) {
3586 return str_replace( '<!--MWTOC-->', $toc, $full );
3593 * Transform wiki markup when saving a page by doing \r\n -> \n
3594 * conversion, substitting signatures, {{subst:}} templates, etc.
3596 * @param string $text the text to transform
3597 * @param Title &$title the Title object for the current article
3598 * @param User &$user the User object describing the current user
3599 * @param ParserOptions $options parsing options
3600 * @param bool $clearState whether to clear the parser state first
3601 * @return string the altered wiki markup
3604 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3605 $this->mOptions
= $options;
3606 $this->setTitle( $title );
3607 $this->setOutputType( self
::OT_WIKI
);
3609 if ( $clearState ) {
3610 $this->clearState();
3616 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3617 $text = $this->pstPass2( $text, $user );
3618 $text = $this->mStripState
->unstripBoth( $text );
3623 * Pre-save transform helper function
3626 function pstPass2( $text, $user ) {
3627 global $wgContLang, $wgLocaltimezone;
3629 /* Note: This is the timestamp saved as hardcoded wikitext to
3630 * the database, we use $wgContLang here in order to give
3631 * everyone the same signature and use the default one rather
3632 * than the one selected in each user's preferences.
3634 if ( isset( $wgLocaltimezone ) ) {
3635 $oldtz = getenv( 'TZ' );
3636 putenv( 'TZ='.$wgLocaltimezone );
3638 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3639 ' (' . date( 'T' ) . ')';
3640 if ( isset( $wgLocaltimezone ) ) {
3641 putenv( 'TZ='.$oldtz );
3644 # Variable replacement
3645 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3646 $text = $this->replaceVariables( $text );
3648 # Strip out <nowiki> etc. added via replaceVariables
3649 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
3652 $sigText = $this->getUserSig( $user );
3653 $text = strtr( $text, array(
3655 '~~~~' => "$sigText $d",
3659 # Context links: [[|name]] and [[name (context)|]]
3661 global $wgLegalTitleChars;
3662 $tc = "[$wgLegalTitleChars]";
3663 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3665 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3666 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3667 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3669 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3670 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3671 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3673 $t = $this->mTitle
->getText();
3675 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3676 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3677 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3678 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3680 # if there's no context, don't bother duplicating the title
3681 $text = preg_replace( $p2, '[[\\1]]', $text );
3684 # Trim trailing whitespace
3685 $text = rtrim( $text );
3691 * Fetch the user's signature text, if any, and normalize to
3692 * validated, ready-to-insert wikitext.
3698 function getUserSig( &$user ) {
3699 global $wgMaxSigChars;
3701 $username = $user->getName();
3702 $nickname = $user->getOption( 'nickname' );
3703 $nickname = $nickname === '' ?
$username : $nickname;
3705 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3706 $nickname = $username;
3707 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3708 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3709 # Sig. might contain markup; validate this
3710 if( $this->validateSig( $nickname ) !== false ) {
3711 # Validated; clean up (if needed) and return it
3712 return $this->cleanSig( $nickname, true );
3714 # Failed to validate; fall back to the default
3715 $nickname = $username;
3716 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3720 // Make sure nickname doesnt get a sig in a sig
3721 $nickname = $this->cleanSigInSig( $nickname );
3723 # If we're still here, make it a link to the user page
3724 $userText = wfEscapeWikiText( $username );
3725 $nickText = wfEscapeWikiText( $nickname );
3726 if ( $user->isAnon() ) {
3727 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3729 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3734 * Check that the user's signature contains no bad XML
3736 * @param string $text
3737 * @return mixed An expanded string, or false if invalid.
3739 function validateSig( $text ) {
3740 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3744 * Clean up signature text
3746 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3747 * 2) Substitute all transclusions
3749 * @param string $text
3750 * @param $parsing Whether we're cleaning (preferences save) or parsing
3751 * @return string Signature text
3753 function cleanSig( $text, $parsing = false ) {
3756 $this->clearState();
3757 $this->setTitle( $wgTitle );
3758 $this->mOptions
= new ParserOptions
;
3759 $this->setOutputType
= self
::OT_PREPROCESS
;
3762 # FIXME: regex doesn't respect extension tags or nowiki
3763 # => Move this logic to braceSubstitution()
3764 $substWord = MagicWord
::get( 'subst' );
3765 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3766 $substText = '{{' . $substWord->getSynonym( 0 );
3768 $text = preg_replace( $substRegex, $substText, $text );
3769 $text = $this->cleanSigInSig( $text );
3770 $dom = $this->preprocessToDom( $text );
3771 $frame = $this->getPreprocessor()->newFrame();
3772 $text = $frame->expand( $dom );
3775 $text = $this->mStripState
->unstripBoth( $text );
3782 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3783 * @param string $text
3784 * @return string Signature text with /~{3,5}/ removed
3786 function cleanSigInSig( $text ) {
3787 $text = preg_replace( '/~{3,5}/', '', $text );
3792 * Set up some variables which are usually set up in parse()
3793 * so that an external function can call some class members with confidence
3796 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3797 $this->setTitle( $title );
3798 $this->mOptions
= $options;
3799 $this->setOutputType( $outputType );
3800 if ( $clearState ) {
3801 $this->clearState();
3806 * Wrapper for preprocess()
3808 * @param string $text the text to preprocess
3809 * @param ParserOptions $options options
3813 function transformMsg( $text, $options ) {
3815 static $executing = false;
3817 $fname = "Parser::transformMsg";
3819 # Guard against infinite recursion
3825 wfProfileIn($fname);
3826 $text = $this->preprocess( $text, $wgTitle, $options );
3829 wfProfileOut($fname);
3834 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3835 * The callback should have the following form:
3836 * function myParserHook( $text, $params, &$parser ) { ... }
3838 * Transform and return $text. Use $parser for any required context, e.g. use
3839 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3843 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3844 * @param mixed $callback The callback function (and object) to use for the tag
3846 * @return The old value of the mTagHooks array associated with the hook
3848 function setHook( $tag, $callback ) {
3849 $tag = strtolower( $tag );
3850 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3851 $this->mTagHooks
[$tag] = $callback;
3852 $this->mStripList
[] = $tag;
3857 function setTransparentTagHook( $tag, $callback ) {
3858 $tag = strtolower( $tag );
3859 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3860 $this->mTransparentTagHooks
[$tag] = $callback;
3866 * Remove all tag hooks
3868 function clearTagHooks() {
3869 $this->mTagHooks
= array();
3870 $this->mStripList
= $this->mDefaultStripList
;
3874 * Create a function, e.g. {{sum:1|2|3}}
3875 * The callback function should have the form:
3876 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3878 * The callback may either return the text result of the function, or an array with the text
3879 * in element 0, and a number of flags in the other elements. The names of the flags are
3880 * specified in the keys. Valid flags are:
3881 * found The text returned is valid, stop processing the template. This
3883 * nowiki Wiki markup in the return value should be escaped
3884 * isHTML The returned text is HTML, armour it against wikitext transformation
3888 * @param string $id The magic word ID
3889 * @param mixed $callback The callback function (and object) to use
3890 * @param integer $flags a combination of the following flags:
3891 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3893 * @return The old callback function for this name, if any
3895 function setFunctionHook( $id, $callback, $flags = 0 ) {
3896 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3897 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3899 # Add to function cache
3900 $mw = MagicWord
::get( $id );
3902 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3904 $synonyms = $mw->getSynonyms();
3905 $sensitive = intval( $mw->isCaseSensitive() );
3907 foreach ( $synonyms as $syn ) {
3909 if ( !$sensitive ) {
3910 $syn = strtolower( $syn );
3913 if ( !( $flags & SFH_NO_HASH
) ) {
3916 # Remove trailing colon
3917 if ( substr( $syn, -1, 1 ) == ':' ) {
3918 $syn = substr( $syn, 0, -1 );
3920 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3926 * Get all registered function hook identifiers
3930 function getFunctionHooks() {
3931 return array_keys( $this->mFunctionHooks
);
3935 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3936 * Placeholders created in Skin::makeLinkObj()
3937 * Returns an array of link CSS classes, indexed by PDBK.
3938 * $options is a bit field, RLH_FOR_UPDATE to select for update
3940 function replaceLinkHolders( &$text, $options = 0 ) {
3944 $fname = 'Parser::replaceLinkHolders';
3945 wfProfileIn( $fname );
3949 $linkcolour_ids = array();
3950 $sk = $this->mOptions
->getSkin();
3951 $linkCache =& LinkCache
::singleton();
3953 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3954 wfProfileIn( $fname.'-check' );
3955 $dbr = wfGetDB( DB_SLAVE
);
3956 $page = $dbr->tableName( 'page' );
3957 $threshold = $wgUser->getOption('stubthreshold');
3960 asort( $this->mLinkHolders
['namespaces'] );
3965 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3967 $title = $this->mLinkHolders
['titles'][$key];
3969 # Skip invalid entries.
3970 # Result will be ugly, but prevents crash.
3971 if ( is_null( $title ) ) {
3974 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3976 # Check if it's a static known link, e.g. interwiki
3977 if ( $title->isAlwaysKnown() ) {
3978 $colours[$pdbk] = '';
3979 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3980 $colours[$pdbk] = '';
3981 $this->mOutput
->addLink( $title, $id );
3982 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3983 $colours[$pdbk] = 'new';
3984 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
3985 $colours[$pdbk] = 'new';
3987 # Not in the link cache, add it to the query
3988 if ( !isset( $current ) ) {
3990 $query = "SELECT page_id, page_namespace, page_title";
3991 if ( $threshold > 0 ) {
3992 $query .= ', page_len, page_is_redirect';
3994 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3995 } elseif ( $current != $ns ) {
3997 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4002 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4007 if ( $options & RLH_FOR_UPDATE
) {
4008 $query .= ' FOR UPDATE';
4011 $res = $dbr->query( $query, $fname );
4013 # Fetch data and form into an associative array
4014 # non-existent = broken
4015 while ( $s = $dbr->fetchObject($res) ) {
4016 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4017 $pdbk = $title->getPrefixedDBkey();
4018 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4019 $this->mOutput
->addLink( $title, $s->page_id
);
4020 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4021 //add id to the extension todolist
4022 $linkcolour_ids[$s->page_id
] = $pdbk;
4024 //pass an array of page_ids to an extension
4025 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4027 wfProfileOut( $fname.'-check' );
4029 # Do a second query for different language variants of links and categories
4030 if($wgContLang->hasVariants()){
4031 $linkBatch = new LinkBatch();
4032 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4033 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4034 $varCategories = array(); // category replacements oldDBkey => newDBkey
4036 $categories = $this->mOutput
->getCategoryLinks();
4038 // Add variants of links to link batch
4039 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4040 $title = $this->mLinkHolders
['titles'][$key];
4041 if ( is_null( $title ) )
4044 $pdbk = $title->getPrefixedDBkey();
4045 $titleText = $title->getText();
4047 // generate all variants of the link title text
4048 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4050 // if link was not found (in first query), add all variants to query
4051 if ( !isset($colours[$pdbk]) ){
4052 foreach($allTextVariants as $textVariant){
4053 if($textVariant != $titleText){
4054 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4055 if(is_null($variantTitle)) continue;
4056 $linkBatch->addObj( $variantTitle );
4057 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4063 // process categories, check if a category exists in some variant
4064 foreach( $categories as $category ){
4065 $variants = $wgContLang->convertLinkToAllVariants($category);
4066 foreach($variants as $variant){
4067 if($variant != $category){
4068 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4069 if(is_null($variantTitle)) continue;
4070 $linkBatch->addObj( $variantTitle );
4071 $categoryMap[$variant] = $category;
4077 if(!$linkBatch->isEmpty()){
4079 $titleClause = $linkBatch->constructSet('page', $dbr);
4081 $variantQuery = "SELECT page_id, page_namespace, page_title";
4082 if ( $threshold > 0 ) {
4083 $variantQuery .= ', page_len, page_is_redirect';
4086 $variantQuery .= " FROM $page WHERE $titleClause";
4087 if ( $options & RLH_FOR_UPDATE
) {
4088 $variantQuery .= ' FOR UPDATE';
4091 $varRes = $dbr->query( $variantQuery, $fname );
4093 // for each found variants, figure out link holders and replace
4094 while ( $s = $dbr->fetchObject($varRes) ) {
4096 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4097 $varPdbk = $variantTitle->getPrefixedDBkey();
4098 $vardbk = $variantTitle->getDBkey();
4100 $holderKeys = array();
4101 if(isset($variantMap[$varPdbk])){
4102 $holderKeys = $variantMap[$varPdbk];
4103 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4104 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4107 // loop over link holders
4108 foreach($holderKeys as $key){
4109 $title = $this->mLinkHolders
['titles'][$key];
4110 if ( is_null( $title ) ) continue;
4112 $pdbk = $title->getPrefixedDBkey();
4114 if(!isset($colours[$pdbk])){
4115 // found link in some of the variants, replace the link holder data
4116 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4117 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4119 // set pdbk and colour
4120 $pdbks[$key] = $varPdbk;
4121 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4122 $linkcolour_ids[$s->page_id
] = $pdbk;
4124 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4127 // check if the object is a variant of a category
4128 if(isset($categoryMap[$vardbk])){
4129 $oldkey = $categoryMap[$vardbk];
4130 if($oldkey != $vardbk)
4131 $varCategories[$oldkey]=$vardbk;
4135 // rebuild the categories in original order (if there are replacements)
4136 if(count($varCategories)>0){
4138 $originalCats = $this->mOutput
->getCategories();
4139 foreach($originalCats as $cat => $sortkey){
4140 // make the replacement
4141 if( array_key_exists($cat,$varCategories) )
4142 $newCats[$varCategories[$cat]] = $sortkey;
4143 else $newCats[$cat] = $sortkey;
4145 $this->mOutput
->setCategoryLinks($newCats);
4150 # Construct search and replace arrays
4151 wfProfileIn( $fname.'-construct' );
4152 $replacePairs = array();
4153 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4154 $pdbk = $pdbks[$key];
4155 $searchkey = "<!--LINK $key-->";
4156 $title = $this->mLinkHolders
['titles'][$key];
4157 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4158 $linkCache->addBadLinkObj( $title );
4159 $colours[$pdbk] = 'new';
4160 $this->mOutput
->addLink( $title, 0 );
4161 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4162 $this->mLinkHolders
['texts'][$key],
4163 $this->mLinkHolders
['queries'][$key] );
4165 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4166 $this->mLinkHolders
['texts'][$key],
4167 $this->mLinkHolders
['queries'][$key] );
4170 $replacer = new HashtableReplacer( $replacePairs, 1 );
4171 wfProfileOut( $fname.'-construct' );
4174 wfProfileIn( $fname.'-replace' );
4175 $text = preg_replace_callback(
4176 '/(<!--LINK .*?-->)/',
4180 wfProfileOut( $fname.'-replace' );
4183 # Now process interwiki link holders
4184 # This is quite a bit simpler than internal links
4185 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4186 wfProfileIn( $fname.'-interwiki' );
4187 # Make interwiki link HTML
4188 $replacePairs = array();
4189 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4190 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4191 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4193 $replacer = new HashtableReplacer( $replacePairs, 1 );
4195 $text = preg_replace_callback(
4196 '/<!--IWLINK (.*?)-->/',
4199 wfProfileOut( $fname.'-interwiki' );
4202 wfProfileOut( $fname );
4207 * Replace <!--LINK--> link placeholders with plain text of links
4208 * (not HTML-formatted).
4209 * @param string $text
4212 function replaceLinkHoldersText( $text ) {
4213 $fname = 'Parser::replaceLinkHoldersText';
4214 wfProfileIn( $fname );
4216 $text = preg_replace_callback(
4217 '/<!--(LINK|IWLINK) (.*?)-->/',
4218 array( &$this, 'replaceLinkHoldersTextCallback' ),
4221 wfProfileOut( $fname );
4226 * @param array $matches
4230 function replaceLinkHoldersTextCallback( $matches ) {
4231 $type = $matches[1];
4233 if( $type == 'LINK' ) {
4234 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4235 return $this->mLinkHolders
['texts'][$key];
4237 } elseif( $type == 'IWLINK' ) {
4238 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4239 return $this->mInterwikiLinkHolders
['texts'][$key];
4246 * Tag hook handler for 'pre'.
4248 function renderPreTag( $text, $attribs ) {
4249 // Backwards-compatibility hack
4250 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4252 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4253 return wfOpenElement( 'pre', $attribs ) .
4254 Xml
::escapeTagsOnly( $content ) .
4259 * Renders an image gallery from a text with one line per image.
4260 * text labels may be given by using |-style alternative text. E.g.
4261 * Image:one.jpg|The number "1"
4262 * Image:tree.jpg|A tree
4263 * given as text will return the HTML of a gallery with two images,
4264 * labeled 'The number "1"' and
4267 function renderImageGallery( $text, $params ) {
4268 $ig = new ImageGallery();
4269 $ig->setContextTitle( $this->mTitle
);
4270 $ig->setShowBytes( false );
4271 $ig->setShowFilename( false );
4272 $ig->setParser( $this );
4273 $ig->setHideBadImages();
4274 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4275 $ig->useSkin( $this->mOptions
->getSkin() );
4276 $ig->mRevisionId
= $this->mRevisionId
;
4278 if( isset( $params['caption'] ) ) {
4279 $caption = $params['caption'];
4280 $caption = htmlspecialchars( $caption );
4281 $caption = $this->replaceInternalLinks( $caption );
4282 $ig->setCaptionHtml( $caption );
4284 if( isset( $params['perrow'] ) ) {
4285 $ig->setPerRow( $params['perrow'] );
4287 if( isset( $params['widths'] ) ) {
4288 $ig->setWidths( $params['widths'] );
4290 if( isset( $params['heights'] ) ) {
4291 $ig->setHeights( $params['heights'] );
4294 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4296 $lines = explode( "\n", $text );
4297 foreach ( $lines as $line ) {
4298 # match lines like these:
4299 # Image:someimage.jpg|This is some image
4301 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4303 if ( count( $matches ) == 0 ) {
4306 $tp = Title
::newFromText( $matches[1] );
4308 if( is_null( $nt ) ) {
4309 # Bogus title. Ignore these so we don't bomb out later.
4312 if ( isset( $matches[3] ) ) {
4313 $label = $matches[3];
4318 $html = $this->recursiveTagParse( trim( $label ) );
4320 $ig->add( $nt, $html );
4322 # Only add real images (bug #5586)
4323 if ( $nt->getNamespace() == NS_IMAGE
) {
4324 $this->mOutput
->addImage( $nt->getDBkey() );
4327 return $ig->toHTML();
4330 function getImageParams( $handler ) {
4332 $handlerClass = get_class( $handler );
4336 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4337 // Initialise static lists
4338 static $internalParamNames = array(
4339 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4340 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4341 'bottom', 'text-bottom' ),
4342 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4343 'upright', 'border' ),
4345 static $internalParamMap;
4346 if ( !$internalParamMap ) {
4347 $internalParamMap = array();
4348 foreach ( $internalParamNames as $type => $names ) {
4349 foreach ( $names as $name ) {
4350 $magicName = str_replace( '-', '_', "img_$name" );
4351 $internalParamMap[$magicName] = array( $type, $name );
4356 // Add handler params
4357 $paramMap = $internalParamMap;
4359 $handlerParamMap = $handler->getParamMap();
4360 foreach ( $handlerParamMap as $magic => $paramName ) {
4361 $paramMap[$magic] = array( 'handler', $paramName );
4364 $this->mImageParams
[$handlerClass] = $paramMap;
4365 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4367 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4371 * Parse image options text and use it to make an image
4373 function makeImage( $title, $options ) {
4374 # @TODO: let the MediaHandler specify its transform parameters
4376 # Check if the options text is of the form "options|alt text"
4378 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4379 # * left no resizing, just left align. label is used for alt= only
4380 # * right same, but right aligned
4381 # * none same, but not aligned
4382 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4383 # * center center the image
4384 # * framed Keep original image size, no magnify-button.
4385 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4386 # * upright reduce width for upright images, rounded to full __0 px
4387 # * border draw a 1px border around the image
4388 # vertical-align values (no % or length right now):
4398 $parts = array_map( 'trim', explode( '|', $options) );
4399 $sk = $this->mOptions
->getSkin();
4401 # Give extensions a chance to select the file revision for us
4402 $skip = $time = false;
4403 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4406 return $sk->makeLinkObj( $title );
4410 $file = wfFindFile( $title, $time );
4411 $handler = $file ?
$file->getHandler() : false;
4413 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4415 # Process the input parameters
4417 $params = array( 'frame' => array(), 'handler' => array(),
4418 'horizAlign' => array(), 'vertAlign' => array() );
4419 foreach( $parts as $part ) {
4420 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4421 if ( isset( $paramMap[$magicName] ) ) {
4422 list( $type, $paramName ) = $paramMap[$magicName];
4423 $params[$type][$paramName] = $value;
4425 // Special case; width and height come in one variable together
4426 if( $type == 'handler' && $paramName == 'width' ) {
4428 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4429 $params[$type]['width'] = intval( $m[1] );
4430 $params[$type]['height'] = intval( $m[2] );
4432 $params[$type]['width'] = intval( $value );
4440 # Process alignment parameters
4441 if ( $params['horizAlign'] ) {
4442 $params['frame']['align'] = key( $params['horizAlign'] );
4444 if ( $params['vertAlign'] ) {
4445 $params['frame']['valign'] = key( $params['vertAlign'] );
4448 # Validate the handler parameters
4450 foreach ( $params['handler'] as $name => $value ) {
4451 if ( !$handler->validateParam( $name, $value ) ) {
4452 unset( $params['handler'][$name] );
4457 # Strip bad stuff out of the alt text
4458 $alt = $this->replaceLinkHoldersText( $caption );
4460 # make sure there are no placeholders in thumbnail attributes
4461 # that are later expanded to html- so expand them now and
4463 $alt = $this->mStripState
->unstripBoth( $alt );
4464 $alt = Sanitizer
::stripAllTags( $alt );
4466 $params['frame']['alt'] = $alt;
4467 $params['frame']['caption'] = $caption;
4469 # Linker does the rest
4470 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4472 # Give the handler a chance to modify the parser object
4474 $handler->parserTransformHook( $this, $file );
4481 * Set a flag in the output object indicating that the content is dynamic and
4482 * shouldn't be cached.
4484 function disableCache() {
4485 wfDebug( "Parser output marked as uncacheable.\n" );
4486 $this->mOutput
->mCacheTime
= -1;
4490 * Callback from the Sanitizer for expanding items found in HTML attribute
4491 * values, so they can be safely tested and escaped.
4492 * @param string $text
4493 * @param PPFrame $frame
4497 function attributeStripCallback( &$text, $frame = false ) {
4498 $text = $this->replaceVariables( $text, $frame );
4499 $text = $this->mStripState
->unstripBoth( $text );
4508 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4509 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4510 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4516 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4521 * Break wikitext input into sections, and either pull or replace
4522 * some particular section's text.
4524 * External callers should use the getSection and replaceSection methods.
4526 * @param string $text Page wikitext
4527 * @param string $section A section identifier string of the form:
4528 * <flag1> - <flag2> - ... - <section number>
4530 * Currently the only recognised flag is "T", which means the target section number
4531 * was derived during a template inclusion parse, in other words this is a template
4532 * section edit link. If no flags are given, it was an ordinary section edit link.
4533 * This flag is required to avoid a section numbering mismatch when a section is
4534 * enclosed by <includeonly> (bug 6563).
4536 * The section number 0 pulls the text before the first heading; other numbers will
4537 * pull the given section along with its lower-level subsections. If the section is
4538 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4540 * @param string $mode One of "get" or "replace"
4541 * @param string $newText Replacement text for section data.
4542 * @return string for "get", the extracted section text.
4543 * for "replace", the whole page with the section replaced.
4545 private function extractSections( $text, $section, $mode, $newText='' ) {
4547 $this->clearState();
4548 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4549 $this->mOptions
= new ParserOptions
;
4550 $this->setOutputType( self
::OT_WIKI
);
4553 $frame = $this->getPreprocessor()->newFrame();
4555 // Process section extraction flags
4557 $sectionParts = explode( '-', $section );
4558 $sectionIndex = array_pop( $sectionParts );
4559 foreach ( $sectionParts as $part ) {
4560 if ( $part == 'T' ) {
4561 $flags |
= self
::PTD_FOR_INCLUSION
;
4564 // Preprocess the text
4565 $root = $this->preprocessToDom( $text, $flags );
4567 // <h> nodes indicate section breaks
4568 // They can only occur at the top level, so we can find them by iterating the root's children
4569 $node = $root->getFirstChild();
4571 // Find the target section
4572 if ( $sectionIndex == 0 ) {
4573 // Section zero doesn't nest, level=big
4574 $targetLevel = 1000;
4577 if ( $node->getName() == 'h' ) {
4578 if ( $curIndex +
1 == $sectionIndex ) {
4583 if ( $mode == 'replace' ) {
4584 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4586 $node = $node->getNextSibling();
4589 $bits = $node->splitHeading();
4590 $targetLevel = $bits['level'];
4596 if ( $mode == 'get' ) {
4603 // Find the end of the section, including nested sections
4605 if ( $node->getName() == 'h' ) {
4607 $bits = $node->splitHeading();
4608 $curLevel = $bits['level'];
4609 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
4613 if ( $mode == 'get' ) {
4614 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4616 $node = $node->getNextSibling();
4619 // Write out the remainder (in replace mode only)
4620 if ( $mode == 'replace' ) {
4621 // Output the replacement text
4622 // Add two newlines on -- trailing whitespace in $newText is conventionally
4623 // stripped by the editor, so we need both newlines to restore the paragraph gap
4624 $outText .= $newText . "\n\n";
4626 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4627 $node = $node->getNextSibling();
4631 if ( is_string( $outText ) ) {
4632 // Re-insert stripped tags
4633 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4640 * This function returns the text of a section, specified by a number ($section).
4641 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4642 * the first section before any such heading (section 0).
4644 * If a section contains subsections, these are also returned.
4646 * @param string $text text to look in
4647 * @param string $section section identifier
4648 * @param string $deftext default to return if section is not found
4649 * @return string text of the requested section
4651 public function getSection( $text, $section, $deftext='' ) {
4652 return $this->extractSections( $text, $section, "get", $deftext );
4655 public function replaceSection( $oldtext, $section, $text ) {
4656 return $this->extractSections( $oldtext, $section, "replace", $text );
4660 * Get the timestamp associated with the current revision, adjusted for
4661 * the default server-local timestamp
4663 function getRevisionTimestamp() {
4664 if ( is_null( $this->mRevisionTimestamp
) ) {
4665 wfProfileIn( __METHOD__
);
4667 $dbr = wfGetDB( DB_SLAVE
);
4668 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4669 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4671 // Normalize timestamp to internal MW format for timezone processing.
4672 // This has the added side-effect of replacing a null value with
4673 // the current time, which gives us more sensible behavior for
4675 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4677 // The cryptic '' timezone parameter tells to use the site-default
4678 // timezone offset instead of the user settings.
4680 // Since this value will be saved into the parser cache, served
4681 // to other users, and potentially even used inside links and such,
4682 // it needs to be consistent for all visitors.
4683 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4685 wfProfileOut( __METHOD__
);
4687 return $this->mRevisionTimestamp
;
4691 * Mutator for $mDefaultSort
4693 * @param $sort New value
4695 public function setDefaultSort( $sort ) {
4696 $this->mDefaultSort
= $sort;
4700 * Accessor for $mDefaultSort
4701 * Will use the title/prefixed title if none is set
4705 public function getDefaultSort() {
4706 if( $this->mDefaultSort
!== false ) {
4707 return $this->mDefaultSort
;
4709 return $this->mTitle
->getNamespace() == NS_CATEGORY
4710 ?
$this->mTitle
->getText()
4711 : $this->mTitle
->getPrefixedText();
4716 * Try to guess the section anchor name based on a wikitext fragment
4717 * presumably extracted from a heading, for example "Header" from
4720 public function guessSectionNameFromWikiText( $text ) {
4721 # Strip out wikitext links(they break the anchor)
4722 $text = $this->stripSectionName( $text );
4723 $headline = Sanitizer
::decodeCharReferences( $text );
4725 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4726 $headline = trim( $headline );
4727 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4728 $replacearray = array(
4733 array_keys( $replacearray ),
4734 array_values( $replacearray ),
4739 * Strips a text string of wikitext for use in a section anchor
4741 * Accepts a text string and then removes all wikitext from the
4742 * string and leaves only the resultant text (i.e. the result of
4743 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4744 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4745 * to create valid section anchors by mimicing the output of the
4746 * parser when headings are parsed.
4748 * @param $text string Text string to be stripped of wikitext
4749 * for use in a Section anchor
4750 * @return Filtered text string
4752 public function stripSectionName( $text ) {
4753 # Strip internal link markup
4754 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4755 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4757 # Strip external link markup (FIXME: Not Tolerant to blank link text
4758 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4759 # on how many empty links there are on the page - need to figure that out.
4760 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4762 # Parse wikitext quotes (italics & bold)
4763 $text = $this->doQuotes($text);
4766 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4770 function srvus( $text ) {
4771 return $this->testSrvus( $text, $this->mOutputType
);
4775 * strip/replaceVariables/unstrip for preprocessor regression testing
4777 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4778 $this->clearState();
4779 $this->mTitle
= $title;
4780 $this->mOptions
= $options;
4781 $this->setOutputType( $outputType );
4782 $text = $this->replaceVariables( $text );
4783 $text = $this->mStripState
->unstripBoth( $text );
4784 $text = Sanitizer
::removeHTMLtags( $text );
4788 function testPst( $text, $title, $options ) {
4790 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4793 function testPreprocess( $text, $title, $options ) {
4794 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4799 * @todo document, briefly.
4800 * @addtogroup Parser
4803 var $general, $nowiki;
4805 function __construct() {
4806 $this->general
= new ReplacementArray
;
4807 $this->nowiki
= new ReplacementArray
;
4810 function unstripGeneral( $text ) {
4811 wfProfileIn( __METHOD__
);
4814 $text = $this->general
->replace( $text );
4815 } while ( $text != $oldText );
4816 wfProfileOut( __METHOD__
);
4820 function unstripNoWiki( $text ) {
4821 wfProfileIn( __METHOD__
);
4824 $text = $this->nowiki
->replace( $text );
4825 } while ( $text != $oldText );
4826 wfProfileOut( __METHOD__
);
4830 function unstripBoth( $text ) {
4831 wfProfileIn( __METHOD__
);
4834 $text = $this->general
->replace( $text );
4835 $text = $this->nowiki
->replace( $text );
4836 } while ( $text != $oldText );
4837 wfProfileOut( __METHOD__
);
4843 * @todo document, briefly.
4844 * @addtogroup Parser
4846 class OnlyIncludeReplacer
{
4849 function replace( $matches ) {
4850 if ( substr( $matches[1], -1 ) == "\n" ) {
4851 $this->output
.= substr( $matches[1], 0, -1 );
4853 $this->output
.= $matches[1];