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 four main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * performs brace substitution on MediaWiki messages
26 * removes HTML comments and expands templates
29 * objects: $wgLang, $wgContLang
31 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
35 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
36 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * * only within ParserOptions
47 * Update this version number when the ParserOutput format
48 * changes in an incompatible way, so the parser cache
49 * can automatically discard old data.
51 const VERSION
= '1.6.4';
53 # Flags for Parser::setFunctionHook
54 # Also available as global constants from Defines.php
55 const SFH_NO_HASH
= 1;
56 const SFH_OBJECT_ARGS
= 2;
58 # Constants needed for external link processing
59 # Everything except bracket, space, or control characters
60 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
61 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
62 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
64 // State constants for the definition list colon extraction
65 const COLON_STATE_TEXT
= 0;
66 const COLON_STATE_TAG
= 1;
67 const COLON_STATE_TAGSTART
= 2;
68 const COLON_STATE_CLOSETAG
= 3;
69 const COLON_STATE_TAGSLASH
= 4;
70 const COLON_STATE_COMMENT
= 5;
71 const COLON_STATE_COMMENTDASH
= 6;
72 const COLON_STATE_COMMENTDASHDASH
= 7;
74 // Flags for preprocessToDom
75 const PTD_FOR_INCLUSION
= 1;
81 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
82 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
83 $mExtLinkBracketedRegex;
85 # Cleared with clearState():
86 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
87 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
88 var $mInterwikiLinkHolders, $mLinkHolders;
89 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
90 var $mTplExpandCache; // empty-frame expansion cache
91 var $mTplRedirCache, $mTplDomCache, $mHeadings;
94 # These are variables reset at least once per parse regardless of $clearState
95 var $mOptions, // ParserOptions object
96 $mTitle, // Title context, used for self-link rendering and similar things
97 $mOutputType, // Output type, one of the OT_xxx constants
98 $ot, // Shortcut alias, see setOutputType()
99 $mRevisionId, // ID to display in {{REVISIONID}} tags
100 $mRevisionTimestamp, // The timestamp of the specified revision ID
101 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
110 function __construct( $conf = array() ) {
111 $this->mTagHooks
= array();
112 $this->mTransparentTagHooks
= array();
113 $this->mFunctionHooks
= array();
114 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
115 $this->mStripList
= array( 'nowiki', 'gallery' );
116 $this->mMarkerSuffix
= "-QINU\x7f";
117 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
118 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
119 $this->mFirstCall
= true;
123 * Do various kinds of initialisation on the first call of the parser
125 function firstCallInit() {
126 if ( !$this->mFirstCall
) {
130 wfProfileIn( __METHOD__
);
131 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
133 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
135 # Syntax for arguments (see self::setFunctionHook):
136 # "name for lookup in localized magic words array",
138 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
139 # instead of {{#int:...}})
140 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
141 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
142 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
143 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
144 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
165 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'tag', array( 'CoreParserFunctions', 'tagObj' ), SFH_OBJECT_ARGS
);
169 if ( $wgAllowDisplayTitle ) {
170 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
172 if ( $wgAllowSlowParserFunctions ) {
173 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
176 $this->initialiseVariables();
177 $this->mFirstCall
= false;
178 wfProfileOut( __METHOD__
);
186 function clearState() {
187 wfProfileIn( __METHOD__
);
188 if ( $this->mFirstCall
) {
189 $this->firstCallInit();
191 $this->mOutput
= new ParserOutput
;
192 $this->mAutonumber
= 0;
193 $this->mLastSection
= '';
194 $this->mDTopen
= false;
195 $this->mIncludeCount
= array();
196 $this->mStripState
= new StripState
;
197 $this->mArgStack
= false;
198 $this->mInPre
= false;
199 $this->mInterwikiLinkHolders
= array(
203 $this->mLinkHolders
= array(
204 'namespaces' => array(),
206 'queries' => array(),
210 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
213 * Prefix for temporary replacement strings for the multipass parser.
214 * \x07 should never appear in input as it's disallowed in XML.
215 * Using it at the front also gives us a little extra robustness
216 * since it shouldn't match when butted up against identifier-like
219 * Must not consist of all title characters, or else it will change
220 * the behaviour of <nowiki> in a link.
222 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
223 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
225 # Clear these on every parse, bug 4549
226 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
228 $this->mShowToc
= true;
229 $this->mForceTocPosition
= false;
230 $this->mIncludeSizes
= array(
234 $this->mPPNodeCount
= 0;
235 $this->mDefaultSort
= false;
236 $this->mHeadings
= array();
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
242 function setOutputType( $ot ) {
243 $this->mOutputType
= $ot;
246 'html' => $ot == OT_HTML
,
247 'wiki' => $ot == OT_WIKI
,
248 'msg' => $ot == OT_MSG
,
249 'pre' => $ot == OT_PREPROCESS
,
254 * Accessor for mUniqPrefix.
258 function uniqPrefix() {
259 if( !isset( $this->mUniqPrefix
) ) {
260 // @fixme this is probably *horribly wrong*
261 // LanguageConverter seems to want $wgParser's uniqPrefix, however
262 // if this is called for a parser cache hit, the parser may not
263 // have ever been initialized in the first place.
264 // Not really sure what the heck is supposed to be going on here.
266 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
268 return $this->mUniqPrefix
;
272 * Convert wikitext to HTML
273 * Do not call this function recursively.
275 * @param string $text Text we want to parse
276 * @param Title &$title A title object
277 * @param array $options
278 * @param boolean $linestart
279 * @param boolean $clearState
280 * @param int $revid number to pass in {{REVISIONID}}
281 * @return ParserOutput a ParserOutput
283 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
285 * First pass--just handle <nowiki> sections, pass the rest off
286 * to internalParse() which does all the real work.
289 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
290 $fname = 'Parser::parse-' . wfGetCaller();
291 wfProfileIn( __METHOD__
);
292 wfProfileIn( $fname );
298 $this->mOptions
= $options;
299 $this->mTitle
=& $title;
300 $oldRevisionId = $this->mRevisionId
;
301 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
302 if( $revid !== null ) {
303 $this->mRevisionId
= $revid;
304 $this->mRevisionTimestamp
= null;
306 $this->setOutputType( OT_HTML
);
307 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
309 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
310 $text = $this->internalParse( $text );
311 $text = $this->mStripState
->unstripGeneral( $text );
313 # Clean up special characters, only run once, next-to-last before doBlockLevels
315 # french spaces, last one Guillemet-left
316 # only if there is something before the space
317 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
318 # french spaces, Guillemet-right
319 '/(\\302\\253) /' => '\\1 ',
321 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
324 $text = $this->doBlockLevels( $text, $linestart );
326 $this->replaceLinkHolders( $text );
328 # the position of the parserConvert() call should not be changed. it
329 # assumes that the links are all replaced and the only thing left
330 # is the <nowiki> mark.
331 # Side-effects: this calls $this->mOutput->setTitleText()
332 $text = $wgContLang->parserConvert( $text, $this );
334 $text = $this->mStripState
->unstripNoWiki( $text );
336 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
338 //!JF Move to its own function
340 $uniq_prefix = $this->mUniqPrefix
;
342 $elements = array_keys( $this->mTransparentTagHooks
);
343 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
345 foreach( $matches as $marker => $data ) {
346 list( $element, $content, $params, $tag ) = $data;
347 $tagName = strtolower( $element );
348 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
349 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
350 array( $content, $params, $this ) );
354 $this->mStripState
->general
->setPair( $marker, $output );
356 $text = $this->mStripState
->unstripGeneral( $text );
358 $text = Sanitizer
::normalizeCharReferences( $text );
360 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
361 $text = Parser
::tidy($text);
363 # attempt to sanitize at least some nesting problems
364 # (bug #2702 and quite a few others)
366 # ''Something [http://www.cool.com cool''] -->
367 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
368 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
369 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
370 # fix up an anchor inside another anchor, only
371 # at least for a single single nested link (bug 3695)
372 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
373 '\\1\\2</a>\\3</a>\\1\\4</a>',
374 # fix div inside inline elements- doBlockLevels won't wrap a line which
375 # contains a div, so fix it up here; replace
376 # div with escaped text
377 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
378 '\\1\\3<div\\5>\\6</div>\\8\\9',
379 # remove empty italic or bold tag pairs, some
380 # introduced by rules above
381 '/<([bi])><\/\\1>/' => '',
384 $text = preg_replace(
385 array_keys( $tidyregs ),
386 array_values( $tidyregs ),
390 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
392 # Information on include size limits, for the benefit of users who try to skirt them
393 if ( $this->mOptions
->getEnableLimitReport() ) {
394 $max = $this->mOptions
->getMaxIncludeSize();
396 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
397 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
398 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
399 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
400 $text .= "\n<!-- \n$limitReport-->\n";
402 $this->mOutput
->setText( $text );
403 $this->mRevisionId
= $oldRevisionId;
404 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
405 wfProfileOut( $fname );
406 wfProfileOut( __METHOD__
);
408 return $this->mOutput
;
412 * Recursive parser entry point that can be called from an extension tag
415 function recursiveTagParse( $text ) {
416 wfProfileIn( __METHOD__
);
417 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
418 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
419 $text = $this->internalParse( $text );
420 wfProfileOut( __METHOD__
);
425 * Expand templates and variables in the text, producing valid, static wikitext.
426 * Also removes comments.
428 function preprocess( $text, $title, $options, $revid = null ) {
429 wfProfileIn( __METHOD__
);
431 $this->setOutputType( OT_PREPROCESS
);
432 $this->mOptions
= $options;
433 $this->mTitle
= $title;
434 if( $revid !== null ) {
435 $this->mRevisionId
= $revid;
437 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
438 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
439 $text = $this->replaceVariables( $text );
440 if ( $this->mOptions
->getRemoveComments() ) {
441 $text = Sanitizer
::removeHTMLcomments( $text );
443 $text = $this->mStripState
->unstripBoth( $text );
444 wfProfileOut( __METHOD__
);
449 * Get a random string
454 function getRandomString() {
455 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
458 function &getTitle() { return $this->mTitle
; }
459 function getOptions() { return $this->mOptions
; }
461 function getFunctionLang() {
462 global $wgLang, $wgContLang;
463 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
467 * Replaces all occurrences of HTML-style comments and the given tags
468 * in the text with a random marker and returns teh next text. The output
469 * parameter $matches will be an associative array filled with data in
471 * 'UNIQ-xxxxx' => array(
474 * array( 'param' => 'x' ),
475 * '<element param="x">tag content</element>' ) )
477 * @param $elements list of element names. Comments are always extracted.
478 * @param $text Source text string.
479 * @param $uniq_prefix
484 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
489 $taglist = implode( '|', $elements );
490 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
492 while ( '' != $text ) {
493 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
495 if( count( $p ) < 5 ) {
498 if( count( $p ) > 5 ) {
512 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
513 $stripped .= $marker;
515 if ( $close === '/>' ) {
516 // Empty element tag, <tag />
521 if( $element == '!--' ) {
524 $end = "/(<\\/$element\\s*>)/i";
526 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
528 if( count( $q ) < 3 ) {
529 # No end tag -- let it run out to the end of the text.
538 $matches[$marker] = array( $element,
540 Sanitizer
::decodeTagAttributes( $attributes ),
541 "<$element$attributes$close$content$tail" );
547 * Get a list of strippable XML-like elements
549 function getStripList() {
551 $elements = $this->mStripList
;
553 $elements[] = 'html';
555 if( $this->mOptions
->getUseTeX() ) {
556 $elements[] = 'math';
562 * @deprecated use replaceVariables
564 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
569 * Restores pre, math, and other extensions removed by strip()
571 * always call unstripNoWiki() after this one
573 * @deprecated use $this->mStripState->unstrip()
575 function unstrip( $text, $state ) {
576 return $state->unstripGeneral( $text );
580 * Always call this after unstrip() to preserve the order
583 * @deprecated use $this->mStripState->unstrip()
585 function unstripNoWiki( $text, $state ) {
586 return $state->unstripNoWiki( $text );
590 * @deprecated use $this->mStripState->unstripBoth()
592 function unstripForHTML( $text ) {
593 return $this->mStripState
->unstripBoth( $text );
597 * Add an item to the strip state
598 * Returns the unique tag which must be inserted into the stripped text
599 * The tag will be replaced with the original text in unstrip()
603 function insertStripItem( $text ) {
605 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
607 $this->mStripState
->general
->setPair( $rnd, $text );
612 * Interface with html tidy, used if $wgUseTidy = true.
613 * If tidy isn't able to correct the markup, the original will be
614 * returned in all its glory with a warning comment appended.
616 * Either the external tidy program or the in-process tidy extension
617 * will be used depending on availability. Override the default
618 * $wgTidyInternal setting to disable the internal if it's not working.
620 * @param string $text Hideous HTML input
621 * @return string Corrected HTML output
625 function tidy( $text ) {
626 global $wgTidyInternal;
627 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
628 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
629 '<head><title>test</title></head><body>'.$text.'</body></html>';
630 if( $wgTidyInternal ) {
631 $correctedtext = Parser
::internalTidy( $wrappedtext );
633 $correctedtext = Parser
::externalTidy( $wrappedtext );
635 if( is_null( $correctedtext ) ) {
636 wfDebug( "Tidy error detected!\n" );
637 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
639 return $correctedtext;
643 * Spawn an external HTML tidy process and get corrected markup back from it.
648 function externalTidy( $text ) {
649 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
650 $fname = 'Parser::externalTidy';
651 wfProfileIn( $fname );
656 $descriptorspec = array(
657 0 => array('pipe', 'r'),
658 1 => array('pipe', 'w'),
659 2 => array('file', wfGetNull(), 'a')
662 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
663 if (is_resource($process)) {
664 // Theoretically, this style of communication could cause a deadlock
665 // here. If the stdout buffer fills up, then writes to stdin could
666 // block. This doesn't appear to happen with tidy, because tidy only
667 // writes to stdout after it's finished reading from stdin. Search
668 // for tidyParseStdin and tidySaveStdout in console/tidy.c
669 fwrite($pipes[0], $text);
671 while (!feof($pipes[1])) {
672 $cleansource .= fgets($pipes[1], 1024);
675 proc_close($process);
678 wfProfileOut( $fname );
680 if( $cleansource == '' && $text != '') {
681 // Some kind of error happened, so we couldn't get the corrected text.
682 // Just give up; we'll use the source text and append a warning.
690 * Use the HTML tidy PECL extension to use the tidy library in-process,
691 * saving the overhead of spawning a new process.
693 * 'pear install tidy' should be able to compile the extension module.
698 function internalTidy( $text ) {
699 global $wgTidyConf, $IP, $wgDebugTidy;
700 $fname = 'Parser::internalTidy';
701 wfProfileIn( $fname );
704 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
705 $tidy->cleanRepair();
706 if( $tidy->getStatus() == 2 ) {
707 // 2 is magic number for fatal error
708 // http://www.php.net/manual/en/function.tidy-get-status.php
711 $cleansource = tidy_get_output( $tidy );
713 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
714 $cleansource .= "<!--\nTidy reports:\n" .
715 str_replace( '-->', '-->', $tidy->errorBuffer
) .
719 wfProfileOut( $fname );
724 * parse the wiki syntax used to render tables
728 function doTableStuff ( $text ) {
729 $fname = 'Parser::doTableStuff';
730 wfProfileIn( $fname );
732 $lines = explode ( "\n" , $text );
733 $td_history = array (); // Is currently a td tag open?
734 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
735 $tr_history = array (); // Is currently a tr tag open?
736 $tr_attributes = array (); // history of tr attributes
737 $has_opened_tr = array(); // Did this table open a <tr> element?
738 $indent_level = 0; // indent level of the table
739 foreach ( $lines as $key => $line )
741 $line = trim ( $line );
743 if( $line == '' ) { // empty line, go to next line
746 $first_character = $line{0};
749 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
750 // First check if we are starting a new table
751 $indent_level = strlen( $matches[1] );
753 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
754 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
756 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
757 array_push ( $td_history , false );
758 array_push ( $last_tag_history , '' );
759 array_push ( $tr_history , false );
760 array_push ( $tr_attributes , '' );
761 array_push ( $has_opened_tr , false );
762 } else if ( count ( $td_history ) == 0 ) {
763 // Don't do any of the following
765 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
766 // We are ending a table
767 $line = '</table>' . substr ( $line , 2 );
768 $last_tag = array_pop ( $last_tag_history );
770 if ( !array_pop ( $has_opened_tr ) ) {
771 $line = "<tr><td></td></tr>{$line}";
774 if ( array_pop ( $tr_history ) ) {
775 $line = "</tr>{$line}";
778 if ( array_pop ( $td_history ) ) {
779 $line = "</{$last_tag}>{$line}";
781 array_pop ( $tr_attributes );
782 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
783 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
784 // Now we have a table row
785 $line = preg_replace( '#^\|-+#', '', $line );
787 // Whats after the tag is now only attributes
788 $attributes = $this->mStripState
->unstripBoth( $line );
789 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
790 array_pop ( $tr_attributes );
791 array_push ( $tr_attributes , $attributes );
794 $last_tag = array_pop ( $last_tag_history );
795 array_pop ( $has_opened_tr );
796 array_push ( $has_opened_tr , true );
798 if ( array_pop ( $tr_history ) ) {
802 if ( array_pop ( $td_history ) ) {
803 $line = "</{$last_tag}>{$line}";
806 $lines[$key] = $line;
807 array_push ( $tr_history , false );
808 array_push ( $td_history , false );
809 array_push ( $last_tag_history , '' );
811 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
812 // This might be cell elements, td, th or captions
813 if ( substr ( $line , 0 , 2 ) == '|+' ) {
814 $first_character = '+';
815 $line = substr ( $line , 1 );
818 $line = substr ( $line , 1 );
820 if ( $first_character == '!' ) {
821 $line = str_replace ( '!!' , '||' , $line );
824 // Split up multiple cells on the same line.
825 // FIXME : This can result in improper nesting of tags processed
826 // by earlier parser steps, but should avoid splitting up eg
827 // attribute values containing literal "||".
828 $cells = StringUtils
::explodeMarkup( '||' , $line );
832 // Loop through each table cell
833 foreach ( $cells as $cell )
836 if ( $first_character != '+' )
838 $tr_after = array_pop ( $tr_attributes );
839 if ( !array_pop ( $tr_history ) ) {
840 $previous = "<tr{$tr_after}>\n";
842 array_push ( $tr_history , true );
843 array_push ( $tr_attributes , '' );
844 array_pop ( $has_opened_tr );
845 array_push ( $has_opened_tr , true );
848 $last_tag = array_pop ( $last_tag_history );
850 if ( array_pop ( $td_history ) ) {
851 $previous = "</{$last_tag}>{$previous}";
854 if ( $first_character == '|' ) {
856 } else if ( $first_character == '!' ) {
858 } else if ( $first_character == '+' ) {
859 $last_tag = 'caption';
864 array_push ( $last_tag_history , $last_tag );
866 // A cell could contain both parameters and data
867 $cell_data = explode ( '|' , $cell , 2 );
869 // Bug 553: Note that a '|' inside an invalid link should not
870 // be mistaken as delimiting cell parameters
871 if ( strpos( $cell_data[0], '[[' ) !== false ) {
872 $cell = "{$previous}<{$last_tag}>{$cell}";
873 } else if ( count ( $cell_data ) == 1 )
874 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
876 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
877 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
878 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
881 $lines[$key] .= $cell;
882 array_push ( $td_history , true );
887 // Closing open td, tr && table
888 while ( count ( $td_history ) > 0 )
890 if ( array_pop ( $td_history ) ) {
893 if ( array_pop ( $tr_history ) ) {
896 if ( !array_pop ( $has_opened_tr ) ) {
897 $lines[] = "<tr><td></td></tr>" ;
900 $lines[] = '</table>' ;
903 $output = implode ( "\n" , $lines ) ;
905 // special case: don't return empty table
906 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
910 wfProfileOut( $fname );
916 * Helper function for parse() that transforms wiki markup into
917 * HTML. Only called for $mOutputType == OT_HTML.
921 function internalParse( $text ) {
923 $fname = 'Parser::internalParse';
924 wfProfileIn( $fname );
926 # Hook to suspend the parser in this state
927 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
928 wfProfileOut( $fname );
932 $text = $this->replaceVariables( $text );
933 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
934 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
936 // Tables need to come after variable replacement for things to work
937 // properly; putting them before other transformations should keep
938 // exciting things like link expansions from showing up in surprising
940 $text = $this->doTableStuff( $text );
942 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
944 $text = $this->stripToc( $text );
945 $this->stripNoGallery( $text );
946 $text = $this->doHeadings( $text );
947 if($this->mOptions
->getUseDynamicDates()) {
948 $df =& DateFormatter
::getInstance();
949 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
951 $text = $this->doAllQuotes( $text );
952 $text = $this->replaceInternalLinks( $text );
953 $text = $this->replaceExternalLinks( $text );
955 # replaceInternalLinks may sometimes leave behind
956 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
957 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
959 $text = $this->doMagicLinks( $text );
960 $text = $this->formatHeadings( $text, $isMain );
962 wfProfileOut( $fname );
967 * Replace special strings like "ISBN xxx" and "RFC xxx" with
968 * magic external links.
972 function doMagicLinks( $text ) {
973 wfProfileIn( __METHOD__
);
974 $text = preg_replace_callback(
976 <a.*?</a> | # Skip link text
977 <.*?> | # Skip stuff inside HTML elements
978 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
979 ISBN\s+(\b # ISBN, capture number as m[2]
980 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
981 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
982 [0-9Xx] # check digit
984 )!x', array( &$this, 'magicLinkCallback' ), $text );
985 wfProfileOut( __METHOD__
);
989 function magicLinkCallback( $m ) {
990 if ( substr( $m[0], 0, 1 ) == '<' ) {
993 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
995 $num = strtr( $isbn, array(
1000 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1001 $text = '<a href="' .
1002 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1003 "\" class=\"internal\">ISBN $isbn</a>";
1005 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1009 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1011 $urlmsg = 'pubmedurl';
1014 throw new MWException( __METHOD__
.': unrecognised match type "' .
1015 substr($m[0], 0, 20 ) . '"' );
1018 $url = wfMsg( $urlmsg, $id);
1019 $sk = $this->mOptions
->getSkin();
1020 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1021 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1027 * Parse headers and return html
1031 function doHeadings( $text ) {
1032 $fname = 'Parser::doHeadings';
1033 wfProfileIn( $fname );
1034 for ( $i = 6; $i >= 1; --$i ) {
1035 $h = str_repeat( '=', $i );
1036 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1037 "<h$i>\\1</h$i>", $text );
1039 wfProfileOut( $fname );
1044 * Replace single quotes with HTML markup
1046 * @return string the altered text
1048 function doAllQuotes( $text ) {
1049 $fname = 'Parser::doAllQuotes';
1050 wfProfileIn( $fname );
1052 $lines = explode( "\n", $text );
1053 foreach ( $lines as $line ) {
1054 $outtext .= $this->doQuotes ( $line ) . "\n";
1056 $outtext = substr($outtext, 0,-1);
1057 wfProfileOut( $fname );
1062 * Helper function for doAllQuotes()
1064 public function doQuotes( $text ) {
1065 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1066 if ( count( $arr ) == 1 )
1070 # First, do some preliminary work. This may shift some apostrophes from
1071 # being mark-up to being text. It also counts the number of occurrences
1072 # of bold and italics mark-ups.
1076 foreach ( $arr as $r )
1078 if ( ( $i %
2 ) == 1 )
1080 # If there are ever four apostrophes, assume the first is supposed to
1081 # be text, and the remaining three constitute mark-up for bold text.
1082 if ( strlen( $arr[$i] ) == 4 )
1087 # If there are more than 5 apostrophes in a row, assume they're all
1088 # text except for the last 5.
1089 else if ( strlen( $arr[$i] ) > 5 )
1091 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1094 # Count the number of occurrences of bold and italics mark-ups.
1095 # We are not counting sequences of five apostrophes.
1096 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1097 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1098 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1103 # If there is an odd number of both bold and italics, it is likely
1104 # that one of the bold ones was meant to be an apostrophe followed
1105 # by italics. Which one we cannot know for certain, but it is more
1106 # likely to be one that has a single-letter word before it.
1107 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1110 $firstsingleletterword = -1;
1111 $firstmultiletterword = -1;
1113 foreach ( $arr as $r )
1115 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1117 $x1 = substr ($arr[$i-1], -1);
1118 $x2 = substr ($arr[$i-1], -2, 1);
1120 if ($firstspace == -1) $firstspace = $i;
1121 } else if ($x2 == ' ') {
1122 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1124 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1130 # If there is a single-letter word, use it!
1131 if ($firstsingleletterword > -1)
1133 $arr [ $firstsingleletterword ] = "''";
1134 $arr [ $firstsingleletterword-1 ] .= "'";
1136 # If not, but there's a multi-letter word, use that one.
1137 else if ($firstmultiletterword > -1)
1139 $arr [ $firstmultiletterword ] = "''";
1140 $arr [ $firstmultiletterword-1 ] .= "'";
1142 # ... otherwise use the first one that has neither.
1143 # (notice that it is possible for all three to be -1 if, for example,
1144 # there is only one pentuple-apostrophe in the line)
1145 else if ($firstspace > -1)
1147 $arr [ $firstspace ] = "''";
1148 $arr [ $firstspace-1 ] .= "'";
1152 # Now let's actually convert our apostrophic mush to HTML!
1157 foreach ($arr as $r)
1161 if ($state == 'both')
1168 if (strlen ($r) == 2)
1171 { $output .= '</i>'; $state = ''; }
1172 else if ($state == 'bi')
1173 { $output .= '</i>'; $state = 'b'; }
1174 else if ($state == 'ib')
1175 { $output .= '</b></i><b>'; $state = 'b'; }
1176 else if ($state == 'both')
1177 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1178 else # $state can be 'b' or ''
1179 { $output .= '<i>'; $state .= 'i'; }
1181 else if (strlen ($r) == 3)
1184 { $output .= '</b>'; $state = ''; }
1185 else if ($state == 'bi')
1186 { $output .= '</i></b><i>'; $state = 'i'; }
1187 else if ($state == 'ib')
1188 { $output .= '</b>'; $state = 'i'; }
1189 else if ($state == 'both')
1190 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1191 else # $state can be 'i' or ''
1192 { $output .= '<b>'; $state .= 'b'; }
1194 else if (strlen ($r) == 5)
1197 { $output .= '</b><i>'; $state = 'i'; }
1198 else if ($state == 'i')
1199 { $output .= '</i><b>'; $state = 'b'; }
1200 else if ($state == 'bi')
1201 { $output .= '</i></b>'; $state = ''; }
1202 else if ($state == 'ib')
1203 { $output .= '</b></i>'; $state = ''; }
1204 else if ($state == 'both')
1205 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1206 else # ($state == '')
1207 { $buffer = ''; $state = 'both'; }
1212 # Now close all remaining tags. Notice that the order is important.
1213 if ($state == 'b' ||
$state == 'ib')
1215 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1219 # There might be lonely ''''', so make sure we have a buffer
1220 if ($state == 'both' && $buffer)
1221 $output .= '<b><i>'.$buffer.'</i></b>';
1227 * Replace external links
1229 * Note: this is all very hackish and the order of execution matters a lot.
1230 * Make sure to run maintenance/parserTests.php if you change this code.
1234 function replaceExternalLinks( $text ) {
1236 $fname = 'Parser::replaceExternalLinks';
1237 wfProfileIn( $fname );
1239 $sk = $this->mOptions
->getSkin();
1241 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1243 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1246 while ( $i<count( $bits ) ) {
1248 $protocol = $bits[$i++
];
1249 $text = $bits[$i++
];
1250 $trail = $bits[$i++
];
1252 # The characters '<' and '>' (which were escaped by
1253 # removeHTMLtags()) should not be included in
1254 # URLs, per RFC 2396.
1256 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1257 $text = substr($url, $m2[0][1]) . ' ' . $text;
1258 $url = substr($url, 0, $m2[0][1]);
1261 # If the link text is an image URL, replace it with an <img> tag
1262 # This happened by accident in the original parser, but some people used it extensively
1263 $img = $this->maybeMakeExternalImage( $text );
1264 if ( $img !== false ) {
1270 # Set linktype for CSS - if URL==text, link is essentially free
1271 $linktype = ($text == $url) ?
'free' : 'text';
1273 # No link text, e.g. [http://domain.tld/some.link]
1274 if ( $text == '' ) {
1275 # Autonumber if allowed. See bug #5918
1276 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1277 $text = '[' . ++
$this->mAutonumber
. ']';
1278 $linktype = 'autonumber';
1280 # Otherwise just use the URL
1281 $text = htmlspecialchars( $url );
1285 # Have link text, e.g. [http://domain.tld/some.link text]s
1287 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1290 $text = $wgContLang->markNoConversion($text);
1292 $url = Sanitizer
::cleanUrl( $url );
1294 # Process the trail (i.e. everything after this link up until start of the next link),
1295 # replacing any non-bracketed links
1296 $trail = $this->replaceFreeExternalLinks( $trail );
1298 # Use the encoded URL
1299 # This means that users can paste URLs directly into the text
1300 # Funny characters like ö aren't valid in URLs anyway
1301 # This was changed in August 2004
1302 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1304 # Register link in the output object.
1305 # Replace unnecessary URL escape codes with the referenced character
1306 # This prevents spammers from hiding links from the filters
1307 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1308 $this->mOutput
->addExternalLink( $pasteurized );
1311 wfProfileOut( $fname );
1316 * Replace anything that looks like a URL with a link
1319 function replaceFreeExternalLinks( $text ) {
1321 $fname = 'Parser::replaceFreeExternalLinks';
1322 wfProfileIn( $fname );
1324 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1325 $s = array_shift( $bits );
1328 $sk = $this->mOptions
->getSkin();
1330 while ( $i < count( $bits ) ){
1331 $protocol = $bits[$i++
];
1332 $remainder = $bits[$i++
];
1335 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1336 # Found some characters after the protocol that look promising
1337 $url = $protocol . $m[1];
1340 # special case: handle urls as url args:
1341 # http://www.example.com/foo?=http://www.example.com/bar
1342 if(strlen($trail) == 0 &&
1344 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1345 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1348 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1353 # The characters '<' and '>' (which were escaped by
1354 # removeHTMLtags()) should not be included in
1355 # URLs, per RFC 2396.
1357 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1358 $trail = substr($url, $m2[0][1]) . $trail;
1359 $url = substr($url, 0, $m2[0][1]);
1362 # Move trailing punctuation to $trail
1364 # If there is no left bracket, then consider right brackets fair game too
1365 if ( strpos( $url, '(' ) === false ) {
1369 $numSepChars = strspn( strrev( $url ), $sep );
1370 if ( $numSepChars ) {
1371 $trail = substr( $url, -$numSepChars ) . $trail;
1372 $url = substr( $url, 0, -$numSepChars );
1375 $url = Sanitizer
::cleanUrl( $url );
1377 # Is this an external image?
1378 $text = $this->maybeMakeExternalImage( $url );
1379 if ( $text === false ) {
1380 # Not an image, make a link
1381 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1382 # Register it in the output object...
1383 # Replace unnecessary URL escape codes with their equivalent characters
1384 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1385 $this->mOutput
->addExternalLink( $pasteurized );
1387 $s .= $text . $trail;
1389 $s .= $protocol . $remainder;
1392 wfProfileOut( $fname );
1397 * Replace unusual URL escape codes with their equivalent characters
1401 * @todo This can merge genuinely required bits in the path or query string,
1402 * breaking legit URLs. A proper fix would treat the various parts of
1403 * the URL differently; as a workaround, just use the output for
1404 * statistical records, not for actual linking/output.
1406 static function replaceUnusualEscapes( $url ) {
1407 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1408 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1412 * Callback function used in replaceUnusualEscapes().
1413 * Replaces unusual URL escape codes with their equivalent character
1417 private static function replaceUnusualEscapesCallback( $matches ) {
1418 $char = urldecode( $matches[0] );
1419 $ord = ord( $char );
1420 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1421 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1422 // No, shouldn't be escaped
1425 // Yes, leave it escaped
1431 * make an image if it's allowed, either through the global
1432 * option or through the exception
1435 function maybeMakeExternalImage( $url ) {
1436 $sk = $this->mOptions
->getSkin();
1437 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1438 $imagesexception = !empty($imagesfrom);
1440 if ( $this->mOptions
->getAllowExternalImages()
1441 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1442 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1444 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1451 * Process [[ ]] wikilinks
1455 function replaceInternalLinks( $s ) {
1457 static $fname = 'Parser::replaceInternalLinks' ;
1459 wfProfileIn( $fname );
1461 wfProfileIn( $fname.'-setup' );
1463 # the % is needed to support urlencoded titles as well
1464 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1466 $sk = $this->mOptions
->getSkin();
1468 #split the entire text string on occurences of [[
1469 $a = explode( '[[', ' ' . $s );
1470 #get the first element (all text up to first [[), and remove the space we added
1471 $s = array_shift( $a );
1472 $s = substr( $s, 1 );
1474 # Match a link having the form [[namespace:link|alternate]]trail
1476 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1477 # Match cases where there is no "]]", which might still be images
1478 static $e1_img = FALSE;
1479 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1481 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1483 if ( $useLinkPrefixExtension ) {
1484 # Match the end of a line for a word that's not followed by whitespace,
1485 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1486 $e2 = wfMsgForContent( 'linkprefix' );
1489 if( is_null( $this->mTitle
) ) {
1490 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1492 $nottalk = !$this->mTitle
->isTalkPage();
1494 if ( $useLinkPrefixExtension ) {
1496 if ( preg_match( $e2, $s, $m ) ) {
1497 $first_prefix = $m[2];
1499 $first_prefix = false;
1505 if($wgContLang->hasVariants()) {
1506 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1508 $selflink = array($this->mTitle
->getPrefixedText());
1510 $useSubpages = $this->areSubpagesAllowed();
1511 wfProfileOut( $fname.'-setup' );
1513 # Loop for each link
1514 for ($k = 0; isset( $a[$k] ); $k++
) {
1516 if ( $useLinkPrefixExtension ) {
1517 wfProfileIn( $fname.'-prefixhandling' );
1518 if ( preg_match( $e2, $s, $m ) ) {
1526 $prefix = $first_prefix;
1527 $first_prefix = false;
1529 wfProfileOut( $fname.'-prefixhandling' );
1532 $might_be_img = false;
1534 wfProfileIn( "$fname-e1" );
1535 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1537 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1538 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1539 # the real problem is with the $e1 regex
1542 # Still some problems for cases where the ] is meant to be outside punctuation,
1543 # and no image is in sight. See bug 2095.
1546 substr( $m[3], 0, 1 ) === ']' &&
1547 strpos($text, '[') !== false
1550 $text .= ']'; # so that replaceExternalLinks($text) works later
1551 $m[3] = substr( $m[3], 1 );
1553 # fix up urlencoded title texts
1554 if( strpos( $m[1], '%' ) !== false ) {
1555 # Should anchors '#' also be rejected?
1556 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1559 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1560 $might_be_img = true;
1562 if ( strpos( $m[1], '%' ) !== false ) {
1563 $m[1] = urldecode($m[1]);
1566 } else { # Invalid form; output directly
1567 $s .= $prefix . '[[' . $line ;
1568 wfProfileOut( "$fname-e1" );
1571 wfProfileOut( "$fname-e1" );
1572 wfProfileIn( "$fname-misc" );
1574 # Don't allow internal links to pages containing
1575 # PROTO: where PROTO is a valid URL protocol; these
1576 # should be external links.
1577 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1578 $s .= $prefix . '[[' . $line ;
1582 # Make subpage if necessary
1583 if( $useSubpages ) {
1584 $link = $this->maybeDoSubpageLink( $m[1], $text );
1589 $noforce = (substr($m[1], 0, 1) != ':');
1591 # Strip off leading ':'
1592 $link = substr($link, 1);
1595 wfProfileOut( "$fname-misc" );
1596 wfProfileIn( "$fname-title" );
1597 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1599 $s .= $prefix . '[[' . $line;
1600 wfProfileOut( "$fname-title" );
1604 $ns = $nt->getNamespace();
1605 $iw = $nt->getInterWiki();
1606 wfProfileOut( "$fname-title" );
1608 if ($might_be_img) { # if this is actually an invalid link
1609 wfProfileIn( "$fname-might_be_img" );
1610 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1612 while (isset ($a[$k+
1]) ) {
1613 #look at the next 'line' to see if we can close it there
1614 $spliced = array_splice( $a, $k +
1, 1 );
1615 $next_line = array_shift( $spliced );
1616 $m = explode( ']]', $next_line, 3 );
1617 if ( count( $m ) == 3 ) {
1618 # the first ]] closes the inner link, the second the image
1620 $text .= "[[{$m[0]}]]{$m[1]}";
1623 } elseif ( count( $m ) == 2 ) {
1624 #if there's exactly one ]] that's fine, we'll keep looking
1625 $text .= "[[{$m[0]}]]{$m[1]}";
1627 #if $next_line is invalid too, we need look no further
1628 $text .= '[[' . $next_line;
1633 # we couldn't find the end of this imageLink, so output it raw
1634 #but don't ignore what might be perfectly normal links in the text we've examined
1635 $text = $this->replaceInternalLinks($text);
1636 $s .= "{$prefix}[[$link|$text";
1637 # note: no $trail, because without an end, there *is* no trail
1638 wfProfileOut( "$fname-might_be_img" );
1641 } else { #it's not an image, so output it raw
1642 $s .= "{$prefix}[[$link|$text";
1643 # note: no $trail, because without an end, there *is* no trail
1644 wfProfileOut( "$fname-might_be_img" );
1647 wfProfileOut( "$fname-might_be_img" );
1650 $wasblank = ( '' == $text );
1651 if( $wasblank ) $text = $link;
1653 # Link not escaped by : , create the various objects
1657 wfProfileIn( "$fname-interwiki" );
1658 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1659 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1660 $s = rtrim($s . $prefix);
1661 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1662 wfProfileOut( "$fname-interwiki" );
1665 wfProfileOut( "$fname-interwiki" );
1667 if ( $ns == NS_IMAGE
) {
1668 wfProfileIn( "$fname-image" );
1669 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1670 # recursively parse links inside the image caption
1671 # actually, this will parse them in any other parameters, too,
1672 # but it might be hard to fix that, and it doesn't matter ATM
1673 $text = $this->replaceExternalLinks($text);
1674 $text = $this->replaceInternalLinks($text);
1676 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1677 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1678 $this->mOutput
->addImage( $nt->getDBkey() );
1680 wfProfileOut( "$fname-image" );
1683 # We still need to record the image's presence on the page
1684 $this->mOutput
->addImage( $nt->getDBkey() );
1686 wfProfileOut( "$fname-image" );
1690 if ( $ns == NS_CATEGORY
) {
1691 wfProfileIn( "$fname-category" );
1692 $s = rtrim($s . "\n"); # bug 87
1695 $sortkey = $this->getDefaultSort();
1699 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1700 $sortkey = str_replace( "\n", '', $sortkey );
1701 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1702 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1705 * Strip the whitespace Category links produce, see bug 87
1706 * @todo We might want to use trim($tmp, "\n") here.
1708 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1710 wfProfileOut( "$fname-category" );
1715 # Self-link checking
1716 if( $nt->getFragment() === '' ) {
1717 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1718 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1723 # Special and Media are pseudo-namespaces; no pages actually exist in them
1724 if( $ns == NS_MEDIA
) {
1725 $link = $sk->makeMediaLinkObj( $nt, $text );
1726 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1727 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1728 $this->mOutput
->addImage( $nt->getDBkey() );
1730 } elseif( $ns == NS_SPECIAL
) {
1731 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1732 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1734 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1737 } elseif( $ns == NS_IMAGE
) {
1738 $img = wfFindFile( $nt );
1740 // Force a blue link if the file exists; may be a remote
1741 // upload on the shared repository, and we want to see its
1742 // auto-generated page.
1743 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1744 $this->mOutput
->addLink( $nt );
1748 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1750 wfProfileOut( $fname );
1755 * Make a link placeholder. The text returned can be later resolved to a real link with
1756 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1757 * parsing of interwiki links, and secondly to allow all existence checks and
1758 * article length checks (for stub links) to be bundled into a single query.
1761 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1762 wfProfileIn( __METHOD__
);
1763 if ( ! is_object($nt) ) {
1765 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1767 # Separate the link trail from the rest of the link
1768 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1770 if ( $nt->isExternal() ) {
1771 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1772 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1773 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1775 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1776 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1777 $this->mLinkHolders
['queries'][] = $query;
1778 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1779 $this->mLinkHolders
['titles'][] = $nt;
1781 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1784 wfProfileOut( __METHOD__
);
1789 * Render a forced-blue link inline; protect against double expansion of
1790 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1791 * Since this little disaster has to split off the trail text to avoid
1792 * breaking URLs in the following text without breaking trails on the
1793 * wiki links, it's been made into a horrible function.
1796 * @param string $text
1797 * @param string $query
1798 * @param string $trail
1799 * @param string $prefix
1800 * @return string HTML-wikitext mix oh yuck
1802 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1803 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1804 $sk = $this->mOptions
->getSkin();
1805 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1806 return $this->armorLinks( $link ) . $trail;
1810 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1811 * going to go through further parsing steps before inline URL expansion.
1813 * In particular this is important when using action=render, which causes
1814 * full URLs to be included.
1816 * Oh man I hate our multi-layer parser!
1818 * @param string more-or-less HTML
1819 * @return string less-or-more HTML with NOPARSE bits
1821 function armorLinks( $text ) {
1822 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1823 "{$this->mUniqPrefix}NOPARSE$1", $text );
1827 * Return true if subpage links should be expanded on this page.
1830 function areSubpagesAllowed() {
1831 # Some namespaces don't allow subpages
1832 global $wgNamespacesWithSubpages;
1833 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1837 * Handle link to subpage if necessary
1838 * @param string $target the source of the link
1839 * @param string &$text the link text, modified as necessary
1840 * @return string the full name of the link
1843 function maybeDoSubpageLink($target, &$text) {
1846 # :Foobar -- override special treatment of prefix (images, language links)
1847 # /Foobar -- convert to CurrentPage/Foobar
1848 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1849 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1850 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1852 $fname = 'Parser::maybeDoSubpageLink';
1853 wfProfileIn( $fname );
1854 $ret = $target; # default return value is no change
1856 # Some namespaces don't allow subpages,
1857 # so only perform processing if subpages are allowed
1858 if( $this->areSubpagesAllowed() ) {
1859 $hash = strpos( $target, '#' );
1860 if( $hash !== false ) {
1861 $suffix = substr( $target, $hash );
1862 $target = substr( $target, 0, $hash );
1867 $target = trim( $target );
1868 # Look at the first character
1869 if( $target != '' && $target{0} == '/' ) {
1870 # / at end means we don't want the slash to be shown
1872 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1873 if( $trailingSlashes ) {
1874 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1876 $noslash = substr( $target, 1 );
1879 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1880 if( '' === $text ) {
1881 $text = $target . $suffix;
1882 } # this might be changed for ugliness reasons
1884 # check for .. subpage backlinks
1886 $nodotdot = $target;
1887 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1889 $nodotdot = substr( $nodotdot, 3 );
1891 if($dotdotcount > 0) {
1892 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1893 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1894 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1895 # / at the end means don't show full path
1896 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1897 $nodotdot = substr( $nodotdot, 0, -1 );
1898 if( '' === $text ) {
1899 $text = $nodotdot . $suffix;
1902 $nodotdot = trim( $nodotdot );
1903 if( $nodotdot != '' ) {
1904 $ret .= '/' . $nodotdot;
1912 wfProfileOut( $fname );
1917 * Used by doBlockLevels()
1920 /* private */ function closeParagraph() {
1922 if ( '' != $this->mLastSection
) {
1923 $result = '</' . $this->mLastSection
. ">\n";
1925 $this->mInPre
= false;
1926 $this->mLastSection
= '';
1929 # getCommon() returns the length of the longest common substring
1930 # of both arguments, starting at the beginning of both.
1932 /* private */ function getCommon( $st1, $st2 ) {
1933 $fl = strlen( $st1 );
1934 $shorter = strlen( $st2 );
1935 if ( $fl < $shorter ) { $shorter = $fl; }
1937 for ( $i = 0; $i < $shorter; ++
$i ) {
1938 if ( $st1{$i} != $st2{$i} ) { break; }
1942 # These next three functions open, continue, and close the list
1943 # element appropriate to the prefix character passed into them.
1945 /* private */ function openList( $char ) {
1946 $result = $this->closeParagraph();
1948 if ( '*' == $char ) { $result .= '<ul><li>'; }
1949 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1950 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1951 else if ( ';' == $char ) {
1952 $result .= '<dl><dt>';
1953 $this->mDTopen
= true;
1955 else { $result = '<!-- ERR 1 -->'; }
1960 /* private */ function nextItem( $char ) {
1961 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1962 else if ( ':' == $char ||
';' == $char ) {
1964 if ( $this->mDTopen
) { $close = '</dt>'; }
1965 if ( ';' == $char ) {
1966 $this->mDTopen
= true;
1967 return $close . '<dt>';
1969 $this->mDTopen
= false;
1970 return $close . '<dd>';
1973 return '<!-- ERR 2 -->';
1976 /* private */ function closeList( $char ) {
1977 if ( '*' == $char ) { $text = '</li></ul>'; }
1978 else if ( '#' == $char ) { $text = '</li></ol>'; }
1979 else if ( ':' == $char ) {
1980 if ( $this->mDTopen
) {
1981 $this->mDTopen
= false;
1982 $text = '</dt></dl>';
1984 $text = '</dd></dl>';
1987 else { return '<!-- ERR 3 -->'; }
1993 * Make lists from lines starting with ':', '*', '#', etc.
1996 * @return string the lists rendered as HTML
1998 function doBlockLevels( $text, $linestart ) {
1999 $fname = 'Parser::doBlockLevels';
2000 wfProfileIn( $fname );
2002 # Parsing through the text line by line. The main thing
2003 # happening here is handling of block-level elements p, pre,
2004 # and making lists from lines starting with * # : etc.
2006 $textLines = explode( "\n", $text );
2008 $lastPrefix = $output = '';
2009 $this->mDTopen
= $inBlockElem = false;
2011 $paragraphStack = false;
2013 if ( !$linestart ) {
2014 $output .= array_shift( $textLines );
2016 foreach ( $textLines as $oLine ) {
2017 $lastPrefixLength = strlen( $lastPrefix );
2018 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2019 $preOpenMatch = preg_match('/<pre/i', $oLine );
2020 if ( !$this->mInPre
) {
2021 # Multiple prefixes may abut each other for nested lists.
2022 $prefixLength = strspn( $oLine, '*#:;' );
2023 $pref = substr( $oLine, 0, $prefixLength );
2026 $pref2 = str_replace( ';', ':', $pref );
2027 $t = substr( $oLine, $prefixLength );
2028 $this->mInPre
= !empty($preOpenMatch);
2030 # Don't interpret any other prefixes in preformatted text
2032 $pref = $pref2 = '';
2037 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2038 # Same as the last item, so no need to deal with nesting or opening stuff
2039 $output .= $this->nextItem( substr( $pref, -1 ) );
2040 $paragraphStack = false;
2042 if ( substr( $pref, -1 ) == ';') {
2043 # The one nasty exception: definition lists work like this:
2044 # ; title : definition text
2045 # So we check for : in the remainder text to split up the
2046 # title and definition, without b0rking links.
2048 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2050 $output .= $term . $this->nextItem( ':' );
2053 } elseif( $prefixLength ||
$lastPrefixLength ) {
2054 # Either open or close a level...
2055 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2056 $paragraphStack = false;
2058 while( $commonPrefixLength < $lastPrefixLength ) {
2059 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2060 --$lastPrefixLength;
2062 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2063 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2065 while ( $prefixLength > $commonPrefixLength ) {
2066 $char = substr( $pref, $commonPrefixLength, 1 );
2067 $output .= $this->openList( $char );
2069 if ( ';' == $char ) {
2070 # FIXME: This is dupe of code above
2071 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2073 $output .= $term . $this->nextItem( ':' );
2076 ++
$commonPrefixLength;
2078 $lastPrefix = $pref2;
2080 if( 0 == $prefixLength ) {
2081 wfProfileIn( "$fname-paragraph" );
2082 # No prefix (not in list)--go to paragraph mode
2083 // XXX: use a stack for nestable elements like span, table and div
2084 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2085 $closematch = preg_match(
2086 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2087 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2088 if ( $openmatch or $closematch ) {
2089 $paragraphStack = false;
2090 #Â TODO bug 5718: paragraph closed
2091 $output .= $this->closeParagraph();
2092 if ( $preOpenMatch and !$preCloseMatch ) {
2093 $this->mInPre
= true;
2095 if ( $closematch ) {
2096 $inBlockElem = false;
2098 $inBlockElem = true;
2100 } else if ( !$inBlockElem && !$this->mInPre
) {
2101 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2103 if ($this->mLastSection
!= 'pre') {
2104 $paragraphStack = false;
2105 $output .= $this->closeParagraph().'<pre>';
2106 $this->mLastSection
= 'pre';
2108 $t = substr( $t, 1 );
2111 if ( '' == trim($t) ) {
2112 if ( $paragraphStack ) {
2113 $output .= $paragraphStack.'<br />';
2114 $paragraphStack = false;
2115 $this->mLastSection
= 'p';
2117 if ($this->mLastSection
!= 'p' ) {
2118 $output .= $this->closeParagraph();
2119 $this->mLastSection
= '';
2120 $paragraphStack = '<p>';
2122 $paragraphStack = '</p><p>';
2126 if ( $paragraphStack ) {
2127 $output .= $paragraphStack;
2128 $paragraphStack = false;
2129 $this->mLastSection
= 'p';
2130 } else if ($this->mLastSection
!= 'p') {
2131 $output .= $this->closeParagraph().'<p>';
2132 $this->mLastSection
= 'p';
2137 wfProfileOut( "$fname-paragraph" );
2139 // somewhere above we forget to get out of pre block (bug 785)
2140 if($preCloseMatch && $this->mInPre
) {
2141 $this->mInPre
= false;
2143 if ($paragraphStack === false) {
2147 while ( $prefixLength ) {
2148 $output .= $this->closeList( $pref2{$prefixLength-1} );
2151 if ( '' != $this->mLastSection
) {
2152 $output .= '</' . $this->mLastSection
. '>';
2153 $this->mLastSection
= '';
2156 wfProfileOut( $fname );
2161 * Split up a string on ':', ignoring any occurences inside tags
2162 * to prevent illegal overlapping.
2163 * @param string $str the string to split
2164 * @param string &$before set to everything before the ':'
2165 * @param string &$after set to everything after the ':'
2166 * return string the position of the ':', or false if none found
2168 function findColonNoLinks($str, &$before, &$after) {
2169 $fname = 'Parser::findColonNoLinks';
2170 wfProfileIn( $fname );
2172 $pos = strpos( $str, ':' );
2173 if( $pos === false ) {
2175 wfProfileOut( $fname );
2179 $lt = strpos( $str, '<' );
2180 if( $lt === false ||
$lt > $pos ) {
2181 // Easy; no tag nesting to worry about
2182 $before = substr( $str, 0, $pos );
2183 $after = substr( $str, $pos+
1 );
2184 wfProfileOut( $fname );
2188 // Ugly state machine to walk through avoiding tags.
2189 $state = self
::COLON_STATE_TEXT
;
2191 $len = strlen( $str );
2192 for( $i = 0; $i < $len; $i++
) {
2196 // (Using the number is a performance hack for common cases)
2197 case 0: // self::COLON_STATE_TEXT:
2200 // Could be either a <start> tag or an </end> tag
2201 $state = self
::COLON_STATE_TAGSTART
;
2206 $before = substr( $str, 0, $i );
2207 $after = substr( $str, $i +
1 );
2208 wfProfileOut( $fname );
2211 // Embedded in a tag; don't break it.
2214 // Skip ahead looking for something interesting
2215 $colon = strpos( $str, ':', $i );
2216 if( $colon === false ) {
2217 // Nothing else interesting
2218 wfProfileOut( $fname );
2221 $lt = strpos( $str, '<', $i );
2222 if( $stack === 0 ) {
2223 if( $lt === false ||
$colon < $lt ) {
2225 $before = substr( $str, 0, $colon );
2226 $after = substr( $str, $colon +
1 );
2227 wfProfileOut( $fname );
2231 if( $lt === false ) {
2232 // Nothing else interesting to find; abort!
2233 // We're nested, but there's no close tags left. Abort!
2236 // Skip ahead to next tag start
2238 $state = self
::COLON_STATE_TAGSTART
;
2241 case 1: // self::COLON_STATE_TAG:
2246 $state = self
::COLON_STATE_TEXT
;
2249 // Slash may be followed by >?
2250 $state = self
::COLON_STATE_TAGSLASH
;
2256 case 2: // self::COLON_STATE_TAGSTART:
2259 $state = self
::COLON_STATE_CLOSETAG
;
2262 $state = self
::COLON_STATE_COMMENT
;
2265 // Illegal early close? This shouldn't happen D:
2266 $state = self
::COLON_STATE_TEXT
;
2269 $state = self
::COLON_STATE_TAG
;
2272 case 3: // self::COLON_STATE_CLOSETAG:
2277 wfDebug( "Invalid input in $fname; too many close tags\n" );
2278 wfProfileOut( $fname );
2281 $state = self
::COLON_STATE_TEXT
;
2284 case self
::COLON_STATE_TAGSLASH
:
2286 // Yes, a self-closed tag <blah/>
2287 $state = self
::COLON_STATE_TEXT
;
2289 // Probably we're jumping the gun, and this is an attribute
2290 $state = self
::COLON_STATE_TAG
;
2293 case 5: // self::COLON_STATE_COMMENT:
2295 $state = self
::COLON_STATE_COMMENTDASH
;
2298 case self
::COLON_STATE_COMMENTDASH
:
2300 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2302 $state = self
::COLON_STATE_COMMENT
;
2305 case self
::COLON_STATE_COMMENTDASHDASH
:
2307 $state = self
::COLON_STATE_TEXT
;
2309 $state = self
::COLON_STATE_COMMENT
;
2313 throw new MWException( "State machine error in $fname" );
2317 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2320 wfProfileOut( $fname );
2325 * Return value of a magic variable (like PAGENAME)
2329 function getVariableValue( $index ) {
2330 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2333 * Some of these require message or data lookups and can be
2334 * expensive to check many times.
2336 static $varCache = array();
2337 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2338 if ( isset( $varCache[$index] ) ) {
2339 return $varCache[$index];
2344 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2347 global $wgLocaltimezone;
2348 if ( isset( $wgLocaltimezone ) ) {
2349 $oldtz = getenv( 'TZ' );
2350 putenv( 'TZ='.$wgLocaltimezone );
2353 wfSuppressWarnings(); // E_STRICT system time bitching
2354 $localTimestamp = date( 'YmdHis', $ts );
2355 $localMonth = date( 'm', $ts );
2356 $localMonthName = date( 'n', $ts );
2357 $localDay = date( 'j', $ts );
2358 $localDay2 = date( 'd', $ts );
2359 $localDayOfWeek = date( 'w', $ts );
2360 $localWeek = date( 'W', $ts );
2361 $localYear = date( 'Y', $ts );
2362 $localHour = date( 'H', $ts );
2363 if ( isset( $wgLocaltimezone ) ) {
2364 putenv( 'TZ='.$oldtz );
2366 wfRestoreWarnings();
2369 case 'currentmonth':
2370 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2371 case 'currentmonthname':
2372 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2373 case 'currentmonthnamegen':
2374 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2375 case 'currentmonthabbrev':
2376 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2378 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2380 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2382 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2383 case 'localmonthname':
2384 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2385 case 'localmonthnamegen':
2386 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2387 case 'localmonthabbrev':
2388 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2390 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2392 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2394 return wfEscapeWikiText( $this->mTitle
->getText() );
2396 return $this->mTitle
->getPartialURL();
2397 case 'fullpagename':
2398 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2399 case 'fullpagenamee':
2400 return $this->mTitle
->getPrefixedURL();
2402 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2403 case 'subpagenamee':
2404 return $this->mTitle
->getSubpageUrlForm();
2405 case 'basepagename':
2406 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2407 case 'basepagenamee':
2408 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2409 case 'talkpagename':
2410 if( $this->mTitle
->canTalk() ) {
2411 $talkPage = $this->mTitle
->getTalkPage();
2412 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2416 case 'talkpagenamee':
2417 if( $this->mTitle
->canTalk() ) {
2418 $talkPage = $this->mTitle
->getTalkPage();
2419 return $talkPage->getPrefixedUrl();
2423 case 'subjectpagename':
2424 $subjPage = $this->mTitle
->getSubjectPage();
2425 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2426 case 'subjectpagenamee':
2427 $subjPage = $this->mTitle
->getSubjectPage();
2428 return $subjPage->getPrefixedUrl();
2430 // Let the edit saving system know we should parse the page
2431 // *after* a revision ID has been assigned.
2432 $this->mOutput
->setFlag( 'vary-revision' );
2433 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2434 return $this->mRevisionId
;
2436 // Let the edit saving system know we should parse the page
2437 // *after* a revision ID has been assigned. This is for null edits.
2438 $this->mOutput
->setFlag( 'vary-revision' );
2439 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2440 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2441 case 'revisionday2':
2442 // Let the edit saving system know we should parse the page
2443 // *after* a revision ID has been assigned. This is for null edits.
2444 $this->mOutput
->setFlag( 'vary-revision' );
2445 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2446 return substr( $this->getRevisionTimestamp(), 6, 2 );
2447 case 'revisionmonth':
2448 // Let the edit saving system know we should parse the page
2449 // *after* a revision ID has been assigned. This is for null edits.
2450 $this->mOutput
->setFlag( 'vary-revision' );
2451 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2452 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2453 case 'revisionyear':
2454 // Let the edit saving system know we should parse the page
2455 // *after* a revision ID has been assigned. This is for null edits.
2456 $this->mOutput
->setFlag( 'vary-revision' );
2457 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2458 return substr( $this->getRevisionTimestamp(), 0, 4 );
2459 case 'revisiontimestamp':
2460 // Let the edit saving system know we should parse the page
2461 // *after* a revision ID has been assigned. This is for null edits.
2462 $this->mOutput
->setFlag( 'vary-revision' );
2463 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2464 return $this->getRevisionTimestamp();
2466 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2468 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2470 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2472 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2473 case 'subjectspace':
2474 return $this->mTitle
->getSubjectNsText();
2475 case 'subjectspacee':
2476 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2477 case 'currentdayname':
2478 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2480 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2482 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2484 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2486 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2487 // int to remove the padding
2488 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2490 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2491 case 'localdayname':
2492 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2494 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2496 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2498 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2500 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2501 // int to remove the padding
2502 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2504 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2505 case 'numberofarticles':
2506 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2507 case 'numberoffiles':
2508 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2509 case 'numberofusers':
2510 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2511 case 'numberofpages':
2512 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2513 case 'numberofadmins':
2514 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2515 case 'numberofedits':
2516 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2517 case 'currenttimestamp':
2518 return $varCache[$index] = wfTimestampNow();
2519 case 'localtimestamp':
2520 return $varCache[$index] = $localTimestamp;
2521 case 'currentversion':
2522 return $varCache[$index] = SpecialVersion
::getVersion();
2528 return $wgServerName;
2530 return $wgScriptPath;
2531 case 'directionmark':
2532 return $wgContLang->getDirMark();
2533 case 'contentlanguage':
2534 global $wgContLanguageCode;
2535 return $wgContLanguageCode;
2538 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2546 * initialise the magic variables (like CURRENTMONTHNAME)
2550 function initialiseVariables() {
2551 $fname = 'Parser::initialiseVariables';
2552 wfProfileIn( $fname );
2553 $variableIDs = MagicWord
::getVariableIDs();
2555 $this->mVariables
= new MagicWordArray( $variableIDs );
2556 wfProfileOut( $fname );
2560 * Preprocess some wikitext and return the document tree.
2561 * This is the ghost of replace_variables().
2563 * @param string $text The text to parse
2564 * @param integer flags Bitwise combination of:
2565 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2566 * included. Default is to assume a direct page view.
2568 * The generated DOM tree must depend only on the input text, the flags, and $this->ot['msg'].
2569 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2571 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2572 * change in the DOM tree for a given text, must be passed through the section identifier
2573 * in the section edit link and thus back to extractSections().
2575 * The output of this function is currently only cached in process memory, but a persistent
2576 * cache may be implemented at a later date which takes further advantage of these strict
2577 * dependency requirements.
2581 function preprocessToDom ( $text, $flags = 0 ) {
2582 wfProfileIn( __METHOD__
);
2583 wfProfileIn( __METHOD__
.'-makexml' );
2585 static $msgRules, $normalRules, $inclusionSupertags, $nonInclusionSupertags;
2598 'names' => array( 2 => null ),
2603 $normalRules = array(
2615 'names' => array( 2 => null ),
2621 if ( $this->ot
['msg'] ) {
2624 $rules = $normalRules;
2626 $forInclusion = $flags & self
::PTD_FOR_INCLUSION
;
2628 $xmlishElements = $this->getStripList();
2629 $enableOnlyinclude = false;
2630 if ( $forInclusion ) {
2631 $ignoredTags = array( 'includeonly', '/includeonly' );
2632 $ignoredElements = array( 'noinclude' );
2633 $xmlishElements[] = 'noinclude';
2634 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
2635 $enableOnlyinclude = true;
2638 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
2639 $ignoredElements = array( 'includeonly' );
2640 $xmlishElements[] = 'includeonly';
2642 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
2644 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
2645 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
2647 $stack = array(); # Stack of unclosed parentheses
2648 $stackIndex = -1; # Stack read pointer
2650 $searchBase = implode( '', array_keys( $rules ) ) . '<';
2651 $revText = strrev( $text ); // For fast reverse searches
2653 $i = -1; # Input pointer, starts out pointing to a pseudo-newline before the start
2654 $topAccum = '<root>'; # Top level text accumulator
2655 $accum =& $topAccum; # Current text accumulator
2656 $findEquals = false; # True to find equals signs in arguments
2657 $findHeading = false; # True to look at LF characters for possible headings
2658 $findPipe = false; # True to take notice of pipe characters
2660 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
2661 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
2663 if ( $enableOnlyinclude ) {
2668 if ( $findOnlyinclude ) {
2669 // Ignore all input up to the next <onlyinclude>
2670 $startPos = strpos( $text, '<onlyinclude>', $i );
2671 if ( $startPos === false ) {
2672 // Ignored section runs to the end
2673 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
2676 $tagEndPos = $startPos +
strlen( '<onlyinclude>' ); // past-the-end
2677 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
2679 $findOnlyinclude = false;
2683 $found = 'line-start';
2686 # Find next opening brace, closing brace or pipe
2687 $search = $searchBase;
2688 if ( $stackIndex == -1 ) {
2689 $currentClosing = '';
2690 // Look for headings only at the top stack level
2691 // Among other things, this resolves the ambiguity between =
2692 // for headings and = for template arguments
2695 $currentClosing = $stack[$stackIndex]['close'];
2696 $search .= $currentClosing;
2701 if ( $findEquals ) {
2705 # Output literal section, advance input counter
2706 $literalLength = strcspn( $text, $search, $i );
2707 if ( $literalLength > 0 ) {
2708 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
2709 $i +
= $literalLength;
2711 if ( $i >= strlen( $text ) ) {
2712 if ( $currentClosing == "\n" ) {
2713 // Do a past-the-end run to finish off the heading
2715 $found = 'line-end';
2721 $curChar = $text[$i];
2722 if ( $curChar == '|' ) {
2724 } elseif ( $curChar == '=' ) {
2726 } elseif ( $curChar == '<' ) {
2728 } elseif ( $curChar == "\n" ) {
2729 if ( $stackIndex == -1 ) {
2730 $found = 'line-start';
2732 $found = 'line-end';
2734 } elseif ( $curChar == $currentClosing ) {
2736 } elseif ( isset( $rules[$curChar] ) ) {
2738 $rule = $rules[$curChar];
2740 # Some versions of PHP have a strcspn which stops on null characters
2741 # Ignore and continue
2748 if ( $found == 'angle' ) {
2750 // Handle </onlyinclude>
2751 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
2752 $findOnlyinclude = true;
2756 // Determine element name
2757 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i +
1 ) ) {
2758 // Element name missing or not listed
2764 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
2765 // To avoid leaving blank lines, when a comment is both preceded
2766 // and followed by a newline (ignoring spaces), trim leading and
2767 // trailing spaces and one of the newlines.
2770 $endPos = strpos( $text, '-->', $i +
4 );
2771 if ( $endPos === false ) {
2772 // Unclosed comment in input, runs to end
2773 $inner = substr( $text, $i );
2774 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2775 $i = strlen( $text );
2777 // Search backwards for leading whitespace
2778 $wsStart = $i ?
( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
2779 // Search forwards for trailing whitespace
2780 // $wsEnd will be the position of the last space
2781 $wsEnd = $endPos +
2 +
strspn( $text, ' ', $endPos +
3 );
2782 // Eat the line if possible
2783 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
2784 && substr( $text, $wsEnd +
1, 1 ) == "\n" )
2786 $startPos = $wsStart;
2787 $endPos = $wsEnd +
1;
2788 // Remove leading whitespace from the end of the accumulator
2789 // Sanity check first though
2790 $wsLength = $i - $wsStart;
2791 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
2792 $accum = substr( $accum, 0, -$wsLength );
2795 // No line to eat, just take the comment itself
2800 $inner = substr( $text, $startPos, $endPos - $startPos +
1 );
2801 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2806 $name = $matches[1];
2807 $attrStart = $i +
strlen( $name ) +
1;
2810 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
2811 if ( $tagEndPos === false ) {
2812 // Infinite backtrack
2813 // Disable tag search to prevent worst-case O(N^2) performance
2820 // Handle ignored tags
2821 if ( in_array( $name, $ignoredTags ) ) {
2822 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i +
1 ) ) . '</ignore>';
2823 $i = $tagEndPos +
1;
2828 if ( $text[$tagEndPos-1] == '/' ) {
2829 $attrEnd = $tagEndPos - 1;
2831 $i = $tagEndPos +
1;
2834 $attrEnd = $tagEndPos;
2836 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
2837 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
2838 $i = $matches[0][1] +
strlen( $matches[0][0] );
2839 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
2841 // No end tag -- let it run out to the end of the text.
2842 $inner = substr( $text, $tagEndPos +
1 );
2843 $i = strlen( $text );
2847 // <includeonly> and <noinclude> just become <ignore> tags
2848 if ( in_array( $name, $ignoredElements ) ) {
2849 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
2855 if ( $attrEnd <= $attrStart ) {
2858 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
2860 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
2861 // Note that the attr element contains the whitespace between name and attribute,
2862 // this is necessary for precise reconstruction during pre-save transform.
2863 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
2864 if ( $inner !== null ) {
2865 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
2867 $accum .= $close . '</ext>';
2870 elseif ( $found == 'line-start' ) {
2871 // Is this the start of a heading?
2872 // Line break belongs before the heading element in any case
2876 $count = strspn( $text, '=', $i, 6 );
2881 'parts' => array( str_repeat( '=', $count ) ),
2882 'count' => $count );
2883 $stack[++
$stackIndex] = $piece;
2885 $accum =& $stack[$stackIndex]['parts'][0];
2890 elseif ( $found == 'line-end' ) {
2891 $piece = $stack[$stackIndex];
2892 // A heading must be open, otherwise \n wouldn't have been in the search list
2893 assert( $piece['open'] == "\n" );
2894 assert( $stackIndex == 0 );
2895 // Search back through the input to see if it has a proper close
2896 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
2898 $count = $piece['count'];
2899 if ( preg_match( "/\s*(={{$count}})/A", $revText, $m, 0, strlen( $text ) - $i ) ) {
2900 // Found match, output <h>
2901 $count = min( strlen( $m[1] ), $count );
2902 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
2905 // No match, no <h>, just pass down the inner text
2909 // Headings can only occur on the top level, so this is a bit simpler than the
2910 // generic stack unwind operation in the close case
2911 unset( $stack[$stackIndex--] );
2912 $accum =& $topAccum;
2913 $findEquals = false;
2916 // Append the result to the enclosing accumulator
2918 // Note that we do NOT increment the input pointer.
2919 // This is because the closing linebreak could be the opening linebreak of
2920 // another heading. Infinite loops are avoided because the next iteration MUST
2921 // hit the heading open case above, which unconditionally increments the
2925 elseif ( $found == 'open' ) {
2926 # count opening brace characters
2927 $count = strspn( $text, $curChar, $i );
2929 # we need to add to stack only if opening brace count is enough for one of the rules
2930 if ( $count >= $rule['min'] ) {
2931 # Add it to the stack
2934 'close' => $rule['end'],
2936 'parts' => array( '' ),
2938 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
2942 $stack[$stackIndex] = $piece;
2943 $accum =& $stack[$stackIndex]['parts'][0];
2944 $findEquals = false;
2947 # Add literal brace(s)
2948 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2953 elseif ( $found == 'close' ) {
2954 $piece = $stack[$stackIndex];
2955 # lets check if there are enough characters for closing brace
2956 $maxCount = $piece['count'];
2957 $count = strspn( $text, $curChar, $i, $maxCount );
2959 # check for maximum matching characters (if there are 5 closing
2960 # characters, we will probably need only 3 - depending on the rules)
2962 $rule = $rules[$piece['open']];
2963 if ( $count > $rule['max'] ) {
2964 # The specified maximum exists in the callback array, unless the caller
2966 $matchingCount = $rule['max'];
2968 # Count is less than the maximum
2969 # Skip any gaps in the callback array to find the true largest match
2970 # Need to use array_key_exists not isset because the callback can be null
2971 $matchingCount = $count;
2972 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
2977 if ($matchingCount <= 0) {
2978 # No matching element found in callback array
2979 # Output a literal closing brace and continue
2980 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2984 $name = $rule['names'][$matchingCount];
2985 if ( $name === null ) {
2986 // No element, just literal text
2987 $element = str_repeat( $piece['open'], $matchingCount ) .
2988 implode( '|', $piece['parts'] ) .
2989 str_repeat( $rule['end'], $matchingCount );
2991 # Create XML element
2992 # Note: $parts is already XML, does not need to be encoded further
2993 $parts = $piece['parts'];
2997 # The invocation is at the start of the line if lineStart is set in
2998 # the stack, and all opening brackets are used up.
2999 if ( $maxCount == $matchingCount && !empty( $piece['lineStart'] ) ) {
3000 $attr = ' lineStart="1"';
3005 $element = "<$name$attr>";
3006 $element .= "<title>$title</title>";
3008 foreach ( $parts as $partIndex => $part ) {
3009 if ( isset( $piece['eqpos'][$partIndex] ) ) {
3010 $eqpos = $piece['eqpos'][$partIndex];
3011 list( $ws1, $argName, $ws2 ) = self
::splitWhitespace( substr( $part, 0, $eqpos ) );
3012 list( $ws3, $argValue, $ws4 ) = self
::splitWhitespace( substr( $part, $eqpos +
1 ) );
3013 $element .= "<part>$ws1<name>$argName</name>$ws2=$ws3<value>$argValue</value>$ws4</part>";
3015 list( $ws1, $value, $ws2 ) = self
::splitWhitespace( $part );
3016 $element .= "<part>$ws1<name index=\"$argIndex\" /><value>$value</value>$ws2</part>";
3020 $element .= "</$name>";
3023 # Advance input pointer
3024 $i +
= $matchingCount;
3027 unset( $stack[$stackIndex--] );
3028 if ( $stackIndex == -1 ) {
3029 $accum =& $topAccum;
3030 $findEquals = false;
3033 $partCount = count( $stack[$stackIndex]['parts'] );
3034 $accum =& $stack[$stackIndex]['parts'][$partCount - 1];
3035 $findPipe = $stack[$stackIndex]['open'] != "\n";
3036 $findEquals = $findPipe && $partCount > 1
3037 && !isset( $stack[$stackIndex]['eqpos'][$partCount - 1] );
3040 # Re-add the old stack element if it still has unmatched opening characters remaining
3041 if ($matchingCount < $piece['count']) {
3042 $piece['parts'] = array( '' );
3043 $piece['count'] -= $matchingCount;
3044 $piece['eqpos'] = array();
3045 # do we still qualify for any callback with remaining count?
3046 $names = $rules[$piece['open']]['names'];
3048 $enclosingAccum =& $accum;
3049 while ( $piece['count'] ) {
3050 if ( array_key_exists( $piece['count'], $names ) ) {
3052 $stack[$stackIndex] = $piece;
3053 $accum =& $stack[$stackIndex]['parts'][0];
3061 $enclosingAccum .= str_repeat( $piece['open'], $skippedBraces );
3064 # Add XML element to the enclosing accumulator
3068 elseif ( $found == 'pipe' ) {
3069 $stack[$stackIndex]['parts'][] = '';
3070 $partsCount = count( $stack[$stackIndex]['parts'] );
3071 $accum =& $stack[$stackIndex]['parts'][$partsCount - 1];
3076 elseif ( $found == 'equals' ) {
3077 $findEquals = false;
3078 $partsCount = count( $stack[$stackIndex]['parts'] );
3079 $stack[$stackIndex]['eqpos'][$partsCount - 1] = strlen( $accum );
3085 # Output any remaining unclosed brackets
3086 foreach ( $stack as $piece ) {
3087 if ( $piece['open'] == "\n" ) {
3088 $topAccum .= $piece['parts'][0];
3090 $topAccum .= str_repeat( $piece['open'], $piece['count'] ) . implode( '|', $piece['parts'] );
3093 $topAccum .= '</root>';
3095 wfProfileOut( __METHOD__
.'-makexml' );
3096 wfProfileIn( __METHOD__
.'-loadXML' );
3097 $dom = new DOMDocument
;
3098 wfSuppressWarnings();
3099 $result = $dom->loadXML( $topAccum );
3100 wfRestoreWarnings();
3102 // Try running the XML through UtfNormal to get rid of invalid characters
3103 $topAccum = UtfNormal
::cleanUp( $topAccum );
3104 $result = $dom->loadXML( $topAccum );
3106 throw new MWException( __METHOD__
.' generated invalid XML' );
3109 wfProfileOut( __METHOD__
.'-loadXML' );
3110 wfProfileOut( __METHOD__
);
3115 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3117 public static function splitWhitespace( $s ) {
3118 $ltrimmed = ltrim( $s );
3119 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3120 $trimmed = rtrim( $ltrimmed );
3121 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3123 $w2 = substr( $ltrimmed, -$diff );
3127 return array( $w1, $trimmed, $w2 );
3131 * Replace magic variables, templates, and template arguments
3132 * with the appropriate text. Templates are substituted recursively,
3133 * taking care to avoid infinite loops.
3135 * Note that the substitution depends on value of $mOutputType:
3136 * OT_WIKI: only {{subst:}} templates
3137 * OT_MSG: only magic variables
3138 * OT_HTML: all templates and magic variables
3140 * @param string $tex The text to transform
3141 * @param PPFrame $frame Object describing the arguments passed to the template
3142 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3145 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3146 # Prevent too big inclusions
3147 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3151 $fname = __METHOD__
;
3152 wfProfileIn( $fname );
3154 if ( $frame === false ) {
3155 $frame = new PPFrame( $this );
3156 } elseif ( !( $frame instanceof PPFrame
) ) {
3157 throw new MWException( __METHOD__
. ' called using the old argument format' );
3160 $dom = $this->preprocessToDom( $text );
3161 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3162 $text = $frame->expand( $dom, $flags );
3164 wfProfileOut( $fname );
3168 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3169 static function createAssocArgs( $args ) {
3170 $assocArgs = array();
3172 foreach( $args as $arg ) {
3173 $eqpos = strpos( $arg, '=' );
3174 if ( $eqpos === false ) {
3175 $assocArgs[$index++
] = $arg;
3177 $name = trim( substr( $arg, 0, $eqpos ) );
3178 $value = trim( substr( $arg, $eqpos+
1 ) );
3179 if ( $value === false ) {
3182 if ( $name !== false ) {
3183 $assocArgs[$name] = $value;
3192 * Return the text of a template, after recursively
3193 * replacing any variables or templates within the template.
3195 * @param array $piece The parts of the template
3196 * $piece['text']: matched text
3197 * $piece['title']: the title, i.e. the part before the |
3198 * $piece['parts']: the parameter array
3199 * @param PPFrame The current frame, contains template arguments
3200 * @return string the text of the template
3203 function braceSubstitution( $piece, $frame ) {
3204 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
3205 $fname = __METHOD__
;
3206 wfProfileIn( $fname );
3207 wfProfileIn( __METHOD__
.'-setup' );
3210 $found = false; # $text has been filled
3211 $nowiki = false; # wiki markup in $text should be escaped
3212 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3213 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3214 $isDOM = false; # $text is a DOM node needing expansion
3216 # Title object, where $text came from
3219 # $part1 is the bit before the first |, and must contain only title characters.
3220 # Various prefixes will be stripped from it later.
3221 $titleWithSpaces = $frame->expand( $piece['title'] );
3222 $part1 = trim( $titleWithSpaces );
3225 # Original title text preserved for various purposes
3226 $originalTitle = $part1;
3228 # $args is a list of argument nodes, starting from index 0, not including $part1
3229 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
3230 wfProfileOut( __METHOD__
.'-setup' );
3233 wfProfileIn( __METHOD__
.'-modifiers' );
3235 $mwSubst =& MagicWord
::get( 'subst' );
3236 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
3237 # One of two possibilities is true:
3238 # 1) Found SUBST but not in the PST phase
3239 # 2) Didn't find SUBST and in the PST phase
3240 # In either case, return without further processing
3241 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3247 if ( !$found && $args->length
== 0 ) {
3248 $id = $this->mVariables
->matchStartToEnd( $part1 );
3249 if ( $id !== false ) {
3250 $text = $this->getVariableValue( $id );
3251 if (MagicWord
::getCacheTTL($id)>-1)
3252 $this->mOutput
->mContainsOldMagic
= true;
3257 # MSG, MSGNW and RAW
3260 $mwMsgnw =& MagicWord
::get( 'msgnw' );
3261 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3264 # Remove obsolete MSG:
3265 $mwMsg =& MagicWord
::get( 'msg' );
3266 $mwMsg->matchStartAndRemove( $part1 );
3270 $mwRaw =& MagicWord
::get( 'raw' );
3271 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3272 $forceRawInterwiki = true;
3275 wfProfileOut( __METHOD__
.'-modifiers' );
3279 wfProfileIn( __METHOD__
. '-pfunc' );
3281 $colonPos = strpos( $part1, ':' );
3282 if ( $colonPos !== false ) {
3283 # Case sensitive functions
3284 $function = substr( $part1, 0, $colonPos );
3285 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3286 $function = $this->mFunctionSynonyms
[1][$function];
3288 # Case insensitive functions
3289 $function = strtolower( $function );
3290 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3291 $function = $this->mFunctionSynonyms
[0][$function];
3297 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3298 $initialArgs = array( &$this );
3299 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3300 if ( $flags & SFH_OBJECT_ARGS
) {
3301 # Add a frame parameter, and pass the arguments as an array
3302 $allArgs = $initialArgs;
3303 $allArgs[] = $frame;
3304 foreach ( $args as $arg ) {
3307 $allArgs[] = $funcArgs;
3309 # Convert arguments to plain text
3310 foreach ( $args as $arg ) {
3311 $funcArgs[] = trim( $frame->expand( $arg ) );
3313 $allArgs = array_merge( $initialArgs, $funcArgs );
3316 $result = call_user_func_array( $callback, $allArgs );
3319 if ( is_array( $result ) ) {
3320 if ( isset( $result[0] ) ) {
3322 unset( $result[0] );
3325 // Extract flags into the local scope
3326 // This allows callers to set flags such as nowiki, found, etc.
3333 wfProfileOut( __METHOD__
. '-pfunc' );
3336 # Finish mangling title and then check for loops.
3337 # Set $title to a Title object and $titleText to the PDBK
3340 # Split the title into page and subpage
3342 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3343 if ($subpage !== '') {
3344 $ns = $this->mTitle
->getNamespace();
3346 $title = Title
::newFromText( $part1, $ns );
3348 $titleText = $title->getPrefixedText();
3349 # Check for language variants if the template is not found
3350 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3351 $wgContLang->findVariantLink($part1, $title);
3353 # Do infinite loop check
3354 if ( isset( $frame->loopCheckHash
[$titleText] ) ) {
3356 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
3357 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3359 # Do recursion depth check
3360 $limit = $this->mOptions
->getMaxTemplateDepth();
3361 if ( $frame->depth
>= $limit ) {
3363 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
3368 # Load from database
3369 if ( !$found && $title ) {
3370 wfProfileIn( __METHOD__
. '-loadtpl' );
3371 if ( !$title->isExternal() ) {
3372 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3373 $text = SpecialPage
::capturePath( $title );
3374 if ( is_string( $text ) ) {
3377 $this->disableCache();
3379 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3380 $found = false; //access denied
3381 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3383 list( $text, $title ) = $this->getTemplateDom( $title );
3384 if ( $text !== false ) {
3390 # If the title is valid but undisplayable, make a link to it
3391 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3392 $text = "[[:$titleText]]";
3395 } elseif ( $title->isTrans() ) {
3396 // Interwiki transclusion
3397 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3398 $text = $this->interwikiTransclude( $title, 'render' );
3401 $text = $this->interwikiTransclude( $title, 'raw' );
3402 // Preprocess it like a template
3403 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3408 wfProfileOut( __METHOD__
. '-loadtpl' );
3411 # If we haven't found text to substitute by now, we're done
3412 # Recover the source wikitext and return it
3414 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3415 wfProfileOut( $fname );
3419 # Expand DOM-style return values in a child frame
3421 # Clean up argument array
3422 $newFrame = $frame->newChild( $args, $title );
3423 # Add a new element to the templace loop detection hashtable
3424 $newFrame->loopCheckHash
[$titleText] = true;
3426 if ( $titleText !== false && count( $newFrame->args
) == 0 ) {
3427 # Expansion is eligible for the empty-frame cache
3428 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3429 $text = $this->mTplExpandCache
[$titleText];
3431 $text = $newFrame->expand( $text );
3432 $this->mTplExpandCache
[$titleText] = $text;
3435 # Uncached expansion
3436 $text = $newFrame->expand( $text );
3440 # Replace raw HTML by a placeholder
3441 # Add a blank line preceding, to prevent it from mucking up
3442 # immediately preceding headings
3444 $text = "\n\n" . $this->insertStripItem( $text );
3446 # Escape nowiki-style return values
3447 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3448 $text = wfEscapeWikiText( $text );
3450 # Bug 529: if the template begins with a table or block-level
3451 # element, it should be treated as beginning a new line.
3452 # This behaviour is somewhat controversial.
3453 elseif ( !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3454 $text = "\n" . $text;
3457 if ( !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3458 # Error, oversize inclusion
3459 $text = "[[$originalTitle]]" .
3460 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3463 wfProfileOut( $fname );
3468 * Get the semi-parsed DOM representation of a template with a given title,
3469 * and its redirect destination title. Cached.
3471 function getTemplateDom( $title ) {
3472 $cacheTitle = $title;
3473 $titleText = $title->getPrefixedDBkey();
3475 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3476 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3477 $title = Title
::makeTitle( $ns, $dbk );
3478 $titleText = $title->getPrefixedDBkey();
3480 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3481 return array( $this->mTplDomCache
[$titleText], $title );
3484 // Cache miss, go to the database
3485 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3487 if ( $text === false ) {
3488 $this->mTplDomCache
[$titleText] = false;
3489 return array( false, $title );
3492 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3493 $this->mTplDomCache
[ $titleText ] = $dom;
3495 if (! $title->equals($cacheTitle)) {
3496 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3497 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3500 return array( $dom, $title );
3504 * Fetch the unparsed text of a template and register a reference to it.
3506 function fetchTemplateAndTitle( $title ) {
3507 $templateCb = $this->mOptions
->getTemplateCallback();
3508 $stuff = call_user_func( $templateCb, $title );
3509 $text = $stuff['text'];
3510 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3511 if ( isset( $stuff['deps'] ) ) {
3512 foreach ( $stuff['deps'] as $dep ) {
3513 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3516 return array($text,$finalTitle);
3519 function fetchTemplate( $title ) {
3520 $rv = $this->fetchTemplateAndTitle($title);
3525 * Static function to get a template
3526 * Can be overridden via ParserOptions::setTemplateCallback().
3528 static function statelessFetchTemplate( $title ) {
3529 $text = $skip = false;
3530 $finalTitle = $title;
3533 // Loop to fetch the article, with up to 1 redirect
3534 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3535 # Give extensions a chance to select the revision instead
3536 $id = false; // Assume current
3537 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3543 'page_id' => $title->getArticleID(),
3547 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3548 $rev_id = $rev ?
$rev->getId() : 0;
3552 'page_id' => $title->getArticleID(),
3553 'rev_id' => $rev_id );
3556 $text = $rev->getText();
3557 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3559 $message = $wgLang->lcfirst( $title->getText() );
3560 $text = wfMsgForContentNoTrans( $message );
3561 if( wfEmptyMsg( $message, $text ) ) {
3568 if ( $text === false ) {
3572 $finalTitle = $title;
3573 $title = Title
::newFromRedirect( $text );
3577 'finalTitle' => $finalTitle,
3582 * Transclude an interwiki link.
3584 function interwikiTransclude( $title, $action ) {
3585 global $wgEnableScaryTranscluding;
3587 if (!$wgEnableScaryTranscluding)
3588 return wfMsg('scarytranscludedisabled');
3590 $url = $title->getFullUrl( "action=$action" );
3592 if (strlen($url) > 255)
3593 return wfMsg('scarytranscludetoolong');
3594 return $this->fetchScaryTemplateMaybeFromCache($url);
3597 function fetchScaryTemplateMaybeFromCache($url) {
3598 global $wgTranscludeCacheExpiry;
3599 $dbr = wfGetDB(DB_SLAVE
);
3600 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3601 array('tc_url' => $url));
3603 $time = $obj->tc_time
;
3604 $text = $obj->tc_contents
;
3605 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3610 $text = Http
::get($url);
3612 return wfMsg('scarytranscludefailed', $url);
3614 $dbw = wfGetDB(DB_MASTER
);
3615 $dbw->replace('transcache', array('tc_url'), array(
3617 'tc_time' => time(),
3618 'tc_contents' => $text));
3624 * Triple brace replacement -- used for template arguments
3627 function argSubstitution( $piece, $frame ) {
3628 wfProfileIn( __METHOD__
);
3632 $parts = $piece['parts'];
3633 $argWithSpaces = $frame->expand( $piece['title'] );
3634 $arg = trim( $argWithSpaces );
3636 if ( isset( $frame->args
[$arg] ) ) {
3637 $text = $frame->parent
->expand( $frame->args
[$arg] );
3638 } else if ( ( $this->ot
['html'] ||
$this->ot
['pre'] ) && $parts->length
> 0 ) {
3639 $text = $frame->expand( $parts->item( 0 ) );
3641 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3642 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3645 if ( $text === false ) {
3646 $text = '{{{' . $frame->implode( '|', $argWithSpaces, $parts ) . '}}}';
3648 if ( $error !== false ) {
3652 wfProfileOut( __METHOD__
);
3657 * Return the text to be used for a given extension tag.
3658 * This is the ghost of strip().
3660 * @param array $params Associative array of parameters:
3661 * name DOMNode for the tag name
3662 * attr DOMNode for unparsed text where tag attributes are thought to be
3663 * attributes Optional associative array of parsed attributes
3664 * inner Contents of extension element
3665 * noClose Original text did not have a close tag
3666 * @param PPFrame $frame
3668 function extensionSubstitution( $params, $frame ) {
3669 global $wgRawHtml, $wgContLang;
3672 $name = $frame->expand( $params['name'] );
3673 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3674 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3676 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
3678 if ( $this->ot
['html'] ) {
3679 $name = strtolower( $name );
3681 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3682 if ( isset( $params['attributes'] ) ) {
3683 $attributes = $attributes +
$params['attributes'];
3691 throw new MWException( '<html> extension tag encountered unexpectedly' );
3694 $output = Xml
::escapeTagsOnly( $content );
3697 $output = $wgContLang->armourMath(
3698 MathRenderer
::renderMath( $content, $attributes ) );
3701 $output = $this->renderImageGallery( $content, $attributes );
3704 if( isset( $this->mTagHooks
[$name] ) ) {
3705 $output = call_user_func_array( $this->mTagHooks
[$name],
3706 array( $content, $attributes, $this ) );
3708 throw new MWException( "Invalid call hook $name" );
3712 if ( $content === null ) {
3713 $output = "<$name$attrText/>";
3715 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3716 $output = "<$name$attrText>$content$close";
3720 if ( $name == 'html' ||
$name == 'nowiki' ) {
3721 $this->mStripState
->nowiki
->setPair( $marker, $output );
3723 $this->mStripState
->general
->setPair( $marker, $output );
3729 * Increment an include size counter
3731 * @param string $type The type of expansion
3732 * @param integer $size The size of the text
3733 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3735 function incrementIncludeSize( $type, $size ) {
3736 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3739 $this->mIncludeSizes
[$type] +
= $size;
3745 * Detect __NOGALLERY__ magic word and set a placeholder
3747 function stripNoGallery( &$text ) {
3748 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3750 $mw = MagicWord
::get( 'nogallery' );
3751 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3755 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3756 * placeholder that will then be replaced by the real TOC in
3757 * ->formatHeadings, this works because at this points real
3758 * comments will have already been discarded by the sanitizer.
3760 * Any additional __TOC__ magic words left over will be discarded
3761 * as there can only be one TOC on the page.
3763 function stripToc( $text ) {
3764 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3766 $mw = MagicWord
::get( 'notoc' );
3767 if( $mw->matchAndRemove( $text ) ) {
3768 $this->mShowToc
= false;
3771 $mw = MagicWord
::get( 'toc' );
3772 if( $mw->match( $text ) ) {
3773 $this->mShowToc
= true;
3774 $this->mForceTocPosition
= true;
3776 // Set a placeholder. At the end we'll fill it in with the TOC.
3777 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3779 // Only keep the first one.
3780 $text = $mw->replace( '', $text );
3786 * This function accomplishes several tasks:
3787 * 1) Auto-number headings if that option is enabled
3788 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3789 * 3) Add a Table of contents on the top for users who have enabled the option
3790 * 4) Auto-anchor headings
3792 * It loops through all headlines, collects the necessary data, then splits up the
3793 * string and re-inserts the newly formatted headlines.
3795 * @param string $text
3796 * @param boolean $isMain
3799 function formatHeadings( $text, $isMain=true ) {
3800 global $wgMaxTocLevel, $wgContLang;
3802 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3803 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3806 $showEditLink = $this->mOptions
->getEditSection();
3809 # Inhibit editsection links if requested in the page
3810 $esw =& MagicWord
::get( 'noeditsection' );
3811 if( $esw->matchAndRemove( $text ) ) {
3815 # Get all headlines for numbering them and adding funky stuff like [edit]
3816 # links - this is for later, but we need the number of headlines right now
3818 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3820 # if there are fewer than 4 headlines in the article, do not show TOC
3821 # unless it's been explicitly enabled.
3822 $enoughToc = $this->mShowToc
&&
3823 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3825 # Allow user to stipulate that a page should have a "new section"
3826 # link added via __NEWSECTIONLINK__
3827 $mw =& MagicWord
::get( 'newsectionlink' );
3828 if( $mw->matchAndRemove( $text ) )
3829 $this->mOutput
->setNewSection( true );
3831 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3832 # override above conditions and always show TOC above first header
3833 $mw =& MagicWord
::get( 'forcetoc' );
3834 if ($mw->matchAndRemove( $text ) ) {
3835 $this->mShowToc
= true;
3839 # We need this to perform operations on the HTML
3840 $sk = $this->mOptions
->getSkin();
3846 # Ugh .. the TOC should have neat indentation levels which can be
3847 # passed to the skin functions. These are determined here
3851 $sublevelCount = array();
3852 $levelCount = array();
3858 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3859 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3862 foreach( $matches[3] as $headline ) {
3863 $isTemplate = false;
3865 $sectionIndex = false;
3867 $markerMatches = array();
3868 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3869 $serial = $markerMatches[1];
3870 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3871 $isTemplate = ($titleText != $baseTitleText);
3872 $headline = preg_replace("/^$markerRegex/", "", $headline);
3876 $prevlevel = $level;
3877 $prevtoclevel = $toclevel;
3879 $level = $matches[1][$headlineCount];
3881 if( $doNumberHeadings ||
$enoughToc ) {
3883 if ( $level > $prevlevel ) {
3884 # Increase TOC level
3886 $sublevelCount[$toclevel] = 0;
3887 if( $toclevel<$wgMaxTocLevel ) {
3888 $prevtoclevel = $toclevel;
3889 $toc .= $sk->tocIndent();
3893 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3894 # Decrease TOC level, find level to jump to
3896 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3897 # Can only go down to level 1
3900 for ($i = $toclevel; $i > 0; $i--) {
3901 if ( $levelCount[$i] == $level ) {
3902 # Found last matching level
3906 elseif ( $levelCount[$i] < $level ) {
3907 # Found first matching level below current level
3913 if( $toclevel<$wgMaxTocLevel ) {
3914 if($prevtoclevel < $wgMaxTocLevel) {
3915 # Unindent only if the previous toc level was shown :p
3916 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3918 $toc .= $sk->tocLineEnd();
3923 # No change in level, end TOC line
3924 if( $toclevel<$wgMaxTocLevel ) {
3925 $toc .= $sk->tocLineEnd();
3929 $levelCount[$toclevel] = $level;
3931 # count number of headlines for each level
3932 @$sublevelCount[$toclevel]++
;
3934 for( $i = 1; $i <= $toclevel; $i++
) {
3935 if( !empty( $sublevelCount[$i] ) ) {
3939 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3945 # The safe header is a version of the header text safe to use for links
3946 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3947 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3949 # Remove link placeholders by the link text.
3950 # <!--LINK number-->
3952 # link text with suffix
3953 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3954 "\$this->mLinkHolders['texts'][\$1]",
3956 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3957 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3960 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3961 $tocline = preg_replace(
3962 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3966 $tocline = trim( $tocline );
3968 # For the anchor, strip out HTML-y stuff period
3969 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3970 $safeHeadline = trim( $safeHeadline );
3972 # Save headline for section edit hint before it's escaped
3973 $headlineHint = $safeHeadline;
3974 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3975 $refers[$headlineCount] = $safeHeadline;
3977 # count how many in assoc. array so we can track dupes in anchors
3978 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3979 $refcount[$headlineCount] = $refers[$safeHeadline];
3981 # Don't number the heading if it is the only one (looks silly)
3982 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3983 # the two are different if the line contains a link
3984 $headline=$numbering . ' ' . $headline;
3987 # Create the anchor for linking from the TOC to the section
3988 $anchor = $safeHeadline;
3989 if($refcount[$headlineCount] > 1 ) {
3990 $anchor .= '_' . $refcount[$headlineCount];
3992 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3993 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3994 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3996 # give headline the correct <h#> tag
3997 if( $showEditLink && $sectionIndex !== false ) {
3999 # Put a T flag in the section identifier, to indicate to extractSections()
4000 # that sections inside <includeonly> should be counted.
4001 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
4003 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
4008 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
4013 $this->mOutput
->setSections( $tocraw );
4015 # Never ever show TOC if no headers
4016 if( $numVisible < 1 ) {
4021 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4022 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
4024 $toc = $sk->tocList( $toc );
4027 # split up and insert constructed headlines
4029 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4032 foreach( $blocks as $block ) {
4033 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
4034 # This is the [edit] link that appears for the top block of text when
4035 # section editing is enabled
4037 # Disabled because it broke block formatting
4038 # For example, a bullet point in the top line
4039 # $full .= $sk->editSectionLink(0);
4042 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4043 # Top anchor now in skin
4047 if( !empty( $head[$i] ) ) {
4052 if( $this->mForceTocPosition
) {
4053 return str_replace( '<!--MWTOC-->', $toc, $full );
4060 * Transform wiki markup when saving a page by doing \r\n -> \n
4061 * conversion, substitting signatures, {{subst:}} templates, etc.
4063 * @param string $text the text to transform
4064 * @param Title &$title the Title object for the current article
4065 * @param User &$user the User object describing the current user
4066 * @param ParserOptions $options parsing options
4067 * @param bool $clearState whether to clear the parser state first
4068 * @return string the altered wiki markup
4071 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
4072 $this->mOptions
= $options;
4073 $this->mTitle
=& $title;
4074 $this->setOutputType( OT_WIKI
);
4076 if ( $clearState ) {
4077 $this->clearState();
4083 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4084 $text = $this->pstPass2( $text, $user );
4085 $text = $this->mStripState
->unstripBoth( $text );
4090 * Pre-save transform helper function
4093 function pstPass2( $text, $user ) {
4094 global $wgContLang, $wgLocaltimezone;
4096 /* Note: This is the timestamp saved as hardcoded wikitext to
4097 * the database, we use $wgContLang here in order to give
4098 * everyone the same signature and use the default one rather
4099 * than the one selected in each user's preferences.
4101 if ( isset( $wgLocaltimezone ) ) {
4102 $oldtz = getenv( 'TZ' );
4103 putenv( 'TZ='.$wgLocaltimezone );
4105 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
4106 ' (' . date( 'T' ) . ')';
4107 if ( isset( $wgLocaltimezone ) ) {
4108 putenv( 'TZ='.$oldtz );
4111 # Variable replacement
4112 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4113 $text = $this->replaceVariables( $text );
4115 # Strip out <nowiki> etc. added via replaceVariables
4116 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
4119 $sigText = $this->getUserSig( $user );
4120 $text = strtr( $text, array(
4122 '~~~~' => "$sigText $d",
4126 # Context links: [[|name]] and [[name (context)|]]
4128 global $wgLegalTitleChars;
4129 $tc = "[$wgLegalTitleChars]";
4130 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
4132 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4133 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4134 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4136 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4137 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4138 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4140 $t = $this->mTitle
->getText();
4142 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4143 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4144 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
4145 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4147 # if there's no context, don't bother duplicating the title
4148 $text = preg_replace( $p2, '[[\\1]]', $text );
4151 # Trim trailing whitespace
4152 $text = rtrim( $text );
4158 * Fetch the user's signature text, if any, and normalize to
4159 * validated, ready-to-insert wikitext.
4165 function getUserSig( &$user ) {
4166 global $wgMaxSigChars;
4168 $username = $user->getName();
4169 $nickname = $user->getOption( 'nickname' );
4170 $nickname = $nickname === '' ?
$username : $nickname;
4172 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4173 $nickname = $username;
4174 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4175 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
4176 # Sig. might contain markup; validate this
4177 if( $this->validateSig( $nickname ) !== false ) {
4178 # Validated; clean up (if needed) and return it
4179 return $this->cleanSig( $nickname, true );
4181 # Failed to validate; fall back to the default
4182 $nickname = $username;
4183 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
4187 // Make sure nickname doesnt get a sig in a sig
4188 $nickname = $this->cleanSigInSig( $nickname );
4190 # If we're still here, make it a link to the user page
4191 $userText = wfEscapeWikiText( $username );
4192 $nickText = wfEscapeWikiText( $nickname );
4193 if ( $user->isAnon() ) {
4194 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4196 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4201 * Check that the user's signature contains no bad XML
4203 * @param string $text
4204 * @return mixed An expanded string, or false if invalid.
4206 function validateSig( $text ) {
4207 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
4211 * Clean up signature text
4213 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4214 * 2) Substitute all transclusions
4216 * @param string $text
4217 * @param $parsing Whether we're cleaning (preferences save) or parsing
4218 * @return string Signature text
4220 function cleanSig( $text, $parsing = false ) {
4223 $this->startExternalParse( $wgTitle, new ParserOptions(), OT_MSG
);
4226 # FIXME: regex doesn't respect extension tags or nowiki
4227 # => Move this logic to braceSubstitution()
4228 $substWord = MagicWord
::get( 'subst' );
4229 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4230 $substText = '{{' . $substWord->getSynonym( 0 );
4232 $text = preg_replace( $substRegex, $substText, $text );
4233 $text = $this->cleanSigInSig( $text );
4234 $dom = $this->preprocessToDom( $text );
4235 $frame = new PPFrame( $this );
4236 $text = $frame->expand( $dom->documentElement
);
4239 $text = $this->mStripState
->unstripBoth( $text );
4246 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4247 * @param string $text
4248 * @return string Signature text with /~{3,5}/ removed
4250 function cleanSigInSig( $text ) {
4251 $text = preg_replace( '/~{3,5}/', '', $text );
4256 * Set up some variables which are usually set up in parse()
4257 * so that an external function can call some class members with confidence
4260 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4261 $this->mTitle
=& $title;
4262 $this->mOptions
= $options;
4263 $this->setOutputType( $outputType );
4264 if ( $clearState ) {
4265 $this->clearState();
4270 * Transform a MediaWiki message by replacing magic variables.
4272 * For some unknown reason, it also expands templates, but only to the
4273 * first recursion level. This is wrong and broken, probably introduced
4274 * accidentally during refactoring, but probably relied upon by thousands
4277 * @param string $text the text to transform
4278 * @param ParserOptions $options options
4279 * @return string the text with variables substituted
4282 function transformMsg( $text, $options ) {
4284 static $executing = false;
4286 $fname = "Parser::transformMsg";
4288 # Guard against infinite recursion
4294 wfProfileIn($fname);
4296 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
4297 $this->mTitle
= $wgTitle;
4299 $this->mTitle
= Title
::newFromText('msg');
4301 $this->mOptions
= $options;
4302 $this->setOutputType( OT_MSG
);
4303 $this->clearState();
4304 $text = $this->replaceVariables( $text );
4305 $text = $this->mStripState
->unstripBoth( $text );
4308 wfProfileOut($fname);
4313 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4314 * The callback should have the following form:
4315 * function myParserHook( $text, $params, &$parser ) { ... }
4317 * Transform and return $text. Use $parser for any required context, e.g. use
4318 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4322 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4323 * @param mixed $callback The callback function (and object) to use for the tag
4325 * @return The old value of the mTagHooks array associated with the hook
4327 function setHook( $tag, $callback ) {
4328 $tag = strtolower( $tag );
4329 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4330 $this->mTagHooks
[$tag] = $callback;
4331 $this->mStripList
[] = $tag;
4336 function setTransparentTagHook( $tag, $callback ) {
4337 $tag = strtolower( $tag );
4338 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4339 $this->mTransparentTagHooks
[$tag] = $callback;
4345 * Create a function, e.g. {{sum:1|2|3}}
4346 * The callback function should have the form:
4347 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4349 * The callback may either return the text result of the function, or an array with the text
4350 * in element 0, and a number of flags in the other elements. The names of the flags are
4351 * specified in the keys. Valid flags are:
4352 * found The text returned is valid, stop processing the template. This
4354 * nowiki Wiki markup in the return value should be escaped
4355 * isHTML The returned text is HTML, armour it against wikitext transformation
4359 * @param string $id The magic word ID
4360 * @param mixed $callback The callback function (and object) to use
4361 * @param integer $flags a combination of the following flags:
4362 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4364 * @return The old callback function for this name, if any
4366 function setFunctionHook( $id, $callback, $flags = 0 ) {
4367 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4368 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4370 # Add to function cache
4371 $mw = MagicWord
::get( $id );
4373 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4375 $synonyms = $mw->getSynonyms();
4376 $sensitive = intval( $mw->isCaseSensitive() );
4378 foreach ( $synonyms as $syn ) {
4380 if ( !$sensitive ) {
4381 $syn = strtolower( $syn );
4384 if ( !( $flags & SFH_NO_HASH
) ) {
4387 # Remove trailing colon
4388 if ( substr( $syn, -1, 1 ) == ':' ) {
4389 $syn = substr( $syn, 0, -1 );
4391 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4397 * Get all registered function hook identifiers
4401 function getFunctionHooks() {
4402 return array_keys( $this->mFunctionHooks
);
4406 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4407 * Placeholders created in Skin::makeLinkObj()
4408 * Returns an array of link CSS classes, indexed by PDBK.
4409 * $options is a bit field, RLH_FOR_UPDATE to select for update
4411 function replaceLinkHolders( &$text, $options = 0 ) {
4415 $fname = 'Parser::replaceLinkHolders';
4416 wfProfileIn( $fname );
4420 $linkcolour_ids = array();
4421 $sk = $this->mOptions
->getSkin();
4422 $linkCache =& LinkCache
::singleton();
4424 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4425 wfProfileIn( $fname.'-check' );
4426 $dbr = wfGetDB( DB_SLAVE
);
4427 $page = $dbr->tableName( 'page' );
4428 $threshold = $wgUser->getOption('stubthreshold');
4431 asort( $this->mLinkHolders
['namespaces'] );
4436 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4438 $title = $this->mLinkHolders
['titles'][$key];
4440 # Skip invalid entries.
4441 # Result will be ugly, but prevents crash.
4442 if ( is_null( $title ) ) {
4445 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4447 # Check if it's a static known link, e.g. interwiki
4448 if ( $title->isAlwaysKnown() ) {
4449 $colours[$pdbk] = '';
4450 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4451 $colours[$pdbk] = '';
4452 $this->mOutput
->addLink( $title, $id );
4453 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4454 $colours[$pdbk] = 'new';
4455 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4456 $colours[$pdbk] = 'new';
4458 # Not in the link cache, add it to the query
4459 if ( !isset( $current ) ) {
4461 $query = "SELECT page_id, page_namespace, page_title";
4462 if ( $threshold > 0 ) {
4463 $query .= ', page_len, page_is_redirect';
4465 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4466 } elseif ( $current != $ns ) {
4468 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4473 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4478 if ( $options & RLH_FOR_UPDATE
) {
4479 $query .= ' FOR UPDATE';
4482 $res = $dbr->query( $query, $fname );
4484 # Fetch data and form into an associative array
4485 # non-existent = broken
4486 while ( $s = $dbr->fetchObject($res) ) {
4487 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4488 $pdbk = $title->getPrefixedDBkey();
4489 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4490 $this->mOutput
->addLink( $title, $s->page_id
);
4491 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4492 //add id to the extension todolist
4493 $linkcolour_ids[$s->page_id
] = $pdbk;
4495 //pass an array of page_ids to an extension
4496 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4498 wfProfileOut( $fname.'-check' );
4500 # Do a second query for different language variants of links and categories
4501 if($wgContLang->hasVariants()){
4502 $linkBatch = new LinkBatch();
4503 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4504 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4505 $varCategories = array(); // category replacements oldDBkey => newDBkey
4507 $categories = $this->mOutput
->getCategoryLinks();
4509 // Add variants of links to link batch
4510 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4511 $title = $this->mLinkHolders
['titles'][$key];
4512 if ( is_null( $title ) )
4515 $pdbk = $title->getPrefixedDBkey();
4516 $titleText = $title->getText();
4518 // generate all variants of the link title text
4519 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4521 // if link was not found (in first query), add all variants to query
4522 if ( !isset($colours[$pdbk]) ){
4523 foreach($allTextVariants as $textVariant){
4524 if($textVariant != $titleText){
4525 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4526 if(is_null($variantTitle)) continue;
4527 $linkBatch->addObj( $variantTitle );
4528 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4534 // process categories, check if a category exists in some variant
4535 foreach( $categories as $category ){
4536 $variants = $wgContLang->convertLinkToAllVariants($category);
4537 foreach($variants as $variant){
4538 if($variant != $category){
4539 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4540 if(is_null($variantTitle)) continue;
4541 $linkBatch->addObj( $variantTitle );
4542 $categoryMap[$variant] = $category;
4548 if(!$linkBatch->isEmpty()){
4550 $titleClause = $linkBatch->constructSet('page', $dbr);
4552 $variantQuery = "SELECT page_id, page_namespace, page_title";
4553 if ( $threshold > 0 ) {
4554 $variantQuery .= ', page_len, page_is_redirect';
4557 $variantQuery .= " FROM $page WHERE $titleClause";
4558 if ( $options & RLH_FOR_UPDATE
) {
4559 $variantQuery .= ' FOR UPDATE';
4562 $varRes = $dbr->query( $variantQuery, $fname );
4564 // for each found variants, figure out link holders and replace
4565 while ( $s = $dbr->fetchObject($varRes) ) {
4567 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4568 $varPdbk = $variantTitle->getPrefixedDBkey();
4569 $vardbk = $variantTitle->getDBkey();
4571 $holderKeys = array();
4572 if(isset($variantMap[$varPdbk])){
4573 $holderKeys = $variantMap[$varPdbk];
4574 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4575 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4578 // loop over link holders
4579 foreach($holderKeys as $key){
4580 $title = $this->mLinkHolders
['titles'][$key];
4581 if ( is_null( $title ) ) continue;
4583 $pdbk = $title->getPrefixedDBkey();
4585 if(!isset($colours[$pdbk])){
4586 // found link in some of the variants, replace the link holder data
4587 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4588 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4590 // set pdbk and colour
4591 $pdbks[$key] = $varPdbk;
4592 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4593 $linkcolour_ids[$s->page_id
] = $pdbk;
4595 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4598 // check if the object is a variant of a category
4599 if(isset($categoryMap[$vardbk])){
4600 $oldkey = $categoryMap[$vardbk];
4601 if($oldkey != $vardbk)
4602 $varCategories[$oldkey]=$vardbk;
4606 // rebuild the categories in original order (if there are replacements)
4607 if(count($varCategories)>0){
4609 $originalCats = $this->mOutput
->getCategories();
4610 foreach($originalCats as $cat => $sortkey){
4611 // make the replacement
4612 if( array_key_exists($cat,$varCategories) )
4613 $newCats[$varCategories[$cat]] = $sortkey;
4614 else $newCats[$cat] = $sortkey;
4616 $this->mOutput
->setCategoryLinks($newCats);
4621 # Construct search and replace arrays
4622 wfProfileIn( $fname.'-construct' );
4623 $replacePairs = array();
4624 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4625 $pdbk = $pdbks[$key];
4626 $searchkey = "<!--LINK $key-->";
4627 $title = $this->mLinkHolders
['titles'][$key];
4628 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4629 $linkCache->addBadLinkObj( $title );
4630 $colours[$pdbk] = 'new';
4631 $this->mOutput
->addLink( $title, 0 );
4632 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4633 $this->mLinkHolders
['texts'][$key],
4634 $this->mLinkHolders
['queries'][$key] );
4636 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4637 $this->mLinkHolders
['texts'][$key],
4638 $this->mLinkHolders
['queries'][$key] );
4641 $replacer = new HashtableReplacer( $replacePairs, 1 );
4642 wfProfileOut( $fname.'-construct' );
4645 wfProfileIn( $fname.'-replace' );
4646 $text = preg_replace_callback(
4647 '/(<!--LINK .*?-->)/',
4651 wfProfileOut( $fname.'-replace' );
4654 # Now process interwiki link holders
4655 # This is quite a bit simpler than internal links
4656 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4657 wfProfileIn( $fname.'-interwiki' );
4658 # Make interwiki link HTML
4659 $replacePairs = array();
4660 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4661 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4662 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4664 $replacer = new HashtableReplacer( $replacePairs, 1 );
4666 $text = preg_replace_callback(
4667 '/<!--IWLINK (.*?)-->/',
4670 wfProfileOut( $fname.'-interwiki' );
4673 wfProfileOut( $fname );
4678 * Replace <!--LINK--> link placeholders with plain text of links
4679 * (not HTML-formatted).
4680 * @param string $text
4683 function replaceLinkHoldersText( $text ) {
4684 $fname = 'Parser::replaceLinkHoldersText';
4685 wfProfileIn( $fname );
4687 $text = preg_replace_callback(
4688 '/<!--(LINK|IWLINK) (.*?)-->/',
4689 array( &$this, 'replaceLinkHoldersTextCallback' ),
4692 wfProfileOut( $fname );
4697 * @param array $matches
4701 function replaceLinkHoldersTextCallback( $matches ) {
4702 $type = $matches[1];
4704 if( $type == 'LINK' ) {
4705 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4706 return $this->mLinkHolders
['texts'][$key];
4708 } elseif( $type == 'IWLINK' ) {
4709 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4710 return $this->mInterwikiLinkHolders
['texts'][$key];
4717 * Tag hook handler for 'pre'.
4719 function renderPreTag( $text, $attribs ) {
4720 // Backwards-compatibility hack
4721 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4723 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4724 return wfOpenElement( 'pre', $attribs ) .
4725 Xml
::escapeTagsOnly( $content ) .
4730 * Renders an image gallery from a text with one line per image.
4731 * text labels may be given by using |-style alternative text. E.g.
4732 * Image:one.jpg|The number "1"
4733 * Image:tree.jpg|A tree
4734 * given as text will return the HTML of a gallery with two images,
4735 * labeled 'The number "1"' and
4738 function renderImageGallery( $text, $params ) {
4739 $ig = new ImageGallery();
4740 $ig->setContextTitle( $this->mTitle
);
4741 $ig->setShowBytes( false );
4742 $ig->setShowFilename( false );
4743 $ig->setParser( $this );
4744 $ig->setHideBadImages();
4745 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4746 $ig->useSkin( $this->mOptions
->getSkin() );
4747 $ig->mRevisionId
= $this->mRevisionId
;
4749 if( isset( $params['caption'] ) ) {
4750 $caption = $params['caption'];
4751 $caption = htmlspecialchars( $caption );
4752 $caption = $this->replaceInternalLinks( $caption );
4753 $ig->setCaptionHtml( $caption );
4755 if( isset( $params['perrow'] ) ) {
4756 $ig->setPerRow( $params['perrow'] );
4758 if( isset( $params['widths'] ) ) {
4759 $ig->setWidths( $params['widths'] );
4761 if( isset( $params['heights'] ) ) {
4762 $ig->setHeights( $params['heights'] );
4765 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4767 $lines = explode( "\n", $text );
4768 foreach ( $lines as $line ) {
4769 # match lines like these:
4770 # Image:someimage.jpg|This is some image
4772 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4774 if ( count( $matches ) == 0 ) {
4777 $tp = Title
::newFromText( $matches[1] );
4779 if( is_null( $nt ) ) {
4780 # Bogus title. Ignore these so we don't bomb out later.
4783 if ( isset( $matches[3] ) ) {
4784 $label = $matches[3];
4789 $pout = $this->parse( $label,
4792 false, // Strip whitespace...?
4793 false // Don't clear state!
4795 $html = $pout->getText();
4797 $ig->add( $nt, $html );
4799 # Only add real images (bug #5586)
4800 if ( $nt->getNamespace() == NS_IMAGE
) {
4801 $this->mOutput
->addImage( $nt->getDBkey() );
4804 return $ig->toHTML();
4807 function getImageParams( $handler ) {
4809 $handlerClass = get_class( $handler );
4813 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4814 // Initialise static lists
4815 static $internalParamNames = array(
4816 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4817 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4818 'bottom', 'text-bottom' ),
4819 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4820 'upright', 'border' ),
4822 static $internalParamMap;
4823 if ( !$internalParamMap ) {
4824 $internalParamMap = array();
4825 foreach ( $internalParamNames as $type => $names ) {
4826 foreach ( $names as $name ) {
4827 $magicName = str_replace( '-', '_', "img_$name" );
4828 $internalParamMap[$magicName] = array( $type, $name );
4833 // Add handler params
4834 $paramMap = $internalParamMap;
4836 $handlerParamMap = $handler->getParamMap();
4837 foreach ( $handlerParamMap as $magic => $paramName ) {
4838 $paramMap[$magic] = array( 'handler', $paramName );
4841 $this->mImageParams
[$handlerClass] = $paramMap;
4842 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4844 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4848 * Parse image options text and use it to make an image
4850 function makeImage( $title, $options ) {
4851 # @TODO: let the MediaHandler specify its transform parameters
4853 # Check if the options text is of the form "options|alt text"
4855 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4856 # * left no resizing, just left align. label is used for alt= only
4857 # * right same, but right aligned
4858 # * none same, but not aligned
4859 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4860 # * center center the image
4861 # * framed Keep original image size, no magnify-button.
4862 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4863 # * upright reduce width for upright images, rounded to full __0 px
4864 # * border draw a 1px border around the image
4865 # vertical-align values (no % or length right now):
4875 $parts = array_map( 'trim', explode( '|', $options) );
4876 $sk = $this->mOptions
->getSkin();
4878 # Give extensions a chance to select the file revision for us
4879 $skip = $time = false;
4880 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4883 return $sk->makeLinkObj( $title );
4887 $file = wfFindFile( $title, $time );
4888 $handler = $file ?
$file->getHandler() : false;
4890 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4892 # Process the input parameters
4894 $params = array( 'frame' => array(), 'handler' => array(),
4895 'horizAlign' => array(), 'vertAlign' => array() );
4896 foreach( $parts as $part ) {
4897 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4898 if ( isset( $paramMap[$magicName] ) ) {
4899 list( $type, $paramName ) = $paramMap[$magicName];
4900 $params[$type][$paramName] = $value;
4902 // Special case; width and height come in one variable together
4903 if( $type == 'handler' && $paramName == 'width' ) {
4905 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4906 $params[$type]['width'] = intval( $m[1] );
4907 $params[$type]['height'] = intval( $m[2] );
4909 $params[$type]['width'] = intval( $value );
4917 # Process alignment parameters
4918 if ( $params['horizAlign'] ) {
4919 $params['frame']['align'] = key( $params['horizAlign'] );
4921 if ( $params['vertAlign'] ) {
4922 $params['frame']['valign'] = key( $params['vertAlign'] );
4925 # Validate the handler parameters
4927 foreach ( $params['handler'] as $name => $value ) {
4928 if ( !$handler->validateParam( $name, $value ) ) {
4929 unset( $params['handler'][$name] );
4934 # Strip bad stuff out of the alt text
4935 $alt = $this->replaceLinkHoldersText( $caption );
4937 # make sure there are no placeholders in thumbnail attributes
4938 # that are later expanded to html- so expand them now and
4940 $alt = $this->mStripState
->unstripBoth( $alt );
4941 $alt = Sanitizer
::stripAllTags( $alt );
4943 $params['frame']['alt'] = $alt;
4944 $params['frame']['caption'] = $caption;
4946 # Linker does the rest
4947 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4949 # Give the handler a chance to modify the parser object
4951 $handler->parserTransformHook( $this, $file );
4958 * Set a flag in the output object indicating that the content is dynamic and
4959 * shouldn't be cached.
4961 function disableCache() {
4962 wfDebug( "Parser output marked as uncacheable.\n" );
4963 $this->mOutput
->mCacheTime
= -1;
4967 * Callback from the Sanitizer for expanding items found in HTML attribute
4968 * values, so they can be safely tested and escaped.
4969 * @param string $text
4970 * @param PPFrame $frame
4974 function attributeStripCallback( &$text, $frame = false ) {
4975 $text = $this->replaceVariables( $text, $frame );
4976 $text = $this->mStripState
->unstripBoth( $text );
4985 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4986 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4987 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4993 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4998 * Break wikitext input into sections, and either pull or replace
4999 * some particular section's text.
5001 * External callers should use the getSection and replaceSection methods.
5003 * @param string $text Page wikitext
5004 * @param string $section A section identifier string of the form:
5005 * <flag1> - <flag2> - ... - <section number>
5007 * Currently the only recognised flag is "T", which means the target section number
5008 * was derived during a template inclusion parse, in other words this is a template
5009 * section edit link. If no flags are given, it was an ordinary section edit link.
5010 * This flag is required to avoid a section numbering mismatch when a section is
5011 * enclosed by <includeonly> (bug 6563).
5013 * The section number 0 pulls the text before the first heading; other numbers will
5014 * pull the given section along with its lower-level subsections. If the section is
5015 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5017 * @param string $mode One of "get" or "replace"
5018 * @param string $newText Replacement text for section data.
5019 * @return string for "get", the extracted section text.
5020 * for "replace", the whole page with the section replaced.
5022 private function extractSections( $text, $section, $mode, $newText='' ) {
5024 $this->clearState();
5025 $this->mTitle
= $wgTitle; // not generally used but removes an ugly failure mode
5026 $this->mOptions
= new ParserOptions
;
5027 $this->setOutputType( OT_WIKI
);
5030 $frame = new PPFrame( $this );
5032 // Process section extraction flags
5034 $sectionParts = explode( '-', $section );
5035 $sectionIndex = array_pop( $sectionParts );
5036 foreach ( $sectionParts as $part ) {
5037 if ( $part == 'T' ) {
5038 $flags |
= self
::PTD_FOR_INCLUSION
;
5041 // Preprocess the text
5042 $dom = $this->preprocessToDom( $text, $flags );
5043 $root = $dom->documentElement
;
5045 // <h> nodes indicate section breaks
5046 // They can only occur at the top level, so we can find them by iterating the root's children
5047 $node = $root->firstChild
;
5049 // Find the target section
5050 if ( $sectionIndex == 0 ) {
5051 // Section zero doesn't nest, level=big
5052 $targetLevel = 1000;
5055 if ( $node->nodeName
== 'h' ) {
5056 if ( $curIndex +
1 == $sectionIndex ) {
5061 if ( $mode == 'replace' ) {
5062 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5064 $node = $node->nextSibling
;
5067 $targetLevel = $node->getAttribute( 'level' );
5073 if ( $mode == 'get' ) {
5080 // Find the end of the section, including nested sections
5082 if ( $node->nodeName
== 'h' ) {
5084 $curLevel = $node->getAttribute( 'level' );
5085 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
5089 if ( $mode == 'get' ) {
5090 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5092 $node = $node->nextSibling
;
5095 // Write out the remainder (in replace mode only)
5096 if ( $mode == 'replace' ) {
5097 // Output the replacement text
5098 // Add two newlines on -- trailing whitespace in $newText is conventionally
5099 // stripped by the editor, so we need both newlines to restore the paragraph gap
5100 $outText .= $newText . "\n\n";
5102 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5103 $node = $node->nextSibling
;
5107 if ( is_string( $outText ) ) {
5108 // Re-insert stripped tags
5109 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
5116 * This function returns the text of a section, specified by a number ($section).
5117 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5118 * the first section before any such heading (section 0).
5120 * If a section contains subsections, these are also returned.
5122 * @param string $text text to look in
5123 * @param string $section section identifier
5124 * @param string $deftext default to return if section is not found
5125 * @return string text of the requested section
5127 public function getSection( $text, $section, $deftext='' ) {
5128 return $this->extractSections( $text, $section, "get", $deftext );
5131 public function replaceSection( $oldtext, $section, $text ) {
5132 return $this->extractSections( $oldtext, $section, "replace", $text );
5136 * Get the timestamp associated with the current revision, adjusted for
5137 * the default server-local timestamp
5139 function getRevisionTimestamp() {
5140 if ( is_null( $this->mRevisionTimestamp
) ) {
5141 wfProfileIn( __METHOD__
);
5143 $dbr = wfGetDB( DB_SLAVE
);
5144 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5145 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
5147 // Normalize timestamp to internal MW format for timezone processing.
5148 // This has the added side-effect of replacing a null value with
5149 // the current time, which gives us more sensible behavior for
5151 $timestamp = wfTimestamp( TS_MW
, $timestamp );
5153 // The cryptic '' timezone parameter tells to use the site-default
5154 // timezone offset instead of the user settings.
5156 // Since this value will be saved into the parser cache, served
5157 // to other users, and potentially even used inside links and such,
5158 // it needs to be consistent for all visitors.
5159 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5161 wfProfileOut( __METHOD__
);
5163 return $this->mRevisionTimestamp
;
5167 * Mutator for $mDefaultSort
5169 * @param $sort New value
5171 public function setDefaultSort( $sort ) {
5172 $this->mDefaultSort
= $sort;
5176 * Accessor for $mDefaultSort
5177 * Will use the title/prefixed title if none is set
5181 public function getDefaultSort() {
5182 if( $this->mDefaultSort
!== false ) {
5183 return $this->mDefaultSort
;
5185 return $this->mTitle
->getNamespace() == NS_CATEGORY
5186 ?
$this->mTitle
->getText()
5187 : $this->mTitle
->getPrefixedText();
5192 * Try to guess the section anchor name based on a wikitext fragment
5193 * presumably extracted from a heading, for example "Header" from
5196 public function guessSectionNameFromWikiText( $text ) {
5197 # Strip out wikitext links(they break the anchor)
5198 $text = $this->stripSectionName( $text );
5199 $headline = Sanitizer
::decodeCharReferences( $text );
5201 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5202 $headline = trim( $headline );
5203 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5204 $replacearray = array(
5209 array_keys( $replacearray ),
5210 array_values( $replacearray ),
5215 * Strips a text string of wikitext for use in a section anchor
5217 * Accepts a text string and then removes all wikitext from the
5218 * string and leaves only the resultant text (i.e. the result of
5219 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5220 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5221 * to create valid section anchors by mimicing the output of the
5222 * parser when headings are parsed.
5224 * @param $text string Text string to be stripped of wikitext
5225 * for use in a Section anchor
5226 * @return Filtered text string
5228 public function stripSectionName( $text ) {
5229 # Strip internal link markup
5230 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5231 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5233 # Strip external link markup (FIXME: Not Tolerant to blank link text
5234 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5235 # on how many empty links there are on the page - need to figure that out.
5236 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5238 # Parse wikitext quotes (italics & bold)
5239 $text = $this->doQuotes($text);
5242 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5247 * strip/replaceVariables/unstrip for preprocessor regression testing
5249 function srvus( $text ) {
5250 $text = $this->replaceVariables( $text );
5251 $text = $this->mStripState
->unstripBoth( $text );
5252 $text = Sanitizer
::removeHTMLtags( $text );
5258 * @todo document, briefly.
5259 * @addtogroup Parser
5261 class OnlyIncludeReplacer
{
5264 function replace( $matches ) {
5265 if ( substr( $matches[1], -1 ) == "\n" ) {
5266 $this->output
.= substr( $matches[1], 0, -1 );
5268 $this->output
.= $matches[1];
5274 * @todo document, briefly.
5275 * @addtogroup Parser
5278 var $general, $nowiki;
5280 function __construct() {
5281 $this->general
= new ReplacementArray
;
5282 $this->nowiki
= new ReplacementArray
;
5285 function unstripGeneral( $text ) {
5286 wfProfileIn( __METHOD__
);
5289 $text = $this->general
->replace( $text );
5290 } while ( $text != $oldText );
5291 wfProfileOut( __METHOD__
);
5295 function unstripNoWiki( $text ) {
5296 wfProfileIn( __METHOD__
);
5299 $text = $this->nowiki
->replace( $text );
5300 } while ( $text != $oldText );
5301 wfProfileOut( __METHOD__
);
5305 function unstripBoth( $text ) {
5306 wfProfileIn( __METHOD__
);
5309 $text = $this->general
->replace( $text );
5310 $text = $this->nowiki
->replace( $text );
5311 } while ( $text != $oldText );
5312 wfProfileOut( __METHOD__
);
5318 * An expansion frame, used as a context to expand the result of preprocessToDom()
5321 var $parser, $title;
5325 * Hashtable listing templates which are disallowed for expansion in this frame,
5326 * having been encountered previously in parent frames.
5331 * Recursion depth of this frame, top = 0
5336 const NO_TEMPLATES
= 2;
5337 const STRIP_COMMENTS
= 4;
5338 const NO_IGNORE
= 8;
5340 const RECOVER_ORIG
= 11;
5343 * Construct a new preprocessor frame.
5344 * @param Parser $parser The parent parser
5345 * @param Title $title The context title, or false if there isn't one
5347 function __construct( $parser ) {
5348 $this->parser
= $parser;
5349 $this->title
= $parser->mTitle
;
5350 $this->titleCache
= array( $this->title ?
$this->title
->getPrefixedDBkey() : false );
5351 $this->loopCheckHash
= array();
5356 * Create a new child frame
5357 * $args is optionally a DOMNodeList containing the template arguments
5359 function newChild( $args = false, $title = false ) {
5360 $assocArgs = array();
5361 if ( $title === false ) {
5362 $title = $this->title
;
5364 if ( $args !== false ) {
5366 foreach ( $args as $arg ) {
5368 $xpath = new DOMXPath( $arg->ownerDocument
);
5371 $nameNodes = $xpath->query( 'name', $arg );
5372 if ( $nameNodes->item( 0 )->hasAttributes() ) {
5373 // Numbered parameter
5374 $name = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
5377 $name = $this->expand( $nameNodes->item( 0 ), PPFrame
::STRIP_COMMENTS
);
5380 $value = $xpath->query( 'value', $arg );
5381 $assocArgs[$name] = $value->item( 0 );
5384 return new PPTemplateFrame( $this->parser
, $this, $assocArgs, $title );
5388 * Expand a DOMNode describing a preprocessed document into plain wikitext,
5389 * using the current context
5390 * @param $root the node
5392 function expand( $root, $flags = 0 ) {
5393 if ( is_string( $root ) ) {
5397 if ( $this->parser
->ot
['html']
5398 && ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
5400 return $this->parser
->insertStripItem( '<!-- node-count limit exceeded -->' );
5403 if ( is_array( $root ) ) {
5405 foreach ( $root as $node ) {
5406 $s .= $this->expand( $node, $flags );
5408 } elseif ( $root instanceof DOMNodeList
) {
5410 foreach ( $root as $node ) {
5411 $s .= $this->expand( $node, $flags );
5413 } elseif ( $root instanceof DOMNode
) {
5414 if ( $root->nodeType
== XML_TEXT_NODE
) {
5415 $s = $root->nodeValue
;
5416 } elseif ( $root->nodeName
== 'template' ) {
5417 # Double-brace expansion
5418 $xpath = new DOMXPath( $root->ownerDocument
);
5419 $titles = $xpath->query( 'title', $root );
5420 $title = $titles->item( 0 );
5421 $parts = $xpath->query( 'part', $root );
5422 if ( $flags & self
::NO_TEMPLATES
) {
5423 $s = '{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}';
5425 $lineStart = $root->getAttribute( 'lineStart' );
5429 'lineStart' => $lineStart,
5430 'text' => 'FIXME' );
5431 $s = $this->parser
->braceSubstitution( $params, $this );
5433 } elseif ( $root->nodeName
== 'tplarg' ) {
5434 # Triple-brace expansion
5435 $xpath = new DOMXPath( $root->ownerDocument
);
5436 $titles = $xpath->query( 'title', $root );
5437 $title = $titles->item( 0 );
5438 $parts = $xpath->query( 'part', $root );
5439 if ( $flags & self
::NO_ARGS ||
$this->parser
->ot
['msg'] ) {
5440 $s = '{{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}}';
5442 $params = array( 'title' => $title, 'parts' => $parts, 'text' => 'FIXME' );
5443 $s = $this->parser
->argSubstitution( $params, $this );
5445 } elseif ( $root->nodeName
== 'comment' ) {
5446 # HTML-style comment
5447 if ( $this->parser
->ot
['html']
5448 ||
( $this->parser
->ot
['pre'] && $this->parser
->mOptions
->getRemoveComments() )
5449 ||
( $flags & self
::STRIP_COMMENTS
) )
5453 $s = $root->textContent
;
5455 } elseif ( $root->nodeName
== 'ignore' ) {
5456 # Output suppression used by <includeonly> etc.
5457 # OT_WIKI will only respect <ignore> in substed templates.
5458 # The other output types respect it unless NO_IGNORE is set.
5459 # extractSections() sets NO_IGNORE and so never respects it.
5460 if ( ( !isset( $this->parent
) && $this->parser
->ot
['wiki'] ) ||
( $flags & self
::NO_IGNORE
) ) {
5461 $s = $root->textContent
;
5465 } elseif ( $root->nodeName
== 'ext' ) {
5467 $xpath = new DOMXPath( $root->ownerDocument
);
5468 $names = $xpath->query( 'name', $root );
5469 $attrs = $xpath->query( 'attr', $root );
5470 $inners = $xpath->query( 'inner', $root );
5471 $closes = $xpath->query( 'close', $root );
5473 'name' => $names->item( 0 ),
5474 'attr' => $attrs->length
> 0 ?
$attrs->item( 0 ) : null,
5475 'inner' => $inners->length
> 0 ?
$inners->item( 0 ) : null,
5476 'close' => $closes->length
> 0 ?
$closes->item( 0 ) : null,
5478 $s = $this->parser
->extensionSubstitution( $params, $this );
5479 } elseif ( $root->nodeName
== 'h' ) {
5481 $s = $this->expand( $root->childNodes
, $flags );
5483 if ( $this->parser
->ot
['html'] ) {
5484 # Insert heading index marker
5485 $headingIndex = $root->getAttribute( 'i' );
5486 $titleText = $this->title
->getPrefixedDBkey();
5487 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
5488 $serial = count( $this->parser
->mHeadings
) - 1;
5489 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
5490 $count = $root->getAttribute( 'level' );
5491 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
5492 $this->parser
->mStripState
->general
->setPair( $marker, '' );
5495 # Generic recursive expansion
5497 for ( $node = $root->firstChild
; $node; $node = $node->nextSibling
) {
5498 if ( $node->nodeType
== XML_TEXT_NODE
) {
5499 $s .= $node->nodeValue
;
5500 } elseif ( $node->nodeType
== XML_ELEMENT_NODE
) {
5501 $s .= $this->expand( $node, $flags );
5506 throw new MWException( __METHOD__
.': Invalid parameter type' );
5511 function implodeWithFlags( $sep, $flags /*, ... */ ) {
5512 $args = array_slice( func_get_args(), 2 );
5516 foreach ( $args as $root ) {
5517 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
5518 $root = array( $root );
5520 foreach ( $root as $node ) {
5526 $s .= $this->expand( $node, $flags );
5532 function implode( $sep /*, ... */ ) {
5533 $args = func_get_args();
5534 $args = array_merge( array_slice( $args, 0, 1 ), array( 0 ), array_slice( $args, 1 ) );
5535 return call_user_func_array( array( $this, 'implodeWithFlags' ), $args );
5539 * Split an <arg> or <template> node into a three-element array:
5540 * DOMNode name, string index and DOMNode value
5542 function splitBraceNode( $node ) {
5543 $xpath = new DOMXPath( $node->ownerDocument
);
5544 $names = $xpath->query( 'name', $node );
5545 $values = $xpath->query( 'value', $node );
5546 if ( !$names->length ||
!$values->length
) {
5547 throw new MWException( 'Invalid brace node passed to ' . __METHOD__
);
5549 $name = $names->item( 0 );
5550 $index = $name->getAttribute( 'index' );
5551 return array( $name, $index, $values->item( 0 ) );
5555 * Split an <ext> node into an associative array containing name, attr, inner and close
5556 * All values in the resulting array are DOMNodes. Inner and close are optional.
5558 function splitExtNode( $node ) {
5559 $xpath = new DOMXPath( $node->ownerDocument
);
5560 $names = $xpath->query( 'name', $node );
5561 $attrs = $xpath->query( 'attr', $node );
5562 $inners = $xpath->query( 'inner', $node );
5563 $closes = $xpath->query( 'close', $node );
5564 if ( !$names->length ||
!$attrs->length
) {
5565 throw new MWException( 'Invalid ext node passed to ' . __METHOD__
);
5568 'name' => $names->item( 0 ),
5569 'attr' => $attrs->item( 0 ) );
5570 if ( $inners->length
) {
5571 $parts['inner'] = $inners->item( 0 );
5573 if ( $closes->length
) {
5574 $parts['close'] = $closes->item( 0 );
5579 function __toString() {
5583 function getPDBK( $level = false ) {
5584 if ( $level === false ) {
5585 return $this->title
->getPrefixedDBkey();
5587 return isset( $this->titleCache
[$level] ) ?
$this->titleCache
[$level] : false;
5593 * Expansion frame with template arguments
5595 class PPTemplateFrame
extends PPFrame
{
5598 function __construct( $parser, $parent = false, $args = array(), $title = false ) {
5599 $this->parser
= $parser;
5600 $this->parent
= $parent;
5601 $this->args
= $args;
5602 $this->title
= $title;
5603 $this->titleCache
= $parent->titleCache
;
5604 $this->titleCache
[] = $title ?
$title->getPrefixedDBkey() : false;
5605 $this->loopCheckHash
= /*clone*/ $parent->loopCheckHash
;
5606 $this->depth
= $parent->depth +
1;
5609 function __toString() {
5612 foreach ( $this->args
as $name => $value ) {
5618 $s .= "\"$name\":\"" .
5619 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';