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;
83 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
84 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
85 $mExtLinkBracketedRegex, $mPreprocessor, $mDefaultStripList;
88 # Cleared with clearState():
89 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
90 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
91 var $mInterwikiLinkHolders, $mLinkHolders;
92 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
93 var $mTplExpandCache; // empty-frame expansion cache
94 var $mTplRedirCache, $mTplDomCache, $mHeadings;
97 # These are variables reset at least once per parse regardless of $clearState
98 var $mOptions, // ParserOptions object
99 $mTitle, // Title context, used for self-link rendering and similar things
100 $mOutputType, // Output type, one of the OT_xxx constants
101 $ot, // Shortcut alias, see setOutputType()
102 $mRevisionId, // ID to display in {{REVISIONID}} tags
103 $mRevisionTimestamp, // The timestamp of the specified revision ID
104 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
113 function __construct( $conf = array() ) {
114 $this->mTagHooks
= array();
115 $this->mTransparentTagHooks
= array();
116 $this->mFunctionHooks
= array();
117 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
118 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
119 $this->mMarkerSuffix
= "-QINU\x7f";
120 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
121 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
122 if ( isset( $conf['preprocessorClass'] ) ) {
123 $this->mPreprocessorClass
= $conf['preprocessorClass'];
125 $this->mPreprocessorClass
= 'Preprocessor_DOM';
127 $this->mFirstCall
= true;
131 * Do various kinds of initialisation on the first call of the parser
133 function firstCallInit() {
134 if ( !$this->mFirstCall
) {
137 $this->mFirstCall
= false;
139 wfProfileIn( __METHOD__
);
140 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
142 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
144 # Syntax for arguments (see self::setFunctionHook):
145 # "name for lookup in localized magic words array",
147 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
148 # instead of {{#int:...}})
149 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
174 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
175 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
176 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS
);
178 if ( $wgAllowDisplayTitle ) {
179 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
181 if ( $wgAllowSlowParserFunctions ) {
182 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
185 $this->initialiseVariables();
187 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
188 wfProfileOut( __METHOD__
);
196 function clearState() {
197 wfProfileIn( __METHOD__
);
198 if ( $this->mFirstCall
) {
199 $this->firstCallInit();
201 $this->mOutput
= new ParserOutput
;
202 $this->mAutonumber
= 0;
203 $this->mLastSection
= '';
204 $this->mDTopen
= false;
205 $this->mIncludeCount
= array();
206 $this->mStripState
= new StripState
;
207 $this->mArgStack
= false;
208 $this->mInPre
= false;
209 $this->mInterwikiLinkHolders
= array(
213 $this->mLinkHolders
= array(
214 'namespaces' => array(),
216 'queries' => array(),
220 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
223 * Prefix for temporary replacement strings for the multipass parser.
224 * \x07 should never appear in input as it's disallowed in XML.
225 * Using it at the front also gives us a little extra robustness
226 * since it shouldn't match when butted up against identifier-like
229 * Must not consist of all title characters, or else it will change
230 * the behaviour of <nowiki> in a link.
232 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
233 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
235 # Clear these on every parse, bug 4549
236 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
238 $this->mShowToc
= true;
239 $this->mForceTocPosition
= false;
240 $this->mIncludeSizes
= array(
244 $this->mPPNodeCount
= 0;
245 $this->mDefaultSort
= false;
246 $this->mHeadings
= array();
248 wfRunHooks( 'ParserClearState', array( &$this ) );
249 wfProfileOut( __METHOD__
);
252 function setOutputType( $ot ) {
253 $this->mOutputType
= $ot;
256 'html' => $ot == OT_HTML
,
257 'wiki' => $ot == OT_WIKI
,
258 'pre' => $ot == OT_PREPROCESS
,
263 * Set the context title
265 function setTitle( $t ) {
266 if ( !$t ||
$t instanceof FakeTitle
) {
267 $t = Title
::newFromText( 'NO TITLE' );
269 if ( strval( $t->getFragment() ) !== '' ) {
270 # Strip the fragment to avoid various odd effects
271 $this->mTitle
= clone $t;
272 $this->mTitle
->setFragment( '' );
279 * Accessor for mUniqPrefix.
283 function uniqPrefix() {
284 if( !isset( $this->mUniqPrefix
) ) {
285 // @fixme this is probably *horribly wrong*
286 // LanguageConverter seems to want $wgParser's uniqPrefix, however
287 // if this is called for a parser cache hit, the parser may not
288 // have ever been initialized in the first place.
289 // Not really sure what the heck is supposed to be going on here.
291 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
293 return $this->mUniqPrefix
;
297 * Convert wikitext to HTML
298 * Do not call this function recursively.
300 * @param string $text Text we want to parse
301 * @param Title &$title A title object
302 * @param array $options
303 * @param boolean $linestart
304 * @param boolean $clearState
305 * @param int $revid number to pass in {{REVISIONID}}
306 * @return ParserOutput a ParserOutput
308 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
310 * First pass--just handle <nowiki> sections, pass the rest off
311 * to internalParse() which does all the real work.
314 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
315 $fname = 'Parser::parse-' . wfGetCaller();
316 wfProfileIn( __METHOD__
);
317 wfProfileIn( $fname );
323 $this->mOptions
= $options;
324 $this->setTitle( $title );
325 $oldRevisionId = $this->mRevisionId
;
326 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
327 if( $revid !== null ) {
328 $this->mRevisionId
= $revid;
329 $this->mRevisionTimestamp
= null;
331 $this->setOutputType( OT_HTML
);
332 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
334 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
335 $text = $this->internalParse( $text );
336 $text = $this->mStripState
->unstripGeneral( $text );
338 # Clean up special characters, only run once, next-to-last before doBlockLevels
340 # french spaces, last one Guillemet-left
341 # only if there is something before the space
342 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
343 # french spaces, Guillemet-right
344 '/(\\302\\253) /' => '\\1 ',
346 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
349 $text = $this->doBlockLevels( $text, $linestart );
351 $this->replaceLinkHolders( $text );
353 # the position of the parserConvert() call should not be changed. it
354 # assumes that the links are all replaced and the only thing left
355 # is the <nowiki> mark.
356 # Side-effects: this calls $this->mOutput->setTitleText()
357 $text = $wgContLang->parserConvert( $text, $this );
359 $text = $this->mStripState
->unstripNoWiki( $text );
361 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
363 //!JF Move to its own function
365 $uniq_prefix = $this->mUniqPrefix
;
367 $elements = array_keys( $this->mTransparentTagHooks
);
368 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
370 foreach( $matches as $marker => $data ) {
371 list( $element, $content, $params, $tag ) = $data;
372 $tagName = strtolower( $element );
373 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
374 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
375 array( $content, $params, $this ) );
379 $this->mStripState
->general
->setPair( $marker, $output );
381 $text = $this->mStripState
->unstripGeneral( $text );
383 $text = Sanitizer
::normalizeCharReferences( $text );
385 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
386 $text = Parser
::tidy($text);
388 # attempt to sanitize at least some nesting problems
389 # (bug #2702 and quite a few others)
391 # ''Something [http://www.cool.com cool''] -->
392 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
393 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
394 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
395 # fix up an anchor inside another anchor, only
396 # at least for a single single nested link (bug 3695)
397 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
398 '\\1\\2</a>\\3</a>\\1\\4</a>',
399 # fix div inside inline elements- doBlockLevels won't wrap a line which
400 # contains a div, so fix it up here; replace
401 # div with escaped text
402 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
403 '\\1\\3<div\\5>\\6</div>\\8\\9',
404 # remove empty italic or bold tag pairs, some
405 # introduced by rules above
406 '/<([bi])><\/\\1>/' => '',
409 $text = preg_replace(
410 array_keys( $tidyregs ),
411 array_values( $tidyregs ),
415 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
417 # Information on include size limits, for the benefit of users who try to skirt them
418 if ( $this->mOptions
->getEnableLimitReport() ) {
419 $max = $this->mOptions
->getMaxIncludeSize();
421 "NewPP limit report\n" .
422 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
423 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
424 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
425 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
426 $text .= "\n<!-- \n$limitReport-->\n";
428 $this->mOutput
->setText( $text );
429 $this->mRevisionId
= $oldRevisionId;
430 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
431 wfProfileOut( $fname );
432 wfProfileOut( __METHOD__
);
434 return $this->mOutput
;
438 * Recursive parser entry point that can be called from an extension tag
441 function recursiveTagParse( $text ) {
442 wfProfileIn( __METHOD__
);
443 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
444 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
445 $text = $this->internalParse( $text );
446 wfProfileOut( __METHOD__
);
451 * Expand templates and variables in the text, producing valid, static wikitext.
452 * Also removes comments.
454 function preprocess( $text, $title, $options, $revid = null ) {
455 wfProfileIn( __METHOD__
);
457 $this->setOutputType( OT_PREPROCESS
);
458 $this->mOptions
= $options;
459 $this->setTitle( $title );
460 if( $revid !== null ) {
461 $this->mRevisionId
= $revid;
463 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
464 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
465 $text = $this->replaceVariables( $text );
466 $text = $this->mStripState
->unstripBoth( $text );
467 wfProfileOut( __METHOD__
);
472 * Get a random string
477 function getRandomString() {
478 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
481 function &getTitle() { return $this->mTitle
; }
482 function getOptions() { return $this->mOptions
; }
484 function getFunctionLang() {
485 global $wgLang, $wgContLang;
486 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
490 * Get a preprocessor object
492 function getPreprocessor() {
493 if ( !isset( $this->mPreprocessor
) ) {
494 $class = $this->mPreprocessorClass
;
495 $this->mPreprocessor
= new $class( $this );
497 return $this->mPreprocessor
;
501 * Replaces all occurrences of HTML-style comments and the given tags
502 * in the text with a random marker and returns teh next text. The output
503 * parameter $matches will be an associative array filled with data in
505 * 'UNIQ-xxxxx' => array(
508 * array( 'param' => 'x' ),
509 * '<element param="x">tag content</element>' ) )
511 * @param $elements list of element names. Comments are always extracted.
512 * @param $text Source text string.
513 * @param $uniq_prefix
518 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
523 $taglist = implode( '|', $elements );
524 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
526 while ( '' != $text ) {
527 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
529 if( count( $p ) < 5 ) {
532 if( count( $p ) > 5 ) {
546 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
547 $stripped .= $marker;
549 if ( $close === '/>' ) {
550 // Empty element tag, <tag />
555 if( $element == '!--' ) {
558 $end = "/(<\\/$element\\s*>)/i";
560 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
562 if( count( $q ) < 3 ) {
563 # No end tag -- let it run out to the end of the text.
572 $matches[$marker] = array( $element,
574 Sanitizer
::decodeTagAttributes( $attributes ),
575 "<$element$attributes$close$content$tail" );
581 * Get a list of strippable XML-like elements
583 function getStripList() {
585 $elements = $this->mStripList
;
587 $elements[] = 'html';
589 if( $this->mOptions
->getUseTeX() ) {
590 $elements[] = 'math';
596 * @deprecated use replaceVariables
598 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
603 * Restores pre, math, and other extensions removed by strip()
605 * always call unstripNoWiki() after this one
607 * @deprecated use $this->mStripState->unstrip()
609 function unstrip( $text, $state ) {
610 return $state->unstripGeneral( $text );
614 * Always call this after unstrip() to preserve the order
617 * @deprecated use $this->mStripState->unstrip()
619 function unstripNoWiki( $text, $state ) {
620 return $state->unstripNoWiki( $text );
624 * @deprecated use $this->mStripState->unstripBoth()
626 function unstripForHTML( $text ) {
627 return $this->mStripState
->unstripBoth( $text );
631 * Add an item to the strip state
632 * Returns the unique tag which must be inserted into the stripped text
633 * The tag will be replaced with the original text in unstrip()
637 function insertStripItem( $text ) {
639 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
641 $this->mStripState
->general
->setPair( $rnd, $text );
646 * Interface with html tidy, used if $wgUseTidy = true.
647 * If tidy isn't able to correct the markup, the original will be
648 * returned in all its glory with a warning comment appended.
650 * Either the external tidy program or the in-process tidy extension
651 * will be used depending on availability. Override the default
652 * $wgTidyInternal setting to disable the internal if it's not working.
654 * @param string $text Hideous HTML input
655 * @return string Corrected HTML output
659 function tidy( $text ) {
660 global $wgTidyInternal;
661 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
662 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
663 '<head><title>test</title></head><body>'.$text.'</body></html>';
664 if( $wgTidyInternal ) {
665 $correctedtext = Parser
::internalTidy( $wrappedtext );
667 $correctedtext = Parser
::externalTidy( $wrappedtext );
669 if( is_null( $correctedtext ) ) {
670 wfDebug( "Tidy error detected!\n" );
671 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
673 return $correctedtext;
677 * Spawn an external HTML tidy process and get corrected markup back from it.
682 function externalTidy( $text ) {
683 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
684 $fname = 'Parser::externalTidy';
685 wfProfileIn( $fname );
690 $descriptorspec = array(
691 0 => array('pipe', 'r'),
692 1 => array('pipe', 'w'),
693 2 => array('file', wfGetNull(), 'a')
696 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
697 if (is_resource($process)) {
698 // Theoretically, this style of communication could cause a deadlock
699 // here. If the stdout buffer fills up, then writes to stdin could
700 // block. This doesn't appear to happen with tidy, because tidy only
701 // writes to stdout after it's finished reading from stdin. Search
702 // for tidyParseStdin and tidySaveStdout in console/tidy.c
703 fwrite($pipes[0], $text);
705 while (!feof($pipes[1])) {
706 $cleansource .= fgets($pipes[1], 1024);
709 proc_close($process);
712 wfProfileOut( $fname );
714 if( $cleansource == '' && $text != '') {
715 // Some kind of error happened, so we couldn't get the corrected text.
716 // Just give up; we'll use the source text and append a warning.
724 * Use the HTML tidy PECL extension to use the tidy library in-process,
725 * saving the overhead of spawning a new process.
727 * 'pear install tidy' should be able to compile the extension module.
732 function internalTidy( $text ) {
733 global $wgTidyConf, $IP, $wgDebugTidy;
734 $fname = 'Parser::internalTidy';
735 wfProfileIn( $fname );
738 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
739 $tidy->cleanRepair();
740 if( $tidy->getStatus() == 2 ) {
741 // 2 is magic number for fatal error
742 // http://www.php.net/manual/en/function.tidy-get-status.php
745 $cleansource = tidy_get_output( $tidy );
747 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
748 $cleansource .= "<!--\nTidy reports:\n" .
749 str_replace( '-->', '-->', $tidy->errorBuffer
) .
753 wfProfileOut( $fname );
758 * parse the wiki syntax used to render tables
762 function doTableStuff ( $text ) {
763 $fname = 'Parser::doTableStuff';
764 wfProfileIn( $fname );
766 $lines = explode ( "\n" , $text );
767 $td_history = array (); // Is currently a td tag open?
768 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
769 $tr_history = array (); // Is currently a tr tag open?
770 $tr_attributes = array (); // history of tr attributes
771 $has_opened_tr = array(); // Did this table open a <tr> element?
772 $indent_level = 0; // indent level of the table
773 foreach ( $lines as $key => $line )
775 $line = trim ( $line );
777 if( $line == '' ) { // empty line, go to next line
780 $first_character = $line{0};
783 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
784 // First check if we are starting a new table
785 $indent_level = strlen( $matches[1] );
787 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
788 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
790 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
791 array_push ( $td_history , false );
792 array_push ( $last_tag_history , '' );
793 array_push ( $tr_history , false );
794 array_push ( $tr_attributes , '' );
795 array_push ( $has_opened_tr , false );
796 } else if ( count ( $td_history ) == 0 ) {
797 // Don't do any of the following
799 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
800 // We are ending a table
801 $line = '</table>' . substr ( $line , 2 );
802 $last_tag = array_pop ( $last_tag_history );
804 if ( !array_pop ( $has_opened_tr ) ) {
805 $line = "<tr><td></td></tr>{$line}";
808 if ( array_pop ( $tr_history ) ) {
809 $line = "</tr>{$line}";
812 if ( array_pop ( $td_history ) ) {
813 $line = "</{$last_tag}>{$line}";
815 array_pop ( $tr_attributes );
816 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
817 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
818 // Now we have a table row
819 $line = preg_replace( '#^\|-+#', '', $line );
821 // Whats after the tag is now only attributes
822 $attributes = $this->mStripState
->unstripBoth( $line );
823 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
824 array_pop ( $tr_attributes );
825 array_push ( $tr_attributes , $attributes );
828 $last_tag = array_pop ( $last_tag_history );
829 array_pop ( $has_opened_tr );
830 array_push ( $has_opened_tr , true );
832 if ( array_pop ( $tr_history ) ) {
836 if ( array_pop ( $td_history ) ) {
837 $line = "</{$last_tag}>{$line}";
840 $lines[$key] = $line;
841 array_push ( $tr_history , false );
842 array_push ( $td_history , false );
843 array_push ( $last_tag_history , '' );
845 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
846 // This might be cell elements, td, th or captions
847 if ( substr ( $line , 0 , 2 ) == '|+' ) {
848 $first_character = '+';
849 $line = substr ( $line , 1 );
852 $line = substr ( $line , 1 );
854 if ( $first_character == '!' ) {
855 $line = str_replace ( '!!' , '||' , $line );
858 // Split up multiple cells on the same line.
859 // FIXME : This can result in improper nesting of tags processed
860 // by earlier parser steps, but should avoid splitting up eg
861 // attribute values containing literal "||".
862 $cells = StringUtils
::explodeMarkup( '||' , $line );
866 // Loop through each table cell
867 foreach ( $cells as $cell )
870 if ( $first_character != '+' )
872 $tr_after = array_pop ( $tr_attributes );
873 if ( !array_pop ( $tr_history ) ) {
874 $previous = "<tr{$tr_after}>\n";
876 array_push ( $tr_history , true );
877 array_push ( $tr_attributes , '' );
878 array_pop ( $has_opened_tr );
879 array_push ( $has_opened_tr , true );
882 $last_tag = array_pop ( $last_tag_history );
884 if ( array_pop ( $td_history ) ) {
885 $previous = "</{$last_tag}>{$previous}";
888 if ( $first_character == '|' ) {
890 } else if ( $first_character == '!' ) {
892 } else if ( $first_character == '+' ) {
893 $last_tag = 'caption';
898 array_push ( $last_tag_history , $last_tag );
900 // A cell could contain both parameters and data
901 $cell_data = explode ( '|' , $cell , 2 );
903 // Bug 553: Note that a '|' inside an invalid link should not
904 // be mistaken as delimiting cell parameters
905 if ( strpos( $cell_data[0], '[[' ) !== false ) {
906 $cell = "{$previous}<{$last_tag}>{$cell}";
907 } else if ( count ( $cell_data ) == 1 )
908 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
910 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
911 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
912 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
915 $lines[$key] .= $cell;
916 array_push ( $td_history , true );
921 // Closing open td, tr && table
922 while ( count ( $td_history ) > 0 )
924 if ( array_pop ( $td_history ) ) {
927 if ( array_pop ( $tr_history ) ) {
930 if ( !array_pop ( $has_opened_tr ) ) {
931 $lines[] = "<tr><td></td></tr>" ;
934 $lines[] = '</table>' ;
937 $output = implode ( "\n" , $lines ) ;
939 // special case: don't return empty table
940 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
944 wfProfileOut( $fname );
950 * Helper function for parse() that transforms wiki markup into
951 * HTML. Only called for $mOutputType == OT_HTML.
955 function internalParse( $text ) {
957 $fname = 'Parser::internalParse';
958 wfProfileIn( $fname );
960 # Hook to suspend the parser in this state
961 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
962 wfProfileOut( $fname );
966 $text = $this->replaceVariables( $text );
967 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
968 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
970 // Tables need to come after variable replacement for things to work
971 // properly; putting them before other transformations should keep
972 // exciting things like link expansions from showing up in surprising
974 $text = $this->doTableStuff( $text );
976 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
978 $text = $this->stripToc( $text );
979 $this->stripNoGallery( $text );
980 $text = $this->doHeadings( $text );
981 if($this->mOptions
->getUseDynamicDates()) {
982 $df =& DateFormatter
::getInstance();
983 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
985 $text = $this->doAllQuotes( $text );
986 $text = $this->replaceInternalLinks( $text );
987 $text = $this->replaceExternalLinks( $text );
989 # replaceInternalLinks may sometimes leave behind
990 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
991 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
993 $text = $this->doMagicLinks( $text );
994 $text = $this->formatHeadings( $text, $isMain );
996 wfProfileOut( $fname );
1001 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1002 * magic external links.
1006 function doMagicLinks( $text ) {
1007 wfProfileIn( __METHOD__
);
1008 $text = preg_replace_callback(
1010 <a.*?</a> | # Skip link text
1011 <.*?> | # Skip stuff inside HTML elements
1012 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1013 ISBN\s+(\b # ISBN, capture number as m[2]
1014 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1015 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1016 [0-9Xx] # check digit
1018 )!x', array( &$this, 'magicLinkCallback' ), $text );
1019 wfProfileOut( __METHOD__
);
1023 function magicLinkCallback( $m ) {
1024 if ( substr( $m[0], 0, 1 ) == '<' ) {
1027 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1029 $num = strtr( $isbn, array(
1034 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1035 $text = '<a href="' .
1036 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1037 "\" class=\"internal\">ISBN $isbn</a>";
1039 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1043 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1045 $urlmsg = 'pubmedurl';
1048 throw new MWException( __METHOD__
.': unrecognised match type "' .
1049 substr($m[0], 0, 20 ) . '"' );
1052 $url = wfMsg( $urlmsg, $id);
1053 $sk = $this->mOptions
->getSkin();
1054 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1055 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1061 * Parse headers and return html
1065 function doHeadings( $text ) {
1066 $fname = 'Parser::doHeadings';
1067 wfProfileIn( $fname );
1068 for ( $i = 6; $i >= 1; --$i ) {
1069 $h = str_repeat( '=', $i );
1070 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1071 "<h$i>\\1</h$i>", $text );
1073 wfProfileOut( $fname );
1078 * Replace single quotes with HTML markup
1080 * @return string the altered text
1082 function doAllQuotes( $text ) {
1083 $fname = 'Parser::doAllQuotes';
1084 wfProfileIn( $fname );
1086 $lines = explode( "\n", $text );
1087 foreach ( $lines as $line ) {
1088 $outtext .= $this->doQuotes ( $line ) . "\n";
1090 $outtext = substr($outtext, 0,-1);
1091 wfProfileOut( $fname );
1096 * Helper function for doAllQuotes()
1098 public function doQuotes( $text ) {
1099 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1100 if ( count( $arr ) == 1 )
1104 # First, do some preliminary work. This may shift some apostrophes from
1105 # being mark-up to being text. It also counts the number of occurrences
1106 # of bold and italics mark-ups.
1110 foreach ( $arr as $r )
1112 if ( ( $i %
2 ) == 1 )
1114 # If there are ever four apostrophes, assume the first is supposed to
1115 # be text, and the remaining three constitute mark-up for bold text.
1116 if ( strlen( $arr[$i] ) == 4 )
1121 # If there are more than 5 apostrophes in a row, assume they're all
1122 # text except for the last 5.
1123 else if ( strlen( $arr[$i] ) > 5 )
1125 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1128 # Count the number of occurrences of bold and italics mark-ups.
1129 # We are not counting sequences of five apostrophes.
1130 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1131 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1132 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1137 # If there is an odd number of both bold and italics, it is likely
1138 # that one of the bold ones was meant to be an apostrophe followed
1139 # by italics. Which one we cannot know for certain, but it is more
1140 # likely to be one that has a single-letter word before it.
1141 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1144 $firstsingleletterword = -1;
1145 $firstmultiletterword = -1;
1147 foreach ( $arr as $r )
1149 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1151 $x1 = substr ($arr[$i-1], -1);
1152 $x2 = substr ($arr[$i-1], -2, 1);
1154 if ($firstspace == -1) $firstspace = $i;
1155 } else if ($x2 == ' ') {
1156 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1158 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1164 # If there is a single-letter word, use it!
1165 if ($firstsingleletterword > -1)
1167 $arr [ $firstsingleletterword ] = "''";
1168 $arr [ $firstsingleletterword-1 ] .= "'";
1170 # If not, but there's a multi-letter word, use that one.
1171 else if ($firstmultiletterword > -1)
1173 $arr [ $firstmultiletterword ] = "''";
1174 $arr [ $firstmultiletterword-1 ] .= "'";
1176 # ... otherwise use the first one that has neither.
1177 # (notice that it is possible for all three to be -1 if, for example,
1178 # there is only one pentuple-apostrophe in the line)
1179 else if ($firstspace > -1)
1181 $arr [ $firstspace ] = "''";
1182 $arr [ $firstspace-1 ] .= "'";
1186 # Now let's actually convert our apostrophic mush to HTML!
1191 foreach ($arr as $r)
1195 if ($state == 'both')
1202 if (strlen ($r) == 2)
1205 { $output .= '</i>'; $state = ''; }
1206 else if ($state == 'bi')
1207 { $output .= '</i>'; $state = 'b'; }
1208 else if ($state == 'ib')
1209 { $output .= '</b></i><b>'; $state = 'b'; }
1210 else if ($state == 'both')
1211 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1212 else # $state can be 'b' or ''
1213 { $output .= '<i>'; $state .= 'i'; }
1215 else if (strlen ($r) == 3)
1218 { $output .= '</b>'; $state = ''; }
1219 else if ($state == 'bi')
1220 { $output .= '</i></b><i>'; $state = 'i'; }
1221 else if ($state == 'ib')
1222 { $output .= '</b>'; $state = 'i'; }
1223 else if ($state == 'both')
1224 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1225 else # $state can be 'i' or ''
1226 { $output .= '<b>'; $state .= 'b'; }
1228 else if (strlen ($r) == 5)
1231 { $output .= '</b><i>'; $state = 'i'; }
1232 else if ($state == 'i')
1233 { $output .= '</i><b>'; $state = 'b'; }
1234 else if ($state == 'bi')
1235 { $output .= '</i></b>'; $state = ''; }
1236 else if ($state == 'ib')
1237 { $output .= '</b></i>'; $state = ''; }
1238 else if ($state == 'both')
1239 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1240 else # ($state == '')
1241 { $buffer = ''; $state = 'both'; }
1246 # Now close all remaining tags. Notice that the order is important.
1247 if ($state == 'b' ||
$state == 'ib')
1249 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1253 # There might be lonely ''''', so make sure we have a buffer
1254 if ($state == 'both' && $buffer)
1255 $output .= '<b><i>'.$buffer.'</i></b>';
1261 * Replace external links
1263 * Note: this is all very hackish and the order of execution matters a lot.
1264 * Make sure to run maintenance/parserTests.php if you change this code.
1268 function replaceExternalLinks( $text ) {
1270 $fname = 'Parser::replaceExternalLinks';
1271 wfProfileIn( $fname );
1273 $sk = $this->mOptions
->getSkin();
1275 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1277 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1280 while ( $i<count( $bits ) ) {
1282 $protocol = $bits[$i++
];
1283 $text = $bits[$i++
];
1284 $trail = $bits[$i++
];
1286 # The characters '<' and '>' (which were escaped by
1287 # removeHTMLtags()) should not be included in
1288 # URLs, per RFC 2396.
1290 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1291 $text = substr($url, $m2[0][1]) . ' ' . $text;
1292 $url = substr($url, 0, $m2[0][1]);
1295 # If the link text is an image URL, replace it with an <img> tag
1296 # This happened by accident in the original parser, but some people used it extensively
1297 $img = $this->maybeMakeExternalImage( $text );
1298 if ( $img !== false ) {
1304 # Set linktype for CSS - if URL==text, link is essentially free
1305 $linktype = ($text == $url) ?
'free' : 'text';
1307 # No link text, e.g. [http://domain.tld/some.link]
1308 if ( $text == '' ) {
1309 # Autonumber if allowed. See bug #5918
1310 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1311 $text = '[' . ++
$this->mAutonumber
. ']';
1312 $linktype = 'autonumber';
1314 # Otherwise just use the URL
1315 $text = htmlspecialchars( $url );
1319 # Have link text, e.g. [http://domain.tld/some.link text]s
1321 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1324 $text = $wgContLang->markNoConversion($text);
1326 $url = Sanitizer
::cleanUrl( $url );
1328 # Process the trail (i.e. everything after this link up until start of the next link),
1329 # replacing any non-bracketed links
1330 $trail = $this->replaceFreeExternalLinks( $trail );
1332 # Use the encoded URL
1333 # This means that users can paste URLs directly into the text
1334 # Funny characters like ö aren't valid in URLs anyway
1335 # This was changed in August 2004
1336 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1338 # Register link in the output object.
1339 # Replace unnecessary URL escape codes with the referenced character
1340 # This prevents spammers from hiding links from the filters
1341 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1342 $this->mOutput
->addExternalLink( $pasteurized );
1345 wfProfileOut( $fname );
1350 * Replace anything that looks like a URL with a link
1353 function replaceFreeExternalLinks( $text ) {
1355 $fname = 'Parser::replaceFreeExternalLinks';
1356 wfProfileIn( $fname );
1358 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1359 $s = array_shift( $bits );
1362 $sk = $this->mOptions
->getSkin();
1364 while ( $i < count( $bits ) ){
1365 $protocol = $bits[$i++
];
1366 $remainder = $bits[$i++
];
1369 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1370 # Found some characters after the protocol that look promising
1371 $url = $protocol . $m[1];
1374 # special case: handle urls as url args:
1375 # http://www.example.com/foo?=http://www.example.com/bar
1376 if(strlen($trail) == 0 &&
1378 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1379 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1382 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1387 # The characters '<' and '>' (which were escaped by
1388 # removeHTMLtags()) should not be included in
1389 # URLs, per RFC 2396.
1391 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1392 $trail = substr($url, $m2[0][1]) . $trail;
1393 $url = substr($url, 0, $m2[0][1]);
1396 # Move trailing punctuation to $trail
1398 # If there is no left bracket, then consider right brackets fair game too
1399 if ( strpos( $url, '(' ) === false ) {
1403 $numSepChars = strspn( strrev( $url ), $sep );
1404 if ( $numSepChars ) {
1405 $trail = substr( $url, -$numSepChars ) . $trail;
1406 $url = substr( $url, 0, -$numSepChars );
1409 $url = Sanitizer
::cleanUrl( $url );
1411 # Is this an external image?
1412 $text = $this->maybeMakeExternalImage( $url );
1413 if ( $text === false ) {
1414 # Not an image, make a link
1415 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1416 # Register it in the output object...
1417 # Replace unnecessary URL escape codes with their equivalent characters
1418 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1419 $this->mOutput
->addExternalLink( $pasteurized );
1421 $s .= $text . $trail;
1423 $s .= $protocol . $remainder;
1426 wfProfileOut( $fname );
1431 * Replace unusual URL escape codes with their equivalent characters
1435 * @todo This can merge genuinely required bits in the path or query string,
1436 * breaking legit URLs. A proper fix would treat the various parts of
1437 * the URL differently; as a workaround, just use the output for
1438 * statistical records, not for actual linking/output.
1440 static function replaceUnusualEscapes( $url ) {
1441 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1442 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1446 * Callback function used in replaceUnusualEscapes().
1447 * Replaces unusual URL escape codes with their equivalent character
1451 private static function replaceUnusualEscapesCallback( $matches ) {
1452 $char = urldecode( $matches[0] );
1453 $ord = ord( $char );
1454 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1455 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1456 // No, shouldn't be escaped
1459 // Yes, leave it escaped
1465 * make an image if it's allowed, either through the global
1466 * option or through the exception
1469 function maybeMakeExternalImage( $url ) {
1470 $sk = $this->mOptions
->getSkin();
1471 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1472 $imagesexception = !empty($imagesfrom);
1474 if ( $this->mOptions
->getAllowExternalImages()
1475 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1476 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1478 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1485 * Process [[ ]] wikilinks
1489 function replaceInternalLinks( $s ) {
1491 static $fname = 'Parser::replaceInternalLinks' ;
1493 wfProfileIn( $fname );
1495 wfProfileIn( $fname.'-setup' );
1497 # the % is needed to support urlencoded titles as well
1498 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1500 $sk = $this->mOptions
->getSkin();
1502 #split the entire text string on occurences of [[
1503 $a = explode( '[[', ' ' . $s );
1504 #get the first element (all text up to first [[), and remove the space we added
1505 $s = array_shift( $a );
1506 $s = substr( $s, 1 );
1508 # Match a link having the form [[namespace:link|alternate]]trail
1510 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1511 # Match cases where there is no "]]", which might still be images
1512 static $e1_img = FALSE;
1513 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1515 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1517 if ( $useLinkPrefixExtension ) {
1518 # Match the end of a line for a word that's not followed by whitespace,
1519 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1520 $e2 = wfMsgForContent( 'linkprefix' );
1523 if( is_null( $this->mTitle
) ) {
1524 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1526 $nottalk = !$this->mTitle
->isTalkPage();
1528 if ( $useLinkPrefixExtension ) {
1530 if ( preg_match( $e2, $s, $m ) ) {
1531 $first_prefix = $m[2];
1533 $first_prefix = false;
1539 if($wgContLang->hasVariants()) {
1540 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1542 $selflink = array($this->mTitle
->getPrefixedText());
1544 $useSubpages = $this->areSubpagesAllowed();
1545 wfProfileOut( $fname.'-setup' );
1547 # Loop for each link
1548 for ($k = 0; isset( $a[$k] ); $k++
) {
1550 if ( $useLinkPrefixExtension ) {
1551 wfProfileIn( $fname.'-prefixhandling' );
1552 if ( preg_match( $e2, $s, $m ) ) {
1560 $prefix = $first_prefix;
1561 $first_prefix = false;
1563 wfProfileOut( $fname.'-prefixhandling' );
1566 $might_be_img = false;
1568 wfProfileIn( "$fname-e1" );
1569 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1571 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1572 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1573 # the real problem is with the $e1 regex
1576 # Still some problems for cases where the ] is meant to be outside punctuation,
1577 # and no image is in sight. See bug 2095.
1580 substr( $m[3], 0, 1 ) === ']' &&
1581 strpos($text, '[') !== false
1584 $text .= ']'; # so that replaceExternalLinks($text) works later
1585 $m[3] = substr( $m[3], 1 );
1587 # fix up urlencoded title texts
1588 if( strpos( $m[1], '%' ) !== false ) {
1589 # Should anchors '#' also be rejected?
1590 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1593 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1594 $might_be_img = true;
1596 if ( strpos( $m[1], '%' ) !== false ) {
1597 $m[1] = urldecode($m[1]);
1600 } else { # Invalid form; output directly
1601 $s .= $prefix . '[[' . $line ;
1602 wfProfileOut( "$fname-e1" );
1605 wfProfileOut( "$fname-e1" );
1606 wfProfileIn( "$fname-misc" );
1608 # Don't allow internal links to pages containing
1609 # PROTO: where PROTO is a valid URL protocol; these
1610 # should be external links.
1611 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1612 $s .= $prefix . '[[' . $line ;
1616 # Make subpage if necessary
1617 if( $useSubpages ) {
1618 $link = $this->maybeDoSubpageLink( $m[1], $text );
1623 $noforce = (substr($m[1], 0, 1) != ':');
1625 # Strip off leading ':'
1626 $link = substr($link, 1);
1629 wfProfileOut( "$fname-misc" );
1630 wfProfileIn( "$fname-title" );
1631 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1633 $s .= $prefix . '[[' . $line;
1634 wfProfileOut( "$fname-title" );
1638 $ns = $nt->getNamespace();
1639 $iw = $nt->getInterWiki();
1640 wfProfileOut( "$fname-title" );
1642 if ($might_be_img) { # if this is actually an invalid link
1643 wfProfileIn( "$fname-might_be_img" );
1644 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1646 while (isset ($a[$k+
1]) ) {
1647 #look at the next 'line' to see if we can close it there
1648 $spliced = array_splice( $a, $k +
1, 1 );
1649 $next_line = array_shift( $spliced );
1650 $m = explode( ']]', $next_line, 3 );
1651 if ( count( $m ) == 3 ) {
1652 # the first ]] closes the inner link, the second the image
1654 $text .= "[[{$m[0]}]]{$m[1]}";
1657 } elseif ( count( $m ) == 2 ) {
1658 #if there's exactly one ]] that's fine, we'll keep looking
1659 $text .= "[[{$m[0]}]]{$m[1]}";
1661 #if $next_line is invalid too, we need look no further
1662 $text .= '[[' . $next_line;
1667 # we couldn't find the end of this imageLink, so output it raw
1668 #but don't ignore what might be perfectly normal links in the text we've examined
1669 $text = $this->replaceInternalLinks($text);
1670 $s .= "{$prefix}[[$link|$text";
1671 # note: no $trail, because without an end, there *is* no trail
1672 wfProfileOut( "$fname-might_be_img" );
1675 } else { #it's not an image, so output it raw
1676 $s .= "{$prefix}[[$link|$text";
1677 # note: no $trail, because without an end, there *is* no trail
1678 wfProfileOut( "$fname-might_be_img" );
1681 wfProfileOut( "$fname-might_be_img" );
1684 $wasblank = ( '' == $text );
1685 if( $wasblank ) $text = $link;
1687 # Link not escaped by : , create the various objects
1691 wfProfileIn( "$fname-interwiki" );
1692 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1693 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1694 $s = rtrim($s . $prefix);
1695 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1696 wfProfileOut( "$fname-interwiki" );
1699 wfProfileOut( "$fname-interwiki" );
1701 if ( $ns == NS_IMAGE
) {
1702 wfProfileIn( "$fname-image" );
1703 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1704 # recursively parse links inside the image caption
1705 # actually, this will parse them in any other parameters, too,
1706 # but it might be hard to fix that, and it doesn't matter ATM
1707 $text = $this->replaceExternalLinks($text);
1708 $text = $this->replaceInternalLinks($text);
1710 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1711 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1712 $this->mOutput
->addImage( $nt->getDBkey() );
1714 wfProfileOut( "$fname-image" );
1717 # We still need to record the image's presence on the page
1718 $this->mOutput
->addImage( $nt->getDBkey() );
1720 wfProfileOut( "$fname-image" );
1724 if ( $ns == NS_CATEGORY
) {
1725 wfProfileIn( "$fname-category" );
1726 $s = rtrim($s . "\n"); # bug 87
1729 $sortkey = $this->getDefaultSort();
1733 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1734 $sortkey = str_replace( "\n", '', $sortkey );
1735 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1736 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1739 * Strip the whitespace Category links produce, see bug 87
1740 * @todo We might want to use trim($tmp, "\n") here.
1742 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1744 wfProfileOut( "$fname-category" );
1749 # Self-link checking
1750 if( $nt->getFragment() === '' ) {
1751 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1752 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1757 # Special and Media are pseudo-namespaces; no pages actually exist in them
1758 if( $ns == NS_MEDIA
) {
1759 $link = $sk->makeMediaLinkObj( $nt, $text );
1760 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1761 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1762 $this->mOutput
->addImage( $nt->getDBkey() );
1764 } elseif( $ns == NS_SPECIAL
) {
1765 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1766 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1768 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1771 } elseif( $ns == NS_IMAGE
) {
1772 $img = wfFindFile( $nt );
1774 // Force a blue link if the file exists; may be a remote
1775 // upload on the shared repository, and we want to see its
1776 // auto-generated page.
1777 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1778 $this->mOutput
->addLink( $nt );
1782 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1784 wfProfileOut( $fname );
1789 * Make a link placeholder. The text returned can be later resolved to a real link with
1790 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1791 * parsing of interwiki links, and secondly to allow all existence checks and
1792 * article length checks (for stub links) to be bundled into a single query.
1795 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1796 wfProfileIn( __METHOD__
);
1797 if ( ! is_object($nt) ) {
1799 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1801 # Separate the link trail from the rest of the link
1802 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1804 if ( $nt->isExternal() ) {
1805 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1806 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1807 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1809 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1810 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1811 $this->mLinkHolders
['queries'][] = $query;
1812 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1813 $this->mLinkHolders
['titles'][] = $nt;
1815 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1818 wfProfileOut( __METHOD__
);
1823 * Render a forced-blue link inline; protect against double expansion of
1824 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1825 * Since this little disaster has to split off the trail text to avoid
1826 * breaking URLs in the following text without breaking trails on the
1827 * wiki links, it's been made into a horrible function.
1830 * @param string $text
1831 * @param string $query
1832 * @param string $trail
1833 * @param string $prefix
1834 * @return string HTML-wikitext mix oh yuck
1836 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1837 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1838 $sk = $this->mOptions
->getSkin();
1839 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1840 return $this->armorLinks( $link ) . $trail;
1844 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1845 * going to go through further parsing steps before inline URL expansion.
1847 * In particular this is important when using action=render, which causes
1848 * full URLs to be included.
1850 * Oh man I hate our multi-layer parser!
1852 * @param string more-or-less HTML
1853 * @return string less-or-more HTML with NOPARSE bits
1855 function armorLinks( $text ) {
1856 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1857 "{$this->mUniqPrefix}NOPARSE$1", $text );
1861 * Return true if subpage links should be expanded on this page.
1864 function areSubpagesAllowed() {
1865 # Some namespaces don't allow subpages
1866 global $wgNamespacesWithSubpages;
1867 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1871 * Handle link to subpage if necessary
1872 * @param string $target the source of the link
1873 * @param string &$text the link text, modified as necessary
1874 * @return string the full name of the link
1877 function maybeDoSubpageLink($target, &$text) {
1880 # :Foobar -- override special treatment of prefix (images, language links)
1881 # /Foobar -- convert to CurrentPage/Foobar
1882 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1883 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1884 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1886 $fname = 'Parser::maybeDoSubpageLink';
1887 wfProfileIn( $fname );
1888 $ret = $target; # default return value is no change
1890 # Some namespaces don't allow subpages,
1891 # so only perform processing if subpages are allowed
1892 if( $this->areSubpagesAllowed() ) {
1893 $hash = strpos( $target, '#' );
1894 if( $hash !== false ) {
1895 $suffix = substr( $target, $hash );
1896 $target = substr( $target, 0, $hash );
1901 $target = trim( $target );
1902 # Look at the first character
1903 if( $target != '' && $target{0} == '/' ) {
1904 # / at end means we don't want the slash to be shown
1906 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1907 if( $trailingSlashes ) {
1908 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1910 $noslash = substr( $target, 1 );
1913 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1914 if( '' === $text ) {
1915 $text = $target . $suffix;
1916 } # this might be changed for ugliness reasons
1918 # check for .. subpage backlinks
1920 $nodotdot = $target;
1921 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1923 $nodotdot = substr( $nodotdot, 3 );
1925 if($dotdotcount > 0) {
1926 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1927 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1928 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1929 # / at the end means don't show full path
1930 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1931 $nodotdot = substr( $nodotdot, 0, -1 );
1932 if( '' === $text ) {
1933 $text = $nodotdot . $suffix;
1936 $nodotdot = trim( $nodotdot );
1937 if( $nodotdot != '' ) {
1938 $ret .= '/' . $nodotdot;
1946 wfProfileOut( $fname );
1951 * Used by doBlockLevels()
1954 /* private */ function closeParagraph() {
1956 if ( '' != $this->mLastSection
) {
1957 $result = '</' . $this->mLastSection
. ">\n";
1959 $this->mInPre
= false;
1960 $this->mLastSection
= '';
1963 # getCommon() returns the length of the longest common substring
1964 # of both arguments, starting at the beginning of both.
1966 /* private */ function getCommon( $st1, $st2 ) {
1967 $fl = strlen( $st1 );
1968 $shorter = strlen( $st2 );
1969 if ( $fl < $shorter ) { $shorter = $fl; }
1971 for ( $i = 0; $i < $shorter; ++
$i ) {
1972 if ( $st1{$i} != $st2{$i} ) { break; }
1976 # These next three functions open, continue, and close the list
1977 # element appropriate to the prefix character passed into them.
1979 /* private */ function openList( $char ) {
1980 $result = $this->closeParagraph();
1982 if ( '*' == $char ) { $result .= '<ul><li>'; }
1983 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1984 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1985 else if ( ';' == $char ) {
1986 $result .= '<dl><dt>';
1987 $this->mDTopen
= true;
1989 else { $result = '<!-- ERR 1 -->'; }
1994 /* private */ function nextItem( $char ) {
1995 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1996 else if ( ':' == $char ||
';' == $char ) {
1998 if ( $this->mDTopen
) { $close = '</dt>'; }
1999 if ( ';' == $char ) {
2000 $this->mDTopen
= true;
2001 return $close . '<dt>';
2003 $this->mDTopen
= false;
2004 return $close . '<dd>';
2007 return '<!-- ERR 2 -->';
2010 /* private */ function closeList( $char ) {
2011 if ( '*' == $char ) { $text = '</li></ul>'; }
2012 else if ( '#' == $char ) { $text = '</li></ol>'; }
2013 else if ( ':' == $char ) {
2014 if ( $this->mDTopen
) {
2015 $this->mDTopen
= false;
2016 $text = '</dt></dl>';
2018 $text = '</dd></dl>';
2021 else { return '<!-- ERR 3 -->'; }
2027 * Make lists from lines starting with ':', '*', '#', etc.
2030 * @return string the lists rendered as HTML
2032 function doBlockLevels( $text, $linestart ) {
2033 $fname = 'Parser::doBlockLevels';
2034 wfProfileIn( $fname );
2036 # Parsing through the text line by line. The main thing
2037 # happening here is handling of block-level elements p, pre,
2038 # and making lists from lines starting with * # : etc.
2040 $textLines = explode( "\n", $text );
2042 $lastPrefix = $output = '';
2043 $this->mDTopen
= $inBlockElem = false;
2045 $paragraphStack = false;
2047 if ( !$linestart ) {
2048 $output .= array_shift( $textLines );
2050 foreach ( $textLines as $oLine ) {
2051 $lastPrefixLength = strlen( $lastPrefix );
2052 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2053 $preOpenMatch = preg_match('/<pre/i', $oLine );
2054 if ( !$this->mInPre
) {
2055 # Multiple prefixes may abut each other for nested lists.
2056 $prefixLength = strspn( $oLine, '*#:;' );
2057 $pref = substr( $oLine, 0, $prefixLength );
2060 $pref2 = str_replace( ';', ':', $pref );
2061 $t = substr( $oLine, $prefixLength );
2062 $this->mInPre
= !empty($preOpenMatch);
2064 # Don't interpret any other prefixes in preformatted text
2066 $pref = $pref2 = '';
2071 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2072 # Same as the last item, so no need to deal with nesting or opening stuff
2073 $output .= $this->nextItem( substr( $pref, -1 ) );
2074 $paragraphStack = false;
2076 if ( substr( $pref, -1 ) == ';') {
2077 # The one nasty exception: definition lists work like this:
2078 # ; title : definition text
2079 # So we check for : in the remainder text to split up the
2080 # title and definition, without b0rking links.
2082 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2084 $output .= $term . $this->nextItem( ':' );
2087 } elseif( $prefixLength ||
$lastPrefixLength ) {
2088 # Either open or close a level...
2089 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2090 $paragraphStack = false;
2092 while( $commonPrefixLength < $lastPrefixLength ) {
2093 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2094 --$lastPrefixLength;
2096 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2097 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2099 while ( $prefixLength > $commonPrefixLength ) {
2100 $char = substr( $pref, $commonPrefixLength, 1 );
2101 $output .= $this->openList( $char );
2103 if ( ';' == $char ) {
2104 # FIXME: This is dupe of code above
2105 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2107 $output .= $term . $this->nextItem( ':' );
2110 ++
$commonPrefixLength;
2112 $lastPrefix = $pref2;
2114 if( 0 == $prefixLength ) {
2115 wfProfileIn( "$fname-paragraph" );
2116 # No prefix (not in list)--go to paragraph mode
2117 // XXX: use a stack for nestable elements like span, table and div
2118 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2119 $closematch = preg_match(
2120 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2121 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2122 if ( $openmatch or $closematch ) {
2123 $paragraphStack = false;
2124 #Â TODO bug 5718: paragraph closed
2125 $output .= $this->closeParagraph();
2126 if ( $preOpenMatch and !$preCloseMatch ) {
2127 $this->mInPre
= true;
2129 if ( $closematch ) {
2130 $inBlockElem = false;
2132 $inBlockElem = true;
2134 } else if ( !$inBlockElem && !$this->mInPre
) {
2135 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2137 if ($this->mLastSection
!= 'pre') {
2138 $paragraphStack = false;
2139 $output .= $this->closeParagraph().'<pre>';
2140 $this->mLastSection
= 'pre';
2142 $t = substr( $t, 1 );
2145 if ( '' == trim($t) ) {
2146 if ( $paragraphStack ) {
2147 $output .= $paragraphStack.'<br />';
2148 $paragraphStack = false;
2149 $this->mLastSection
= 'p';
2151 if ($this->mLastSection
!= 'p' ) {
2152 $output .= $this->closeParagraph();
2153 $this->mLastSection
= '';
2154 $paragraphStack = '<p>';
2156 $paragraphStack = '</p><p>';
2160 if ( $paragraphStack ) {
2161 $output .= $paragraphStack;
2162 $paragraphStack = false;
2163 $this->mLastSection
= 'p';
2164 } else if ($this->mLastSection
!= 'p') {
2165 $output .= $this->closeParagraph().'<p>';
2166 $this->mLastSection
= 'p';
2171 wfProfileOut( "$fname-paragraph" );
2173 // somewhere above we forget to get out of pre block (bug 785)
2174 if($preCloseMatch && $this->mInPre
) {
2175 $this->mInPre
= false;
2177 if ($paragraphStack === false) {
2181 while ( $prefixLength ) {
2182 $output .= $this->closeList( $pref2{$prefixLength-1} );
2185 if ( '' != $this->mLastSection
) {
2186 $output .= '</' . $this->mLastSection
. '>';
2187 $this->mLastSection
= '';
2190 wfProfileOut( $fname );
2195 * Split up a string on ':', ignoring any occurences inside tags
2196 * to prevent illegal overlapping.
2197 * @param string $str the string to split
2198 * @param string &$before set to everything before the ':'
2199 * @param string &$after set to everything after the ':'
2200 * return string the position of the ':', or false if none found
2202 function findColonNoLinks($str, &$before, &$after) {
2203 $fname = 'Parser::findColonNoLinks';
2204 wfProfileIn( $fname );
2206 $pos = strpos( $str, ':' );
2207 if( $pos === false ) {
2209 wfProfileOut( $fname );
2213 $lt = strpos( $str, '<' );
2214 if( $lt === false ||
$lt > $pos ) {
2215 // Easy; no tag nesting to worry about
2216 $before = substr( $str, 0, $pos );
2217 $after = substr( $str, $pos+
1 );
2218 wfProfileOut( $fname );
2222 // Ugly state machine to walk through avoiding tags.
2223 $state = self
::COLON_STATE_TEXT
;
2225 $len = strlen( $str );
2226 for( $i = 0; $i < $len; $i++
) {
2230 // (Using the number is a performance hack for common cases)
2231 case 0: // self::COLON_STATE_TEXT:
2234 // Could be either a <start> tag or an </end> tag
2235 $state = self
::COLON_STATE_TAGSTART
;
2240 $before = substr( $str, 0, $i );
2241 $after = substr( $str, $i +
1 );
2242 wfProfileOut( $fname );
2245 // Embedded in a tag; don't break it.
2248 // Skip ahead looking for something interesting
2249 $colon = strpos( $str, ':', $i );
2250 if( $colon === false ) {
2251 // Nothing else interesting
2252 wfProfileOut( $fname );
2255 $lt = strpos( $str, '<', $i );
2256 if( $stack === 0 ) {
2257 if( $lt === false ||
$colon < $lt ) {
2259 $before = substr( $str, 0, $colon );
2260 $after = substr( $str, $colon +
1 );
2261 wfProfileOut( $fname );
2265 if( $lt === false ) {
2266 // Nothing else interesting to find; abort!
2267 // We're nested, but there's no close tags left. Abort!
2270 // Skip ahead to next tag start
2272 $state = self
::COLON_STATE_TAGSTART
;
2275 case 1: // self::COLON_STATE_TAG:
2280 $state = self
::COLON_STATE_TEXT
;
2283 // Slash may be followed by >?
2284 $state = self
::COLON_STATE_TAGSLASH
;
2290 case 2: // self::COLON_STATE_TAGSTART:
2293 $state = self
::COLON_STATE_CLOSETAG
;
2296 $state = self
::COLON_STATE_COMMENT
;
2299 // Illegal early close? This shouldn't happen D:
2300 $state = self
::COLON_STATE_TEXT
;
2303 $state = self
::COLON_STATE_TAG
;
2306 case 3: // self::COLON_STATE_CLOSETAG:
2311 wfDebug( "Invalid input in $fname; too many close tags\n" );
2312 wfProfileOut( $fname );
2315 $state = self
::COLON_STATE_TEXT
;
2318 case self
::COLON_STATE_TAGSLASH
:
2320 // Yes, a self-closed tag <blah/>
2321 $state = self
::COLON_STATE_TEXT
;
2323 // Probably we're jumping the gun, and this is an attribute
2324 $state = self
::COLON_STATE_TAG
;
2327 case 5: // self::COLON_STATE_COMMENT:
2329 $state = self
::COLON_STATE_COMMENTDASH
;
2332 case self
::COLON_STATE_COMMENTDASH
:
2334 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2336 $state = self
::COLON_STATE_COMMENT
;
2339 case self
::COLON_STATE_COMMENTDASHDASH
:
2341 $state = self
::COLON_STATE_TEXT
;
2343 $state = self
::COLON_STATE_COMMENT
;
2347 throw new MWException( "State machine error in $fname" );
2351 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2354 wfProfileOut( $fname );
2359 * Return value of a magic variable (like PAGENAME)
2363 function getVariableValue( $index ) {
2364 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2367 * Some of these require message or data lookups and can be
2368 * expensive to check many times.
2370 static $varCache = array();
2371 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2372 if ( isset( $varCache[$index] ) ) {
2373 return $varCache[$index];
2378 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2381 global $wgLocaltimezone;
2382 if ( isset( $wgLocaltimezone ) ) {
2383 $oldtz = getenv( 'TZ' );
2384 putenv( 'TZ='.$wgLocaltimezone );
2387 wfSuppressWarnings(); // E_STRICT system time bitching
2388 $localTimestamp = date( 'YmdHis', $ts );
2389 $localMonth = date( 'm', $ts );
2390 $localMonthName = date( 'n', $ts );
2391 $localDay = date( 'j', $ts );
2392 $localDay2 = date( 'd', $ts );
2393 $localDayOfWeek = date( 'w', $ts );
2394 $localWeek = date( 'W', $ts );
2395 $localYear = date( 'Y', $ts );
2396 $localHour = date( 'H', $ts );
2397 if ( isset( $wgLocaltimezone ) ) {
2398 putenv( 'TZ='.$oldtz );
2400 wfRestoreWarnings();
2403 case 'currentmonth':
2404 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2405 case 'currentmonthname':
2406 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2407 case 'currentmonthnamegen':
2408 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2409 case 'currentmonthabbrev':
2410 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2412 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2414 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2416 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2417 case 'localmonthname':
2418 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2419 case 'localmonthnamegen':
2420 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2421 case 'localmonthabbrev':
2422 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2424 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2426 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2428 return wfEscapeWikiText( $this->mTitle
->getText() );
2430 return $this->mTitle
->getPartialURL();
2431 case 'fullpagename':
2432 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2433 case 'fullpagenamee':
2434 return $this->mTitle
->getPrefixedURL();
2436 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2437 case 'subpagenamee':
2438 return $this->mTitle
->getSubpageUrlForm();
2439 case 'basepagename':
2440 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2441 case 'basepagenamee':
2442 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2443 case 'talkpagename':
2444 if( $this->mTitle
->canTalk() ) {
2445 $talkPage = $this->mTitle
->getTalkPage();
2446 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2450 case 'talkpagenamee':
2451 if( $this->mTitle
->canTalk() ) {
2452 $talkPage = $this->mTitle
->getTalkPage();
2453 return $talkPage->getPrefixedUrl();
2457 case 'subjectpagename':
2458 $subjPage = $this->mTitle
->getSubjectPage();
2459 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2460 case 'subjectpagenamee':
2461 $subjPage = $this->mTitle
->getSubjectPage();
2462 return $subjPage->getPrefixedUrl();
2464 // Let the edit saving system know we should parse the page
2465 // *after* a revision ID has been assigned.
2466 $this->mOutput
->setFlag( 'vary-revision' );
2467 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2468 return $this->mRevisionId
;
2470 // Let the edit saving system know we should parse the page
2471 // *after* a revision ID has been assigned. This is for null edits.
2472 $this->mOutput
->setFlag( 'vary-revision' );
2473 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2474 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2475 case 'revisionday2':
2476 // Let the edit saving system know we should parse the page
2477 // *after* a revision ID has been assigned. This is for null edits.
2478 $this->mOutput
->setFlag( 'vary-revision' );
2479 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2480 return substr( $this->getRevisionTimestamp(), 6, 2 );
2481 case 'revisionmonth':
2482 // Let the edit saving system know we should parse the page
2483 // *after* a revision ID has been assigned. This is for null edits.
2484 $this->mOutput
->setFlag( 'vary-revision' );
2485 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2486 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2487 case 'revisionyear':
2488 // Let the edit saving system know we should parse the page
2489 // *after* a revision ID has been assigned. This is for null edits.
2490 $this->mOutput
->setFlag( 'vary-revision' );
2491 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2492 return substr( $this->getRevisionTimestamp(), 0, 4 );
2493 case 'revisiontimestamp':
2494 // Let the edit saving system know we should parse the page
2495 // *after* a revision ID has been assigned. This is for null edits.
2496 $this->mOutput
->setFlag( 'vary-revision' );
2497 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2498 return $this->getRevisionTimestamp();
2500 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2502 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2504 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2506 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2507 case 'subjectspace':
2508 return $this->mTitle
->getSubjectNsText();
2509 case 'subjectspacee':
2510 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2511 case 'currentdayname':
2512 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2514 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2516 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2518 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2520 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2521 // int to remove the padding
2522 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2524 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2525 case 'localdayname':
2526 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2528 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2530 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2532 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2534 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2535 // int to remove the padding
2536 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2538 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2539 case 'numberofarticles':
2540 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2541 case 'numberoffiles':
2542 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2543 case 'numberofusers':
2544 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2545 case 'numberofpages':
2546 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2547 case 'numberofadmins':
2548 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2549 case 'numberofedits':
2550 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2551 case 'currenttimestamp':
2552 return $varCache[$index] = wfTimestampNow();
2553 case 'localtimestamp':
2554 return $varCache[$index] = $localTimestamp;
2555 case 'currentversion':
2556 return $varCache[$index] = SpecialVersion
::getVersion();
2562 return $wgServerName;
2564 return $wgScriptPath;
2565 case 'directionmark':
2566 return $wgContLang->getDirMark();
2567 case 'contentlanguage':
2568 global $wgContLanguageCode;
2569 return $wgContLanguageCode;
2572 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2580 * initialise the magic variables (like CURRENTMONTHNAME)
2584 function initialiseVariables() {
2585 $fname = 'Parser::initialiseVariables';
2586 wfProfileIn( $fname );
2587 $variableIDs = MagicWord
::getVariableIDs();
2589 $this->mVariables
= new MagicWordArray( $variableIDs );
2590 wfProfileOut( $fname );
2594 * Preprocess some wikitext and return the document tree.
2595 * This is the ghost of replace_variables().
2597 * @param string $text The text to parse
2598 * @param integer flags Bitwise combination of:
2599 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2600 * included. Default is to assume a direct page view.
2602 * The generated DOM tree must depend only on the input text and the flags.
2603 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2605 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2606 * change in the DOM tree for a given text, must be passed through the section identifier
2607 * in the section edit link and thus back to extractSections().
2609 * The output of this function is currently only cached in process memory, but a persistent
2610 * cache may be implemented at a later date which takes further advantage of these strict
2611 * dependency requirements.
2615 function preprocessToDom ( $text, $flags = 0 ) {
2616 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2621 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2623 public static function splitWhitespace( $s ) {
2624 $ltrimmed = ltrim( $s );
2625 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2626 $trimmed = rtrim( $ltrimmed );
2627 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2629 $w2 = substr( $ltrimmed, -$diff );
2633 return array( $w1, $trimmed, $w2 );
2637 * Replace magic variables, templates, and template arguments
2638 * with the appropriate text. Templates are substituted recursively,
2639 * taking care to avoid infinite loops.
2641 * Note that the substitution depends on value of $mOutputType:
2642 * OT_WIKI: only {{subst:}} templates
2643 * OT_PREPROCESS: templates but not extension tags
2644 * OT_HTML: all templates and extension tags
2646 * @param string $tex The text to transform
2647 * @param PPFrame $frame Object describing the arguments passed to the template
2648 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2651 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2652 # Prevent too big inclusions
2653 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2657 $fname = __METHOD__
;
2658 wfProfileIn( $fname );
2660 if ( $frame === false ) {
2661 $frame = $this->getPreprocessor()->newFrame();
2662 } elseif ( !( $frame instanceof PPFrame
) ) {
2663 throw new MWException( __METHOD__
. ' called using the old argument format' );
2666 $dom = $this->preprocessToDom( $text );
2667 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2668 $text = $frame->expand( $dom, $flags );
2670 wfProfileOut( $fname );
2674 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2675 static function createAssocArgs( $args ) {
2676 $assocArgs = array();
2678 foreach( $args as $arg ) {
2679 $eqpos = strpos( $arg, '=' );
2680 if ( $eqpos === false ) {
2681 $assocArgs[$index++
] = $arg;
2683 $name = trim( substr( $arg, 0, $eqpos ) );
2684 $value = trim( substr( $arg, $eqpos+
1 ) );
2685 if ( $value === false ) {
2688 if ( $name !== false ) {
2689 $assocArgs[$name] = $value;
2698 * Return the text of a template, after recursively
2699 * replacing any variables or templates within the template.
2701 * @param array $piece The parts of the template
2702 * $piece['title']: the title, i.e. the part before the |
2703 * $piece['parts']: the parameter array
2704 * $piece['lineStart']: whether the brace was at the start of a line
2705 * @param PPFrame The current frame, contains template arguments
2706 * @return string the text of the template
2709 function braceSubstitution( $piece, $frame ) {
2710 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2711 $fname = __METHOD__
;
2712 wfProfileIn( $fname );
2713 wfProfileIn( __METHOD__
.'-setup' );
2716 $found = false; # $text has been filled
2717 $nowiki = false; # wiki markup in $text should be escaped
2718 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2719 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2720 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2721 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2723 # Title object, where $text came from
2726 # $part1 is the bit before the first |, and must contain only title characters.
2727 # Various prefixes will be stripped from it later.
2728 $titleWithSpaces = $frame->expand( $piece['title'] );
2729 $part1 = trim( $titleWithSpaces );
2732 # Original title text preserved for various purposes
2733 $originalTitle = $part1;
2735 # $args is a list of argument nodes, starting from index 0, not including $part1
2736 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2737 wfProfileOut( __METHOD__
.'-setup' );
2740 wfProfileIn( __METHOD__
.'-modifiers' );
2742 $mwSubst =& MagicWord
::get( 'subst' );
2743 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2744 # One of two possibilities is true:
2745 # 1) Found SUBST but not in the PST phase
2746 # 2) Didn't find SUBST and in the PST phase
2747 # In either case, return without further processing
2748 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2755 if ( !$found && $args->getLength() == 0 ) {
2756 $id = $this->mVariables
->matchStartToEnd( $part1 );
2757 if ( $id !== false ) {
2758 $text = $this->getVariableValue( $id );
2759 if (MagicWord
::getCacheTTL($id)>-1)
2760 $this->mOutput
->mContainsOldMagic
= true;
2765 # MSG, MSGNW and RAW
2768 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2769 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2772 # Remove obsolete MSG:
2773 $mwMsg =& MagicWord
::get( 'msg' );
2774 $mwMsg->matchStartAndRemove( $part1 );
2778 $mwRaw =& MagicWord
::get( 'raw' );
2779 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2780 $forceRawInterwiki = true;
2783 wfProfileOut( __METHOD__
.'-modifiers' );
2787 wfProfileIn( __METHOD__
. '-pfunc' );
2789 $colonPos = strpos( $part1, ':' );
2790 if ( $colonPos !== false ) {
2791 # Case sensitive functions
2792 $function = substr( $part1, 0, $colonPos );
2793 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2794 $function = $this->mFunctionSynonyms
[1][$function];
2796 # Case insensitive functions
2797 $function = strtolower( $function );
2798 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2799 $function = $this->mFunctionSynonyms
[0][$function];
2805 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2806 $initialArgs = array( &$this );
2807 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2808 if ( $flags & SFH_OBJECT_ARGS
) {
2809 # Add a frame parameter, and pass the arguments as an array
2810 $allArgs = $initialArgs;
2811 $allArgs[] = $frame;
2812 for ( $i = 0; $i < $args->getLength(); $i++
) {
2813 $funcArgs[] = $args->item( $i );
2815 $allArgs[] = $funcArgs;
2817 # Convert arguments to plain text
2818 for ( $i = 0; $i < $args->getLength(); $i++
) {
2819 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2821 $allArgs = array_merge( $initialArgs, $funcArgs );
2824 $result = call_user_func_array( $callback, $allArgs );
2827 if ( is_array( $result ) ) {
2828 if ( isset( $result[0] ) ) {
2830 unset( $result[0] );
2833 // Extract flags into the local scope
2834 // This allows callers to set flags such as nowiki, found, etc.
2841 wfProfileOut( __METHOD__
. '-pfunc' );
2844 # Finish mangling title and then check for loops.
2845 # Set $title to a Title object and $titleText to the PDBK
2848 # Split the title into page and subpage
2850 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2851 if ($subpage !== '') {
2852 $ns = $this->mTitle
->getNamespace();
2854 $title = Title
::newFromText( $part1, $ns );
2856 $titleText = $title->getPrefixedText();
2857 # Check for language variants if the template is not found
2858 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2859 $wgContLang->findVariantLink($part1, $title);
2861 # Do infinite loop check
2862 if ( !$frame->loopCheck( $title ) ) {
2864 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2865 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2867 # Do recursion depth check
2868 $limit = $this->mOptions
->getMaxTemplateDepth();
2869 if ( $frame->depth
>= $limit ) {
2871 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2876 # Load from database
2877 if ( !$found && $title ) {
2878 wfProfileIn( __METHOD__
. '-loadtpl' );
2879 if ( !$title->isExternal() ) {
2880 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2881 $text = SpecialPage
::capturePath( $title );
2882 if ( is_string( $text ) ) {
2885 $this->disableCache();
2887 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2888 $found = false; //access denied
2889 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2891 list( $text, $title ) = $this->getTemplateDom( $title );
2892 if ( $text !== false ) {
2898 # If the title is valid but undisplayable, make a link to it
2899 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2900 $text = "[[:$titleText]]";
2903 } elseif ( $title->isTrans() ) {
2904 // Interwiki transclusion
2905 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2906 $text = $this->interwikiTransclude( $title, 'render' );
2909 $text = $this->interwikiTransclude( $title, 'raw' );
2910 // Preprocess it like a template
2911 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2916 wfProfileOut( __METHOD__
. '-loadtpl' );
2919 # If we haven't found text to substitute by now, we're done
2920 # Recover the source wikitext and return it
2922 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2923 wfProfileOut( $fname );
2924 return array( 'object' => $text );
2927 # Expand DOM-style return values in a child frame
2928 if ( $isChildObj ) {
2929 # Clean up argument array
2930 $newFrame = $frame->newChild( $args, $title );
2932 if ( $titleText !== false && $newFrame->isEmpty() ) {
2933 # Expansion is eligible for the empty-frame cache
2934 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2935 $text = $this->mTplExpandCache
[$titleText];
2937 $text = $newFrame->expand( $text );
2938 $this->mTplExpandCache
[$titleText] = $text;
2941 # Uncached expansion
2942 $text = $newFrame->expand( $text );
2946 # Replace raw HTML by a placeholder
2947 # Add a blank line preceding, to prevent it from mucking up
2948 # immediately preceding headings
2950 $text = "\n\n" . $this->insertStripItem( $text );
2952 # Escape nowiki-style return values
2953 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2954 $text = wfEscapeWikiText( $text );
2956 # Bug 529: if the template begins with a table or block-level
2957 # element, it should be treated as beginning a new line.
2958 # This behaviour is somewhat controversial.
2959 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2960 $text = "\n" . $text;
2963 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2964 # Error, oversize inclusion
2965 $text = "[[$originalTitle]]" .
2966 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2969 if ( $isLocalObj ) {
2970 $ret = array( 'object' => $text );
2972 $ret = array( 'text' => $text );
2975 wfProfileOut( $fname );
2980 * Get the semi-parsed DOM representation of a template with a given title,
2981 * and its redirect destination title. Cached.
2983 function getTemplateDom( $title ) {
2984 $cacheTitle = $title;
2985 $titleText = $title->getPrefixedDBkey();
2987 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2988 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2989 $title = Title
::makeTitle( $ns, $dbk );
2990 $titleText = $title->getPrefixedDBkey();
2992 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2993 return array( $this->mTplDomCache
[$titleText], $title );
2996 // Cache miss, go to the database
2997 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2999 if ( $text === false ) {
3000 $this->mTplDomCache
[$titleText] = false;
3001 return array( false, $title );
3004 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3005 $this->mTplDomCache
[ $titleText ] = $dom;
3007 if (! $title->equals($cacheTitle)) {
3008 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3009 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3012 return array( $dom, $title );
3016 * Fetch the unparsed text of a template and register a reference to it.
3018 function fetchTemplateAndTitle( $title ) {
3019 $templateCb = $this->mOptions
->getTemplateCallback();
3020 $stuff = call_user_func( $templateCb, $title );
3021 $text = $stuff['text'];
3022 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3023 if ( isset( $stuff['deps'] ) ) {
3024 foreach ( $stuff['deps'] as $dep ) {
3025 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3028 return array($text,$finalTitle);
3031 function fetchTemplate( $title ) {
3032 $rv = $this->fetchTemplateAndTitle($title);
3037 * Static function to get a template
3038 * Can be overridden via ParserOptions::setTemplateCallback().
3040 static function statelessFetchTemplate( $title ) {
3041 $text = $skip = false;
3042 $finalTitle = $title;
3045 // Loop to fetch the article, with up to 1 redirect
3046 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3047 # Give extensions a chance to select the revision instead
3048 $id = false; // Assume current
3049 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3055 'page_id' => $title->getArticleID(),
3059 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3060 $rev_id = $rev ?
$rev->getId() : 0;
3064 'page_id' => $title->getArticleID(),
3065 'rev_id' => $rev_id );
3068 $text = $rev->getText();
3069 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3071 $message = $wgLang->lcfirst( $title->getText() );
3072 $text = wfMsgForContentNoTrans( $message );
3073 if( wfEmptyMsg( $message, $text ) ) {
3080 if ( $text === false ) {
3084 $finalTitle = $title;
3085 $title = Title
::newFromRedirect( $text );
3089 'finalTitle' => $finalTitle,
3094 * Transclude an interwiki link.
3096 function interwikiTransclude( $title, $action ) {
3097 global $wgEnableScaryTranscluding;
3099 if (!$wgEnableScaryTranscluding)
3100 return wfMsg('scarytranscludedisabled');
3102 $url = $title->getFullUrl( "action=$action" );
3104 if (strlen($url) > 255)
3105 return wfMsg('scarytranscludetoolong');
3106 return $this->fetchScaryTemplateMaybeFromCache($url);
3109 function fetchScaryTemplateMaybeFromCache($url) {
3110 global $wgTranscludeCacheExpiry;
3111 $dbr = wfGetDB(DB_SLAVE
);
3112 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3113 array('tc_url' => $url));
3115 $time = $obj->tc_time
;
3116 $text = $obj->tc_contents
;
3117 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3122 $text = Http
::get($url);
3124 return wfMsg('scarytranscludefailed', $url);
3126 $dbw = wfGetDB(DB_MASTER
);
3127 $dbw->replace('transcache', array('tc_url'), array(
3129 'tc_time' => time(),
3130 'tc_contents' => $text));
3136 * Triple brace replacement -- used for template arguments
3139 function argSubstitution( $piece, $frame ) {
3140 wfProfileIn( __METHOD__
);
3143 $parts = $piece['parts'];
3144 $nameWithSpaces = $frame->expand( $piece['title'] );
3145 $argName = trim( $nameWithSpaces );
3147 $text = $frame->getArgument( $argName );
3148 if ( $text === false && ( $this->ot
['html'] ||
$this->ot
['pre'] ) && $parts->getLength() > 0 ) {
3149 # No match in frame, use the supplied default
3150 $object = $parts->item( 0 )->getChildren();
3152 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3153 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3156 if ( $text === false && $object === false ) {
3158 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3160 if ( $error !== false ) {
3163 if ( $object !== false ) {
3164 $ret = array( 'object' => $object );
3166 $ret = array( 'text' => $text );
3169 wfProfileOut( __METHOD__
);
3174 * Return the text to be used for a given extension tag.
3175 * This is the ghost of strip().
3177 * @param array $params Associative array of parameters:
3178 * name PPNode for the tag name
3179 * attr PPNode for unparsed text where tag attributes are thought to be
3180 * attributes Optional associative array of parsed attributes
3181 * inner Contents of extension element
3182 * noClose Original text did not have a close tag
3183 * @param PPFrame $frame
3185 function extensionSubstitution( $params, $frame ) {
3186 global $wgRawHtml, $wgContLang;
3189 $name = $frame->expand( $params['name'] );
3190 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3191 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3193 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
3195 if ( $this->ot
['html'] ) {
3196 $name = strtolower( $name );
3198 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3199 if ( isset( $params['attributes'] ) ) {
3200 $attributes = $attributes +
$params['attributes'];
3208 throw new MWException( '<html> extension tag encountered unexpectedly' );
3211 $output = Xml
::escapeTagsOnly( $content );
3214 $output = $wgContLang->armourMath(
3215 MathRenderer
::renderMath( $content, $attributes ) );
3218 $output = $this->renderImageGallery( $content, $attributes );
3221 if( isset( $this->mTagHooks
[$name] ) ) {
3222 $output = call_user_func_array( $this->mTagHooks
[$name],
3223 array( $content, $attributes, $this ) );
3225 throw new MWException( "Invalid call hook $name" );
3229 if ( is_null( $attrText ) ) {
3232 if ( isset( $params['attributes'] ) ) {
3233 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3234 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3235 htmlspecialchars( $attrValue ) . '"';
3238 if ( $content === null ) {
3239 $output = "<$name$attrText/>";
3241 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3242 $output = "<$name$attrText>$content$close";
3246 if ( $name == 'html' ||
$name == 'nowiki' ) {
3247 $this->mStripState
->nowiki
->setPair( $marker, $output );
3249 $this->mStripState
->general
->setPair( $marker, $output );
3255 * Increment an include size counter
3257 * @param string $type The type of expansion
3258 * @param integer $size The size of the text
3259 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3261 function incrementIncludeSize( $type, $size ) {
3262 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3265 $this->mIncludeSizes
[$type] +
= $size;
3271 * Detect __NOGALLERY__ magic word and set a placeholder
3273 function stripNoGallery( &$text ) {
3274 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3276 $mw = MagicWord
::get( 'nogallery' );
3277 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3281 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3282 * placeholder that will then be replaced by the real TOC in
3283 * ->formatHeadings, this works because at this points real
3284 * comments will have already been discarded by the sanitizer.
3286 * Any additional __TOC__ magic words left over will be discarded
3287 * as there can only be one TOC on the page.
3289 function stripToc( $text ) {
3290 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3292 $mw = MagicWord
::get( 'notoc' );
3293 if( $mw->matchAndRemove( $text ) ) {
3294 $this->mShowToc
= false;
3297 $mw = MagicWord
::get( 'toc' );
3298 if( $mw->match( $text ) ) {
3299 $this->mShowToc
= true;
3300 $this->mForceTocPosition
= true;
3302 // Set a placeholder. At the end we'll fill it in with the TOC.
3303 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3305 // Only keep the first one.
3306 $text = $mw->replace( '', $text );
3312 * This function accomplishes several tasks:
3313 * 1) Auto-number headings if that option is enabled
3314 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3315 * 3) Add a Table of contents on the top for users who have enabled the option
3316 * 4) Auto-anchor headings
3318 * It loops through all headlines, collects the necessary data, then splits up the
3319 * string and re-inserts the newly formatted headlines.
3321 * @param string $text
3322 * @param boolean $isMain
3325 function formatHeadings( $text, $isMain=true ) {
3326 global $wgMaxTocLevel, $wgContLang;
3328 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3329 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3332 $showEditLink = $this->mOptions
->getEditSection();
3335 # Inhibit editsection links if requested in the page
3336 $esw =& MagicWord
::get( 'noeditsection' );
3337 if( $esw->matchAndRemove( $text ) ) {
3341 # Get all headlines for numbering them and adding funky stuff like [edit]
3342 # links - this is for later, but we need the number of headlines right now
3344 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3346 # if there are fewer than 4 headlines in the article, do not show TOC
3347 # unless it's been explicitly enabled.
3348 $enoughToc = $this->mShowToc
&&
3349 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3351 # Allow user to stipulate that a page should have a "new section"
3352 # link added via __NEWSECTIONLINK__
3353 $mw =& MagicWord
::get( 'newsectionlink' );
3354 if( $mw->matchAndRemove( $text ) )
3355 $this->mOutput
->setNewSection( true );
3357 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3358 # override above conditions and always show TOC above first header
3359 $mw =& MagicWord
::get( 'forcetoc' );
3360 if ($mw->matchAndRemove( $text ) ) {
3361 $this->mShowToc
= true;
3365 # We need this to perform operations on the HTML
3366 $sk = $this->mOptions
->getSkin();
3372 # Ugh .. the TOC should have neat indentation levels which can be
3373 # passed to the skin functions. These are determined here
3377 $sublevelCount = array();
3378 $levelCount = array();
3384 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3385 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3388 foreach( $matches[3] as $headline ) {
3389 $isTemplate = false;
3391 $sectionIndex = false;
3393 $markerMatches = array();
3394 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3395 $serial = $markerMatches[1];
3396 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3397 $isTemplate = ($titleText != $baseTitleText);
3398 $headline = preg_replace("/^$markerRegex/", "", $headline);
3402 $prevlevel = $level;
3403 $prevtoclevel = $toclevel;
3405 $level = $matches[1][$headlineCount];
3407 if( $doNumberHeadings ||
$enoughToc ) {
3409 if ( $level > $prevlevel ) {
3410 # Increase TOC level
3412 $sublevelCount[$toclevel] = 0;
3413 if( $toclevel<$wgMaxTocLevel ) {
3414 $prevtoclevel = $toclevel;
3415 $toc .= $sk->tocIndent();
3419 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3420 # Decrease TOC level, find level to jump to
3422 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3423 # Can only go down to level 1
3426 for ($i = $toclevel; $i > 0; $i--) {
3427 if ( $levelCount[$i] == $level ) {
3428 # Found last matching level
3432 elseif ( $levelCount[$i] < $level ) {
3433 # Found first matching level below current level
3439 if( $toclevel<$wgMaxTocLevel ) {
3440 if($prevtoclevel < $wgMaxTocLevel) {
3441 # Unindent only if the previous toc level was shown :p
3442 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3444 $toc .= $sk->tocLineEnd();
3449 # No change in level, end TOC line
3450 if( $toclevel<$wgMaxTocLevel ) {
3451 $toc .= $sk->tocLineEnd();
3455 $levelCount[$toclevel] = $level;
3457 # count number of headlines for each level
3458 @$sublevelCount[$toclevel]++
;
3460 for( $i = 1; $i <= $toclevel; $i++
) {
3461 if( !empty( $sublevelCount[$i] ) ) {
3465 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3471 # The safe header is a version of the header text safe to use for links
3472 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3473 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3475 # Remove link placeholders by the link text.
3476 # <!--LINK number-->
3478 # link text with suffix
3479 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3480 "\$this->mLinkHolders['texts'][\$1]",
3482 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3483 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3486 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3487 $tocline = preg_replace(
3488 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3492 $tocline = trim( $tocline );
3494 # For the anchor, strip out HTML-y stuff period
3495 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3496 $safeHeadline = trim( $safeHeadline );
3498 # Save headline for section edit hint before it's escaped
3499 $headlineHint = $safeHeadline;
3500 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3501 $refers[$headlineCount] = $safeHeadline;
3503 # count how many in assoc. array so we can track dupes in anchors
3504 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3505 $refcount[$headlineCount] = $refers[$safeHeadline];
3507 # Don't number the heading if it is the only one (looks silly)
3508 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3509 # the two are different if the line contains a link
3510 $headline=$numbering . ' ' . $headline;
3513 # Create the anchor for linking from the TOC to the section
3514 $anchor = $safeHeadline;
3515 if($refcount[$headlineCount] > 1 ) {
3516 $anchor .= '_' . $refcount[$headlineCount];
3518 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3519 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3520 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3522 # give headline the correct <h#> tag
3523 if( $showEditLink && $sectionIndex !== false ) {
3525 # Put a T flag in the section identifier, to indicate to extractSections()
3526 # that sections inside <includeonly> should be counted.
3527 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3529 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3534 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3539 $this->mOutput
->setSections( $tocraw );
3541 # Never ever show TOC if no headers
3542 if( $numVisible < 1 ) {
3547 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3548 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3550 $toc = $sk->tocList( $toc );
3553 # split up and insert constructed headlines
3555 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3558 foreach( $blocks as $block ) {
3559 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3560 # This is the [edit] link that appears for the top block of text when
3561 # section editing is enabled
3563 # Disabled because it broke block formatting
3564 # For example, a bullet point in the top line
3565 # $full .= $sk->editSectionLink(0);
3568 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3569 # Top anchor now in skin
3573 if( !empty( $head[$i] ) ) {
3578 if( $this->mForceTocPosition
) {
3579 return str_replace( '<!--MWTOC-->', $toc, $full );
3586 * Transform wiki markup when saving a page by doing \r\n -> \n
3587 * conversion, substitting signatures, {{subst:}} templates, etc.
3589 * @param string $text the text to transform
3590 * @param Title &$title the Title object for the current article
3591 * @param User &$user the User object describing the current user
3592 * @param ParserOptions $options parsing options
3593 * @param bool $clearState whether to clear the parser state first
3594 * @return string the altered wiki markup
3597 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3598 $this->mOptions
= $options;
3599 $this->setTitle( $title );
3600 $this->setOutputType( OT_WIKI
);
3602 if ( $clearState ) {
3603 $this->clearState();
3609 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3610 $text = $this->pstPass2( $text, $user );
3611 $text = $this->mStripState
->unstripBoth( $text );
3616 * Pre-save transform helper function
3619 function pstPass2( $text, $user ) {
3620 global $wgContLang, $wgLocaltimezone;
3622 /* Note: This is the timestamp saved as hardcoded wikitext to
3623 * the database, we use $wgContLang here in order to give
3624 * everyone the same signature and use the default one rather
3625 * than the one selected in each user's preferences.
3627 if ( isset( $wgLocaltimezone ) ) {
3628 $oldtz = getenv( 'TZ' );
3629 putenv( 'TZ='.$wgLocaltimezone );
3631 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3632 ' (' . date( 'T' ) . ')';
3633 if ( isset( $wgLocaltimezone ) ) {
3634 putenv( 'TZ='.$oldtz );
3637 # Variable replacement
3638 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3639 $text = $this->replaceVariables( $text );
3641 # Strip out <nowiki> etc. added via replaceVariables
3642 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
3645 $sigText = $this->getUserSig( $user );
3646 $text = strtr( $text, array(
3648 '~~~~' => "$sigText $d",
3652 # Context links: [[|name]] and [[name (context)|]]
3654 global $wgLegalTitleChars;
3655 $tc = "[$wgLegalTitleChars]";
3656 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3658 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3659 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3660 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3662 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3663 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3664 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3666 $t = $this->mTitle
->getText();
3668 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3669 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3670 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3671 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3673 # if there's no context, don't bother duplicating the title
3674 $text = preg_replace( $p2, '[[\\1]]', $text );
3677 # Trim trailing whitespace
3678 $text = rtrim( $text );
3684 * Fetch the user's signature text, if any, and normalize to
3685 * validated, ready-to-insert wikitext.
3691 function getUserSig( &$user ) {
3692 global $wgMaxSigChars;
3694 $username = $user->getName();
3695 $nickname = $user->getOption( 'nickname' );
3696 $nickname = $nickname === '' ?
$username : $nickname;
3698 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3699 $nickname = $username;
3700 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3701 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3702 # Sig. might contain markup; validate this
3703 if( $this->validateSig( $nickname ) !== false ) {
3704 # Validated; clean up (if needed) and return it
3705 return $this->cleanSig( $nickname, true );
3707 # Failed to validate; fall back to the default
3708 $nickname = $username;
3709 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3713 // Make sure nickname doesnt get a sig in a sig
3714 $nickname = $this->cleanSigInSig( $nickname );
3716 # If we're still here, make it a link to the user page
3717 $userText = wfEscapeWikiText( $username );
3718 $nickText = wfEscapeWikiText( $nickname );
3719 if ( $user->isAnon() ) {
3720 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3722 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3727 * Check that the user's signature contains no bad XML
3729 * @param string $text
3730 * @return mixed An expanded string, or false if invalid.
3732 function validateSig( $text ) {
3733 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3737 * Clean up signature text
3739 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3740 * 2) Substitute all transclusions
3742 * @param string $text
3743 * @param $parsing Whether we're cleaning (preferences save) or parsing
3744 * @return string Signature text
3746 function cleanSig( $text, $parsing = false ) {
3749 $this->clearState();
3750 $this->setTitle( $wgTitle );
3751 $this->mOptions
= new ParserOptions
;
3752 $this->setOutputType
= OT_PREPROCESS
;
3755 # FIXME: regex doesn't respect extension tags or nowiki
3756 # => Move this logic to braceSubstitution()
3757 $substWord = MagicWord
::get( 'subst' );
3758 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3759 $substText = '{{' . $substWord->getSynonym( 0 );
3761 $text = preg_replace( $substRegex, $substText, $text );
3762 $text = $this->cleanSigInSig( $text );
3763 $dom = $this->preprocessToDom( $text );
3764 $frame = $this->getPreprocessor()->newFrame();
3765 $text = $frame->expand( $dom );
3768 $text = $this->mStripState
->unstripBoth( $text );
3775 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3776 * @param string $text
3777 * @return string Signature text with /~{3,5}/ removed
3779 function cleanSigInSig( $text ) {
3780 $text = preg_replace( '/~{3,5}/', '', $text );
3785 * Set up some variables which are usually set up in parse()
3786 * so that an external function can call some class members with confidence
3789 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3790 $this->setTitle( $title );
3791 $this->mOptions
= $options;
3792 $this->setOutputType( $outputType );
3793 if ( $clearState ) {
3794 $this->clearState();
3799 * Wrapper for preprocess()
3801 * @param string $text the text to preprocess
3802 * @param ParserOptions $options options
3806 function transformMsg( $text, $options ) {
3808 static $executing = false;
3810 $fname = "Parser::transformMsg";
3812 # Guard against infinite recursion
3818 wfProfileIn($fname);
3819 $text = $this->preprocess( $text, $wgTitle, $options );
3822 wfProfileOut($fname);
3827 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3828 * The callback should have the following form:
3829 * function myParserHook( $text, $params, &$parser ) { ... }
3831 * Transform and return $text. Use $parser for any required context, e.g. use
3832 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3836 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3837 * @param mixed $callback The callback function (and object) to use for the tag
3839 * @return The old value of the mTagHooks array associated with the hook
3841 function setHook( $tag, $callback ) {
3842 $tag = strtolower( $tag );
3843 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3844 $this->mTagHooks
[$tag] = $callback;
3845 $this->mStripList
[] = $tag;
3850 function setTransparentTagHook( $tag, $callback ) {
3851 $tag = strtolower( $tag );
3852 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3853 $this->mTransparentTagHooks
[$tag] = $callback;
3859 * Remove all tag hooks
3861 function clearTagHooks() {
3862 $this->mTagHooks
= array();
3863 $this->mStripList
= $this->mDefaultStripList
;
3867 * Create a function, e.g. {{sum:1|2|3}}
3868 * The callback function should have the form:
3869 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3871 * The callback may either return the text result of the function, or an array with the text
3872 * in element 0, and a number of flags in the other elements. The names of the flags are
3873 * specified in the keys. Valid flags are:
3874 * found The text returned is valid, stop processing the template. This
3876 * nowiki Wiki markup in the return value should be escaped
3877 * isHTML The returned text is HTML, armour it against wikitext transformation
3881 * @param string $id The magic word ID
3882 * @param mixed $callback The callback function (and object) to use
3883 * @param integer $flags a combination of the following flags:
3884 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3886 * @return The old callback function for this name, if any
3888 function setFunctionHook( $id, $callback, $flags = 0 ) {
3889 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3890 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3892 # Add to function cache
3893 $mw = MagicWord
::get( $id );
3895 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3897 $synonyms = $mw->getSynonyms();
3898 $sensitive = intval( $mw->isCaseSensitive() );
3900 foreach ( $synonyms as $syn ) {
3902 if ( !$sensitive ) {
3903 $syn = strtolower( $syn );
3906 if ( !( $flags & SFH_NO_HASH
) ) {
3909 # Remove trailing colon
3910 if ( substr( $syn, -1, 1 ) == ':' ) {
3911 $syn = substr( $syn, 0, -1 );
3913 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3919 * Get all registered function hook identifiers
3923 function getFunctionHooks() {
3924 return array_keys( $this->mFunctionHooks
);
3928 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3929 * Placeholders created in Skin::makeLinkObj()
3930 * Returns an array of link CSS classes, indexed by PDBK.
3931 * $options is a bit field, RLH_FOR_UPDATE to select for update
3933 function replaceLinkHolders( &$text, $options = 0 ) {
3937 $fname = 'Parser::replaceLinkHolders';
3938 wfProfileIn( $fname );
3942 $linkcolour_ids = array();
3943 $sk = $this->mOptions
->getSkin();
3944 $linkCache =& LinkCache
::singleton();
3946 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3947 wfProfileIn( $fname.'-check' );
3948 $dbr = wfGetDB( DB_SLAVE
);
3949 $page = $dbr->tableName( 'page' );
3950 $threshold = $wgUser->getOption('stubthreshold');
3953 asort( $this->mLinkHolders
['namespaces'] );
3958 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3960 $title = $this->mLinkHolders
['titles'][$key];
3962 # Skip invalid entries.
3963 # Result will be ugly, but prevents crash.
3964 if ( is_null( $title ) ) {
3967 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3969 # Check if it's a static known link, e.g. interwiki
3970 if ( $title->isAlwaysKnown() ) {
3971 $colours[$pdbk] = '';
3972 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3973 $colours[$pdbk] = '';
3974 $this->mOutput
->addLink( $title, $id );
3975 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3976 $colours[$pdbk] = 'new';
3977 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
3978 $colours[$pdbk] = 'new';
3980 # Not in the link cache, add it to the query
3981 if ( !isset( $current ) ) {
3983 $query = "SELECT page_id, page_namespace, page_title";
3984 if ( $threshold > 0 ) {
3985 $query .= ', page_len, page_is_redirect';
3987 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3988 } elseif ( $current != $ns ) {
3990 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3995 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4000 if ( $options & RLH_FOR_UPDATE
) {
4001 $query .= ' FOR UPDATE';
4004 $res = $dbr->query( $query, $fname );
4006 # Fetch data and form into an associative array
4007 # non-existent = broken
4008 while ( $s = $dbr->fetchObject($res) ) {
4009 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4010 $pdbk = $title->getPrefixedDBkey();
4011 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4012 $this->mOutput
->addLink( $title, $s->page_id
);
4013 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4014 //add id to the extension todolist
4015 $linkcolour_ids[$s->page_id
] = $pdbk;
4017 //pass an array of page_ids to an extension
4018 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4020 wfProfileOut( $fname.'-check' );
4022 # Do a second query for different language variants of links and categories
4023 if($wgContLang->hasVariants()){
4024 $linkBatch = new LinkBatch();
4025 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4026 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4027 $varCategories = array(); // category replacements oldDBkey => newDBkey
4029 $categories = $this->mOutput
->getCategoryLinks();
4031 // Add variants of links to link batch
4032 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4033 $title = $this->mLinkHolders
['titles'][$key];
4034 if ( is_null( $title ) )
4037 $pdbk = $title->getPrefixedDBkey();
4038 $titleText = $title->getText();
4040 // generate all variants of the link title text
4041 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4043 // if link was not found (in first query), add all variants to query
4044 if ( !isset($colours[$pdbk]) ){
4045 foreach($allTextVariants as $textVariant){
4046 if($textVariant != $titleText){
4047 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4048 if(is_null($variantTitle)) continue;
4049 $linkBatch->addObj( $variantTitle );
4050 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4056 // process categories, check if a category exists in some variant
4057 foreach( $categories as $category ){
4058 $variants = $wgContLang->convertLinkToAllVariants($category);
4059 foreach($variants as $variant){
4060 if($variant != $category){
4061 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4062 if(is_null($variantTitle)) continue;
4063 $linkBatch->addObj( $variantTitle );
4064 $categoryMap[$variant] = $category;
4070 if(!$linkBatch->isEmpty()){
4072 $titleClause = $linkBatch->constructSet('page', $dbr);
4074 $variantQuery = "SELECT page_id, page_namespace, page_title";
4075 if ( $threshold > 0 ) {
4076 $variantQuery .= ', page_len, page_is_redirect';
4079 $variantQuery .= " FROM $page WHERE $titleClause";
4080 if ( $options & RLH_FOR_UPDATE
) {
4081 $variantQuery .= ' FOR UPDATE';
4084 $varRes = $dbr->query( $variantQuery, $fname );
4086 // for each found variants, figure out link holders and replace
4087 while ( $s = $dbr->fetchObject($varRes) ) {
4089 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4090 $varPdbk = $variantTitle->getPrefixedDBkey();
4091 $vardbk = $variantTitle->getDBkey();
4093 $holderKeys = array();
4094 if(isset($variantMap[$varPdbk])){
4095 $holderKeys = $variantMap[$varPdbk];
4096 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4097 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4100 // loop over link holders
4101 foreach($holderKeys as $key){
4102 $title = $this->mLinkHolders
['titles'][$key];
4103 if ( is_null( $title ) ) continue;
4105 $pdbk = $title->getPrefixedDBkey();
4107 if(!isset($colours[$pdbk])){
4108 // found link in some of the variants, replace the link holder data
4109 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4110 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4112 // set pdbk and colour
4113 $pdbks[$key] = $varPdbk;
4114 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4115 $linkcolour_ids[$s->page_id
] = $pdbk;
4117 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4120 // check if the object is a variant of a category
4121 if(isset($categoryMap[$vardbk])){
4122 $oldkey = $categoryMap[$vardbk];
4123 if($oldkey != $vardbk)
4124 $varCategories[$oldkey]=$vardbk;
4128 // rebuild the categories in original order (if there are replacements)
4129 if(count($varCategories)>0){
4131 $originalCats = $this->mOutput
->getCategories();
4132 foreach($originalCats as $cat => $sortkey){
4133 // make the replacement
4134 if( array_key_exists($cat,$varCategories) )
4135 $newCats[$varCategories[$cat]] = $sortkey;
4136 else $newCats[$cat] = $sortkey;
4138 $this->mOutput
->setCategoryLinks($newCats);
4143 # Construct search and replace arrays
4144 wfProfileIn( $fname.'-construct' );
4145 $replacePairs = array();
4146 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4147 $pdbk = $pdbks[$key];
4148 $searchkey = "<!--LINK $key-->";
4149 $title = $this->mLinkHolders
['titles'][$key];
4150 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4151 $linkCache->addBadLinkObj( $title );
4152 $colours[$pdbk] = 'new';
4153 $this->mOutput
->addLink( $title, 0 );
4154 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4155 $this->mLinkHolders
['texts'][$key],
4156 $this->mLinkHolders
['queries'][$key] );
4158 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4159 $this->mLinkHolders
['texts'][$key],
4160 $this->mLinkHolders
['queries'][$key] );
4163 $replacer = new HashtableReplacer( $replacePairs, 1 );
4164 wfProfileOut( $fname.'-construct' );
4167 wfProfileIn( $fname.'-replace' );
4168 $text = preg_replace_callback(
4169 '/(<!--LINK .*?-->)/',
4173 wfProfileOut( $fname.'-replace' );
4176 # Now process interwiki link holders
4177 # This is quite a bit simpler than internal links
4178 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4179 wfProfileIn( $fname.'-interwiki' );
4180 # Make interwiki link HTML
4181 $replacePairs = array();
4182 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4183 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4184 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4186 $replacer = new HashtableReplacer( $replacePairs, 1 );
4188 $text = preg_replace_callback(
4189 '/<!--IWLINK (.*?)-->/',
4192 wfProfileOut( $fname.'-interwiki' );
4195 wfProfileOut( $fname );
4200 * Replace <!--LINK--> link placeholders with plain text of links
4201 * (not HTML-formatted).
4202 * @param string $text
4205 function replaceLinkHoldersText( $text ) {
4206 $fname = 'Parser::replaceLinkHoldersText';
4207 wfProfileIn( $fname );
4209 $text = preg_replace_callback(
4210 '/<!--(LINK|IWLINK) (.*?)-->/',
4211 array( &$this, 'replaceLinkHoldersTextCallback' ),
4214 wfProfileOut( $fname );
4219 * @param array $matches
4223 function replaceLinkHoldersTextCallback( $matches ) {
4224 $type = $matches[1];
4226 if( $type == 'LINK' ) {
4227 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4228 return $this->mLinkHolders
['texts'][$key];
4230 } elseif( $type == 'IWLINK' ) {
4231 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4232 return $this->mInterwikiLinkHolders
['texts'][$key];
4239 * Tag hook handler for 'pre'.
4241 function renderPreTag( $text, $attribs ) {
4242 // Backwards-compatibility hack
4243 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4245 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4246 return wfOpenElement( 'pre', $attribs ) .
4247 Xml
::escapeTagsOnly( $content ) .
4252 * Renders an image gallery from a text with one line per image.
4253 * text labels may be given by using |-style alternative text. E.g.
4254 * Image:one.jpg|The number "1"
4255 * Image:tree.jpg|A tree
4256 * given as text will return the HTML of a gallery with two images,
4257 * labeled 'The number "1"' and
4260 function renderImageGallery( $text, $params ) {
4261 $ig = new ImageGallery();
4262 $ig->setContextTitle( $this->mTitle
);
4263 $ig->setShowBytes( false );
4264 $ig->setShowFilename( false );
4265 $ig->setParser( $this );
4266 $ig->setHideBadImages();
4267 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4268 $ig->useSkin( $this->mOptions
->getSkin() );
4269 $ig->mRevisionId
= $this->mRevisionId
;
4271 if( isset( $params['caption'] ) ) {
4272 $caption = $params['caption'];
4273 $caption = htmlspecialchars( $caption );
4274 $caption = $this->replaceInternalLinks( $caption );
4275 $ig->setCaptionHtml( $caption );
4277 if( isset( $params['perrow'] ) ) {
4278 $ig->setPerRow( $params['perrow'] );
4280 if( isset( $params['widths'] ) ) {
4281 $ig->setWidths( $params['widths'] );
4283 if( isset( $params['heights'] ) ) {
4284 $ig->setHeights( $params['heights'] );
4287 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4289 $lines = explode( "\n", $text );
4290 foreach ( $lines as $line ) {
4291 # match lines like these:
4292 # Image:someimage.jpg|This is some image
4294 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4296 if ( count( $matches ) == 0 ) {
4299 $tp = Title
::newFromText( $matches[1] );
4301 if( is_null( $nt ) ) {
4302 # Bogus title. Ignore these so we don't bomb out later.
4305 if ( isset( $matches[3] ) ) {
4306 $label = $matches[3];
4311 $html = $this->recursiveTagParse( trim( $label ) );
4313 $ig->add( $nt, $html );
4315 # Only add real images (bug #5586)
4316 if ( $nt->getNamespace() == NS_IMAGE
) {
4317 $this->mOutput
->addImage( $nt->getDBkey() );
4320 return $ig->toHTML();
4323 function getImageParams( $handler ) {
4325 $handlerClass = get_class( $handler );
4329 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4330 // Initialise static lists
4331 static $internalParamNames = array(
4332 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4333 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4334 'bottom', 'text-bottom' ),
4335 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4336 'upright', 'border' ),
4338 static $internalParamMap;
4339 if ( !$internalParamMap ) {
4340 $internalParamMap = array();
4341 foreach ( $internalParamNames as $type => $names ) {
4342 foreach ( $names as $name ) {
4343 $magicName = str_replace( '-', '_', "img_$name" );
4344 $internalParamMap[$magicName] = array( $type, $name );
4349 // Add handler params
4350 $paramMap = $internalParamMap;
4352 $handlerParamMap = $handler->getParamMap();
4353 foreach ( $handlerParamMap as $magic => $paramName ) {
4354 $paramMap[$magic] = array( 'handler', $paramName );
4357 $this->mImageParams
[$handlerClass] = $paramMap;
4358 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4360 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4364 * Parse image options text and use it to make an image
4366 function makeImage( $title, $options ) {
4367 # @TODO: let the MediaHandler specify its transform parameters
4369 # Check if the options text is of the form "options|alt text"
4371 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4372 # * left no resizing, just left align. label is used for alt= only
4373 # * right same, but right aligned
4374 # * none same, but not aligned
4375 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4376 # * center center the image
4377 # * framed Keep original image size, no magnify-button.
4378 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4379 # * upright reduce width for upright images, rounded to full __0 px
4380 # * border draw a 1px border around the image
4381 # vertical-align values (no % or length right now):
4391 $parts = array_map( 'trim', explode( '|', $options) );
4392 $sk = $this->mOptions
->getSkin();
4394 # Give extensions a chance to select the file revision for us
4395 $skip = $time = false;
4396 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4399 return $sk->makeLinkObj( $title );
4403 $file = wfFindFile( $title, $time );
4404 $handler = $file ?
$file->getHandler() : false;
4406 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4408 # Process the input parameters
4410 $params = array( 'frame' => array(), 'handler' => array(),
4411 'horizAlign' => array(), 'vertAlign' => array() );
4412 foreach( $parts as $part ) {
4413 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4414 if ( isset( $paramMap[$magicName] ) ) {
4415 list( $type, $paramName ) = $paramMap[$magicName];
4416 $params[$type][$paramName] = $value;
4418 // Special case; width and height come in one variable together
4419 if( $type == 'handler' && $paramName == 'width' ) {
4421 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4422 $params[$type]['width'] = intval( $m[1] );
4423 $params[$type]['height'] = intval( $m[2] );
4425 $params[$type]['width'] = intval( $value );
4433 # Process alignment parameters
4434 if ( $params['horizAlign'] ) {
4435 $params['frame']['align'] = key( $params['horizAlign'] );
4437 if ( $params['vertAlign'] ) {
4438 $params['frame']['valign'] = key( $params['vertAlign'] );
4441 # Validate the handler parameters
4443 foreach ( $params['handler'] as $name => $value ) {
4444 if ( !$handler->validateParam( $name, $value ) ) {
4445 unset( $params['handler'][$name] );
4450 # Strip bad stuff out of the alt text
4451 $alt = $this->replaceLinkHoldersText( $caption );
4453 # make sure there are no placeholders in thumbnail attributes
4454 # that are later expanded to html- so expand them now and
4456 $alt = $this->mStripState
->unstripBoth( $alt );
4457 $alt = Sanitizer
::stripAllTags( $alt );
4459 $params['frame']['alt'] = $alt;
4460 $params['frame']['caption'] = $caption;
4462 # Linker does the rest
4463 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4465 # Give the handler a chance to modify the parser object
4467 $handler->parserTransformHook( $this, $file );
4474 * Set a flag in the output object indicating that the content is dynamic and
4475 * shouldn't be cached.
4477 function disableCache() {
4478 wfDebug( "Parser output marked as uncacheable.\n" );
4479 $this->mOutput
->mCacheTime
= -1;
4483 * Callback from the Sanitizer for expanding items found in HTML attribute
4484 * values, so they can be safely tested and escaped.
4485 * @param string $text
4486 * @param PPFrame $frame
4490 function attributeStripCallback( &$text, $frame = false ) {
4491 $text = $this->replaceVariables( $text, $frame );
4492 $text = $this->mStripState
->unstripBoth( $text );
4501 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4502 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4503 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4509 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4514 * Break wikitext input into sections, and either pull or replace
4515 * some particular section's text.
4517 * External callers should use the getSection and replaceSection methods.
4519 * @param string $text Page wikitext
4520 * @param string $section A section identifier string of the form:
4521 * <flag1> - <flag2> - ... - <section number>
4523 * Currently the only recognised flag is "T", which means the target section number
4524 * was derived during a template inclusion parse, in other words this is a template
4525 * section edit link. If no flags are given, it was an ordinary section edit link.
4526 * This flag is required to avoid a section numbering mismatch when a section is
4527 * enclosed by <includeonly> (bug 6563).
4529 * The section number 0 pulls the text before the first heading; other numbers will
4530 * pull the given section along with its lower-level subsections. If the section is
4531 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4533 * @param string $mode One of "get" or "replace"
4534 * @param string $newText Replacement text for section data.
4535 * @return string for "get", the extracted section text.
4536 * for "replace", the whole page with the section replaced.
4538 private function extractSections( $text, $section, $mode, $newText='' ) {
4540 $this->clearState();
4541 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4542 $this->mOptions
= new ParserOptions
;
4543 $this->setOutputType( OT_WIKI
);
4546 $frame = $this->getPreprocessor()->newFrame();
4548 // Process section extraction flags
4550 $sectionParts = explode( '-', $section );
4551 $sectionIndex = array_pop( $sectionParts );
4552 foreach ( $sectionParts as $part ) {
4553 if ( $part == 'T' ) {
4554 $flags |
= self
::PTD_FOR_INCLUSION
;
4557 // Preprocess the text
4558 $root = $this->preprocessToDom( $text, $flags );
4560 // <h> nodes indicate section breaks
4561 // They can only occur at the top level, so we can find them by iterating the root's children
4562 $node = $root->getFirstChild();
4564 // Find the target section
4565 if ( $sectionIndex == 0 ) {
4566 // Section zero doesn't nest, level=big
4567 $targetLevel = 1000;
4570 if ( $node->getName() == 'h' ) {
4571 if ( $curIndex +
1 == $sectionIndex ) {
4576 if ( $mode == 'replace' ) {
4577 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4579 $node = $node->getNextSibling();
4582 $bits = $node->splitHeading();
4583 $targetLevel = $bits['level'];
4589 if ( $mode == 'get' ) {
4596 // Find the end of the section, including nested sections
4598 if ( $node->getName() == 'h' ) {
4600 $bits = $node->splitHeading();
4601 $curLevel = $bits['level'];
4602 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
4606 if ( $mode == 'get' ) {
4607 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4609 $node = $node->getNextSibling();
4612 // Write out the remainder (in replace mode only)
4613 if ( $mode == 'replace' ) {
4614 // Output the replacement text
4615 // Add two newlines on -- trailing whitespace in $newText is conventionally
4616 // stripped by the editor, so we need both newlines to restore the paragraph gap
4617 $outText .= $newText . "\n\n";
4619 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4620 $node = $node->getNextSibling();
4624 if ( is_string( $outText ) ) {
4625 // Re-insert stripped tags
4626 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4633 * This function returns the text of a section, specified by a number ($section).
4634 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4635 * the first section before any such heading (section 0).
4637 * If a section contains subsections, these are also returned.
4639 * @param string $text text to look in
4640 * @param string $section section identifier
4641 * @param string $deftext default to return if section is not found
4642 * @return string text of the requested section
4644 public function getSection( $text, $section, $deftext='' ) {
4645 return $this->extractSections( $text, $section, "get", $deftext );
4648 public function replaceSection( $oldtext, $section, $text ) {
4649 return $this->extractSections( $oldtext, $section, "replace", $text );
4653 * Get the timestamp associated with the current revision, adjusted for
4654 * the default server-local timestamp
4656 function getRevisionTimestamp() {
4657 if ( is_null( $this->mRevisionTimestamp
) ) {
4658 wfProfileIn( __METHOD__
);
4660 $dbr = wfGetDB( DB_SLAVE
);
4661 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4662 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4664 // Normalize timestamp to internal MW format for timezone processing.
4665 // This has the added side-effect of replacing a null value with
4666 // the current time, which gives us more sensible behavior for
4668 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4670 // The cryptic '' timezone parameter tells to use the site-default
4671 // timezone offset instead of the user settings.
4673 // Since this value will be saved into the parser cache, served
4674 // to other users, and potentially even used inside links and such,
4675 // it needs to be consistent for all visitors.
4676 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4678 wfProfileOut( __METHOD__
);
4680 return $this->mRevisionTimestamp
;
4684 * Mutator for $mDefaultSort
4686 * @param $sort New value
4688 public function setDefaultSort( $sort ) {
4689 $this->mDefaultSort
= $sort;
4693 * Accessor for $mDefaultSort
4694 * Will use the title/prefixed title if none is set
4698 public function getDefaultSort() {
4699 if( $this->mDefaultSort
!== false ) {
4700 return $this->mDefaultSort
;
4702 return $this->mTitle
->getNamespace() == NS_CATEGORY
4703 ?
$this->mTitle
->getText()
4704 : $this->mTitle
->getPrefixedText();
4709 * Try to guess the section anchor name based on a wikitext fragment
4710 * presumably extracted from a heading, for example "Header" from
4713 public function guessSectionNameFromWikiText( $text ) {
4714 # Strip out wikitext links(they break the anchor)
4715 $text = $this->stripSectionName( $text );
4716 $headline = Sanitizer
::decodeCharReferences( $text );
4718 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4719 $headline = trim( $headline );
4720 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4721 $replacearray = array(
4726 array_keys( $replacearray ),
4727 array_values( $replacearray ),
4732 * Strips a text string of wikitext for use in a section anchor
4734 * Accepts a text string and then removes all wikitext from the
4735 * string and leaves only the resultant text (i.e. the result of
4736 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4737 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4738 * to create valid section anchors by mimicing the output of the
4739 * parser when headings are parsed.
4741 * @param $text string Text string to be stripped of wikitext
4742 * for use in a Section anchor
4743 * @return Filtered text string
4745 public function stripSectionName( $text ) {
4746 # Strip internal link markup
4747 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4748 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4750 # Strip external link markup (FIXME: Not Tolerant to blank link text
4751 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4752 # on how many empty links there are on the page - need to figure that out.
4753 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4755 # Parse wikitext quotes (italics & bold)
4756 $text = $this->doQuotes($text);
4759 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4763 function srvus( $text ) {
4764 return $this->testSrvus( $text, $this->mOutputType
);
4768 * strip/replaceVariables/unstrip for preprocessor regression testing
4770 function testSrvus( $text, $title, $options, $outputType = OT_HTML
) {
4771 $this->clearState();
4772 $this->mTitle
= $title;
4773 $this->mOptions
= $options;
4774 $this->setOutputType( $outputType );
4775 $text = $this->replaceVariables( $text );
4776 $text = $this->mStripState
->unstripBoth( $text );
4777 $text = Sanitizer
::removeHTMLtags( $text );
4781 function testPst( $text, $title, $options ) {
4783 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4786 function testPreprocess( $text, $title, $options ) {
4787 return $this->testSrvus( $text, $title, $options, OT_PREPROCESS
);
4792 * @todo document, briefly.
4793 * @addtogroup Parser
4796 var $general, $nowiki;
4798 function __construct() {
4799 $this->general
= new ReplacementArray
;
4800 $this->nowiki
= new ReplacementArray
;
4803 function unstripGeneral( $text ) {
4804 wfProfileIn( __METHOD__
);
4807 $text = $this->general
->replace( $text );
4808 } while ( $text != $oldText );
4809 wfProfileOut( __METHOD__
);
4813 function unstripNoWiki( $text ) {
4814 wfProfileIn( __METHOD__
);
4817 $text = $this->nowiki
->replace( $text );
4818 } while ( $text != $oldText );
4819 wfProfileOut( __METHOD__
);
4823 function unstripBoth( $text ) {
4824 wfProfileIn( __METHOD__
);
4827 $text = $this->general
->replace( $text );
4828 $text = $this->nowiki
->replace( $text );
4829 } while ( $text != $oldText );
4830 wfProfileOut( __METHOD__
);
4836 * @todo document, briefly.
4837 * @addtogroup Parser
4839 class OnlyIncludeReplacer
{
4842 function replace( $matches ) {
4843 if ( substr( $matches[1], -1 ) == "\n" ) {
4844 $this->output
.= substr( $matches[1], 0, -1 );
4846 $this->output
.= $matches[1];