3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
16 define( 'RLH_FOR_UPDATE', 1 );
18 # Allowed values for $mOutputType
19 define( 'OT_HTML', 1 );
20 define( 'OT_WIKI', 2 );
21 define( 'OT_MSG' , 3 );
22 define( 'OT_PREPROCESS', 4 );
24 # Flags for setFunctionHook
25 define( 'SFH_NO_HASH', 1 );
27 # string parameter for extractTags which will cause it
28 # to strip HTML comments in addition to regular
29 # <XML>-style tags. This should not be anything we
30 # may want to use in wikisyntax
31 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
33 # Constants needed for external link processing
34 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
35 # Everything except bracket, space, or control characters
36 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
37 # Including space, but excluding newlines
38 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
39 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
40 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
41 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
42 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
43 define( 'EXT_IMAGE_REGEX',
44 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
45 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
46 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
49 // State constants for the definition list colon extraction
50 define( 'MW_COLON_STATE_TEXT', 0 );
51 define( 'MW_COLON_STATE_TAG', 1 );
52 define( 'MW_COLON_STATE_TAGSTART', 2 );
53 define( 'MW_COLON_STATE_CLOSETAG', 3 );
54 define( 'MW_COLON_STATE_TAGSLASH', 4 );
55 define( 'MW_COLON_STATE_COMMENT', 5 );
56 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
57 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
62 * Processes wiki markup
65 * There are four main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
73 * removes HTML comments and expands templates
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
86 * * only within ParserOptions
97 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId, // ID to display in {{REVISIONID}} tags
116 $mRevisionTimestamp, // The timestamp of the specified revision ID
117 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
127 $this->mTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mFirstCall
= true;
134 * Do various kinds of initialisation on the first call of the parser
136 function firstCallInit() {
137 if ( !$this->mFirstCall
) {
141 wfProfileIn( __METHOD__
);
142 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
144 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
146 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
171 if ( $wgAllowDisplayTitle ) {
172 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
174 if ( $wgAllowSlowParserFunctions ) {
175 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
178 $this->initialiseVariables();
179 $this->mFirstCall
= false;
180 wfProfileOut( __METHOD__
);
188 function clearState() {
189 wfProfileIn( __METHOD__
);
190 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= new StripState
;
199 $this->mArgStack
= array();
200 $this->mInPre
= false;
201 $this->mInterwikiLinkHolders
= array(
205 $this->mLinkHolders
= array(
206 'namespaces' => array(),
208 'queries' => array(),
212 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
215 * Prefix for temporary replacement strings for the multipass parser.
216 * \x07 should never appear in input as it's disallowed in XML.
217 * Using it at the front also gives us a little extra robustness
218 * since it shouldn't match when butted up against identifier-like
221 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTemplates
= array();
225 $this->mTemplatePath
= array();
227 $this->mShowToc
= true;
228 $this->mForceTocPosition
= false;
229 $this->mIncludeSizes
= array(
235 wfRunHooks( 'ParserClearState', array( &$this ) );
236 wfProfileOut( __METHOD__
);
239 function setOutputType( $ot ) {
240 $this->mOutputType
= $ot;
243 'html' => $ot == OT_HTML
,
244 'wiki' => $ot == OT_WIKI
,
245 'msg' => $ot == OT_MSG
,
246 'pre' => $ot == OT_PREPROCESS
,
251 * Accessor for mUniqPrefix.
255 function uniqPrefix() {
256 return $this->mUniqPrefix
;
260 * Convert wikitext to HTML
261 * Do not call this function recursively.
264 * @param string $text Text we want to parse
265 * @param Title &$title A title object
266 * @param array $options
267 * @param boolean $linestart
268 * @param boolean $clearState
269 * @param int $revid number to pass in {{REVISIONID}}
270 * @return ParserOutput a ParserOutput
272 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
274 * First pass--just handle <nowiki> sections, pass the rest off
275 * to internalParse() which does all the real work.
278 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
279 $fname = 'Parser::parse-' . wfGetCaller();
280 wfProfileIn( __METHOD__
);
281 wfProfileIn( $fname );
287 $this->mOptions
= $options;
288 $this->mTitle
=& $title;
289 $oldRevisionId = $this->mRevisionId
;
290 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
291 if( $revid !== null ) {
292 $this->mRevisionId
= $revid;
293 $this->mRevisionTimestamp
= null;
295 $this->setOutputType( OT_HTML
);
296 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
297 $text = $this->strip( $text, $this->mStripState
);
298 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
299 $text = $this->internalParse( $text );
300 $text = $this->mStripState
->unstripGeneral( $text );
302 # Clean up special characters, only run once, next-to-last before doBlockLevels
304 # french spaces, last one Guillemet-left
305 # only if there is something before the space
306 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
307 # french spaces, Guillemet-right
308 '/(\\302\\253) /' => '\\1 ',
310 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
313 $text = $this->doBlockLevels( $text, $linestart );
315 $this->replaceLinkHolders( $text );
317 # the position of the parserConvert() call should not be changed. it
318 # assumes that the links are all replaced and the only thing left
319 # is the <nowiki> mark.
320 # Side-effects: this calls $this->mOutput->setTitleText()
321 $text = $wgContLang->parserConvert( $text, $this );
323 $text = $this->mStripState
->unstripNoWiki( $text );
325 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
327 $text = Sanitizer
::normalizeCharReferences( $text );
329 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
330 $text = Parser
::tidy($text);
332 # attempt to sanitize at least some nesting problems
333 # (bug #2702 and quite a few others)
335 # ''Something [http://www.cool.com cool''] -->
336 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
337 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
338 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
339 # fix up an anchor inside another anchor, only
340 # at least for a single single nested link (bug 3695)
341 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
342 '\\1\\2</a>\\3</a>\\1\\4</a>',
343 # fix div inside inline elements- doBlockLevels won't wrap a line which
344 # contains a div, so fix it up here; replace
345 # div with escaped text
346 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
347 '\\1\\3<div\\5>\\6</div>\\8\\9',
348 # remove empty italic or bold tag pairs, some
349 # introduced by rules above
350 '/<([bi])><\/\\1>/' => '',
353 $text = preg_replace(
354 array_keys( $tidyregs ),
355 array_values( $tidyregs ),
359 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
361 # Information on include size limits, for the benefit of users who try to skirt them
362 if ( max( $this->mIncludeSizes
) > 1000 ) {
363 $max = $this->mOptions
->getMaxIncludeSize();
365 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
366 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
367 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
368 "Maximum: $max bytes\n" .
371 $this->mOutput
->setText( $text );
372 $this->mRevisionId
= $oldRevisionId;
373 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
374 wfProfileOut( $fname );
375 wfProfileOut( __METHOD__
);
377 return $this->mOutput
;
381 * Recursive parser entry point that can be called from an extension tag
384 function recursiveTagParse( $text ) {
385 wfProfileIn( __METHOD__
);
386 $x =& $this->mStripState
;
387 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
388 $text = $this->strip( $text, $x );
389 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
390 $text = $this->internalParse( $text );
391 wfProfileOut( __METHOD__
);
396 * Expand templates and variables in the text, producing valid, static wikitext.
397 * Also removes comments.
399 function preprocess( $text, $title, $options ) {
400 wfProfileIn( __METHOD__
);
402 $this->setOutputType( OT_PREPROCESS
);
403 $this->mOptions
= $options;
404 $this->mTitle
= $title;
405 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
406 $text = $this->strip( $text, $this->mStripState
);
407 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
408 if ( $this->mOptions
->getRemoveComments() ) {
409 $text = Sanitizer
::removeHTMLcomments( $text );
411 $text = $this->replaceVariables( $text );
412 $text = $this->mStripState
->unstripBoth( $text );
413 wfProfileOut( __METHOD__
);
418 * Get a random string
423 function getRandomString() {
424 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
427 function &getTitle() { return $this->mTitle
; }
428 function getOptions() { return $this->mOptions
; }
430 function getFunctionLang() {
431 global $wgLang, $wgContLang;
432 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
436 * Replaces all occurrences of HTML-style comments and the given tags
437 * in the text with a random marker and returns teh next text. The output
438 * parameter $matches will be an associative array filled with data in
440 * 'UNIQ-xxxxx' => array(
443 * array( 'param' => 'x' ),
444 * '<element param="x">tag content</element>' ) )
446 * @param $elements list of element names. Comments are always extracted.
447 * @param $text Source text string.
448 * @param $uniq_prefix
453 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
458 $taglist = implode( '|', $elements );
459 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
461 while ( '' != $text ) {
462 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
464 if( count( $p ) < 5 ) {
467 if( count( $p ) > 5 ) {
481 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
482 $stripped .= $marker;
484 if ( $close === '/>' ) {
485 // Empty element tag, <tag />
490 if( $element == '!--' ) {
493 $end = "/(<\\/$element\\s*>)/i";
495 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
497 if( count( $q ) < 3 ) {
498 # No end tag -- let it run out to the end of the text.
507 $matches[$marker] = array( $element,
509 Sanitizer
::decodeTagAttributes( $attributes ),
510 "<$element$attributes$close$content$tail" );
516 * Strips and renders nowiki, pre, math, hiero
517 * If $render is set, performs necessary rendering operations on plugins
518 * Returns the text, and fills an array with data needed in unstrip()
520 * @param StripState $state
522 * @param bool $stripcomments when set, HTML comments <!-- like this -->
523 * will be stripped in addition to other tags. This is important
524 * for section editing, where these comments cause confusion when
525 * counting the sections in the wikisource
527 * @param array dontstrip contains tags which should not be stripped;
528 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
532 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
533 wfProfileIn( __METHOD__
);
534 $render = ($this->mOutputType
== OT_HTML
);
536 $uniq_prefix = $this->mUniqPrefix
;
537 $commentState = new ReplacementArray
;
539 $elements = array_merge(
540 array( 'nowiki', 'gallery' ),
541 array_keys( $this->mTagHooks
) );
544 $elements[] = 'html';
546 if( $this->mOptions
->getUseTeX() ) {
547 $elements[] = 'math';
550 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
551 foreach ( $elements AS $k => $v ) {
552 if ( !in_array ( $v , $dontstrip ) ) continue;
553 unset ( $elements[$k] );
557 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
559 foreach( $matches as $marker => $data ) {
560 list( $element, $content, $params, $tag ) = $data;
562 $tagName = strtolower( $element );
563 wfProfileIn( __METHOD__
."-render-$tagName" );
567 if( substr( $tag, -3 ) == '-->' ) {
570 // Unclosed comment in input.
571 // Close it so later stripping can remove it
580 // Shouldn't happen otherwise. :)
582 $output = Xml
::escapeTagsOnly( $content );
585 $output = MathRenderer
::renderMath( $content );
588 $output = $this->renderImageGallery( $content, $params );
591 if( isset( $this->mTagHooks
[$tagName] ) ) {
592 $output = call_user_func_array( $this->mTagHooks
[$tagName],
593 array( $content, $params, $this ) );
595 throw new MWException( "Invalid call hook $element" );
598 wfProfileOut( __METHOD__
."-render-$tagName" );
600 // Just stripping tags; keep the source
604 // Unstrip the output, because unstrip() is no longer recursive so
605 // it won't do it itself
606 $output = $state->unstripBoth( $output );
608 if( !$stripcomments && $element == '!--' ) {
609 $commentState->setPair( $marker, $output );
610 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
611 $state->nowiki
->setPair( $marker, $output );
613 $state->general
->setPair( $marker, $output );
617 # Unstrip comments unless explicitly told otherwise.
618 # (The comments are always stripped prior to this point, so as to
619 # not invoke any extension tags / parser hooks contained within
621 if ( !$stripcomments ) {
622 // Put them all back and forget them
623 $text = $commentState->replace( $text );
626 wfProfileOut( __METHOD__
);
631 * Restores pre, math, and other extensions removed by strip()
633 * always call unstripNoWiki() after this one
635 * @deprecated use $this->mStripState->unstrip()
637 function unstrip( $text, $state ) {
638 return $state->unstripGeneral( $text );
642 * Always call this after unstrip() to preserve the order
645 * @deprecated use $this->mStripState->unstrip()
647 function unstripNoWiki( $text, $state ) {
648 return $state->unstripNoWiki( $text );
652 * @deprecated use $this->mStripState->unstripBoth()
654 function unstripForHTML( $text ) {
655 return $this->mStripState
->unstripBoth( $text );
659 * Add an item to the strip state
660 * Returns the unique tag which must be inserted into the stripped text
661 * The tag will be replaced with the original text in unstrip()
665 function insertStripItem( $text, &$state ) {
666 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
667 $state->general
->setPair( $rnd, $text );
672 * Interface with html tidy, used if $wgUseTidy = true.
673 * If tidy isn't able to correct the markup, the original will be
674 * returned in all its glory with a warning comment appended.
676 * Either the external tidy program or the in-process tidy extension
677 * will be used depending on availability. Override the default
678 * $wgTidyInternal setting to disable the internal if it's not working.
680 * @param string $text Hideous HTML input
681 * @return string Corrected HTML output
685 function tidy( $text ) {
686 global $wgTidyInternal;
687 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
688 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
689 '<head><title>test</title></head><body>'.$text.'</body></html>';
690 if( $wgTidyInternal ) {
691 $correctedtext = Parser
::internalTidy( $wrappedtext );
693 $correctedtext = Parser
::externalTidy( $wrappedtext );
695 if( is_null( $correctedtext ) ) {
696 wfDebug( "Tidy error detected!\n" );
697 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
699 return $correctedtext;
703 * Spawn an external HTML tidy process and get corrected markup back from it.
708 function externalTidy( $text ) {
709 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
710 $fname = 'Parser::externalTidy';
711 wfProfileIn( $fname );
716 $descriptorspec = array(
717 0 => array('pipe', 'r'),
718 1 => array('pipe', 'w'),
719 2 => array('file', '/dev/null', 'a')
722 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
723 if (is_resource($process)) {
724 // Theoretically, this style of communication could cause a deadlock
725 // here. If the stdout buffer fills up, then writes to stdin could
726 // block. This doesn't appear to happen with tidy, because tidy only
727 // writes to stdout after it's finished reading from stdin. Search
728 // for tidyParseStdin and tidySaveStdout in console/tidy.c
729 fwrite($pipes[0], $text);
731 while (!feof($pipes[1])) {
732 $cleansource .= fgets($pipes[1], 1024);
735 proc_close($process);
738 wfProfileOut( $fname );
740 if( $cleansource == '' && $text != '') {
741 // Some kind of error happened, so we couldn't get the corrected text.
742 // Just give up; we'll use the source text and append a warning.
750 * Use the HTML tidy PECL extension to use the tidy library in-process,
751 * saving the overhead of spawning a new process. Currently written to
752 * the PHP 4.3.x version of the extension, may not work on PHP 5.
754 * 'pear install tidy' should be able to compile the extension module.
759 function internalTidy( $text ) {
761 $fname = 'Parser::internalTidy';
762 wfProfileIn( $fname );
764 tidy_load_config( $wgTidyConf );
765 tidy_set_encoding( 'utf8' );
766 tidy_parse_string( $text );
768 if( tidy_get_status() == 2 ) {
769 // 2 is magic number for fatal error
770 // http://www.php.net/manual/en/function.tidy-get-status.php
773 $cleansource = tidy_get_output();
775 wfProfileOut( $fname );
780 * parse the wiki syntax used to render tables
784 function doTableStuff ( $t ) {
785 $fname = 'Parser::doTableStuff';
786 wfProfileIn( $fname );
788 $t = explode ( "\n" , $t ) ;
789 $td = array () ; # Is currently a td tag open?
790 $ltd = array () ; # Was it TD or TH?
791 $tr = array () ; # Is currently a tr tag open?
792 $ltr = array () ; # tr attributes
793 $has_opened_tr = array(); # Did this table open a <tr> element?
794 $indent_level = 0; # indent level of the table
795 foreach ( $t AS $k => $x )
798 $fc = substr ( $x , 0 , 1 ) ;
800 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
801 $indent_level = strlen( $matches[1] );
803 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
805 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
806 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
807 array_push ( $td , false ) ;
808 array_push ( $ltd , '' ) ;
809 array_push ( $tr , false ) ;
810 array_push ( $ltr , '' ) ;
811 array_push ( $has_opened_tr, false );
813 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
814 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
815 $z = "</table>" . substr ( $x , 2);
816 $l = array_pop ( $ltd ) ;
817 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
818 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
819 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
821 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
823 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
824 $x = substr ( $x , 1 ) ;
825 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
827 $l = array_pop ( $ltd ) ;
828 array_pop ( $has_opened_tr );
829 array_push ( $has_opened_tr , true ) ;
830 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
831 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
834 array_push ( $tr , false ) ;
835 array_push ( $td , false ) ;
836 array_push ( $ltd , '' ) ;
837 $attributes = $this->mStripState
->unstripBoth( $x );
838 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
840 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
842 if ( '|+' == substr ( $x , 0 , 2 ) ) {
844 $x = substr ( $x , 1 ) ;
846 $after = substr ( $x , 1 ) ;
847 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
849 // Split up multiple cells on the same line.
850 // FIXME: This can result in improper nesting of tags processed
851 // by earlier parser steps, but should avoid splitting up eg
852 // attribute values containing literal "||".
853 $after = StringUtils
::explodeMarkup( '||', $after );
857 # Loop through each table cell
858 foreach ( $after AS $theline )
863 $tra = array_pop ( $ltr ) ;
864 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
865 array_push ( $tr , true ) ;
866 array_push ( $ltr , '' ) ;
867 array_pop ( $has_opened_tr );
868 array_push ( $has_opened_tr , true ) ;
871 $l = array_pop ( $ltd ) ;
872 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
875 } else if ( $fc == '!' ) {
877 } else if ( $fc == '+' ) {
882 array_push ( $ltd , $l ) ;
885 $y = explode ( '|' , $theline , 2 ) ;
886 # Note that a '|' inside an invalid link should not
887 # be mistaken as delimiting cell parameters
888 if ( strpos( $y[0], '[[' ) !== false ) {
889 $y = array ($theline);
891 if ( count ( $y ) == 1 )
892 $y = "{$z}<{$l}>{$y[0]}" ;
894 $attributes = $this->mStripState
->unstripBoth( $y[0] );
895 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
898 array_push ( $td , true ) ;
903 # Closing open td, tr && table
904 while ( count ( $td ) > 0 )
906 $l = array_pop ( $ltd ) ;
907 if ( array_pop ( $td ) ) $t[] = '</td>' ;
908 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
909 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
913 $t = implode ( "\n" , $t ) ;
914 # special case: don't return empty table
915 if($t == "<table>\n<tr><td></td></tr>\n</table>")
917 wfProfileOut( $fname );
922 * Helper function for parse() that transforms wiki markup into
923 * HTML. Only called for $mOutputType == OT_HTML.
927 function internalParse( $text ) {
930 $fname = 'Parser::internalParse';
931 wfProfileIn( $fname );
933 # Hook to suspend the parser in this state
934 $x =& $this->mStripState
; // FIXME: Please check that this initialization is correct.
935 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
936 wfProfileOut( $fname );
940 # Remove <noinclude> tags and <includeonly> sections
941 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
942 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
943 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
945 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
947 $text = $this->replaceVariables( $text, $args );
949 // Tables need to come after variable replacement for things to work
950 // properly; putting them before other transformations should keep
951 // exciting things like link expansions from showing up in surprising
953 $text = $this->doTableStuff( $text );
955 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
957 $text = $this->stripToc( $text );
958 $this->stripNoGallery( $text );
959 $text = $this->doHeadings( $text );
960 if($this->mOptions
->getUseDynamicDates()) {
961 $df =& DateFormatter
::getInstance();
962 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
964 $text = $this->doAllQuotes( $text );
965 $text = $this->replaceInternalLinks( $text );
966 $text = $this->replaceExternalLinks( $text );
968 # replaceInternalLinks may sometimes leave behind
969 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
970 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
972 $text = $this->doMagicLinks( $text );
973 $text = $this->formatHeadings( $text, $isMain );
975 wfProfileOut( $fname );
980 * Replace special strings like "ISBN xxx" and "RFC xxx" with
981 * magic external links.
985 function &doMagicLinks( &$text ) {
986 wfProfileIn( __METHOD__
);
987 $text = preg_replace_callback(
989 <a.*?</a> | # Skip link text
990 <.*?> | # Skip stuff inside HTML elements
991 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
992 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
993 )!x', array( &$this, 'magicLinkCallback' ), $text );
994 wfProfileOut( __METHOD__
);
998 function magicLinkCallback( $m ) {
999 if ( substr( $m[0], 0, 1 ) == '<' ) {
1002 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1004 $num = strtr( $isbn, array(
1009 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1010 $text = '<a href="' .
1011 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1012 "\" class=\"internal\">ISBN $isbn</a>";
1014 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1018 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1020 $urlmsg = 'pubmedurl';
1023 throw new MWException( __METHOD__
.': unrecognised match type "' .
1024 substr($m[0], 0, 20 ) . '"' );
1027 $url = wfMsg( $urlmsg, $id);
1028 $sk =& $this->mOptions
->getSkin();
1029 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1030 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1036 * Parse headers and return html
1040 function doHeadings( $text ) {
1041 $fname = 'Parser::doHeadings';
1042 wfProfileIn( $fname );
1043 for ( $i = 6; $i >= 1; --$i ) {
1044 $h = str_repeat( '=', $i );
1045 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1046 "<h{$i}>\\1</h{$i}>\\2", $text );
1048 wfProfileOut( $fname );
1053 * Replace single quotes with HTML markup
1055 * @return string the altered text
1057 function doAllQuotes( $text ) {
1058 $fname = 'Parser::doAllQuotes';
1059 wfProfileIn( $fname );
1061 $lines = explode( "\n", $text );
1062 foreach ( $lines as $line ) {
1063 $outtext .= $this->doQuotes ( $line ) . "\n";
1065 $outtext = substr($outtext, 0,-1);
1066 wfProfileOut( $fname );
1071 * Helper function for doAllQuotes()
1074 function doQuotes( $text ) {
1075 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1076 if ( count( $arr ) == 1 )
1080 # First, do some preliminary work. This may shift some apostrophes from
1081 # being mark-up to being text. It also counts the number of occurrences
1082 # of bold and italics mark-ups.
1086 foreach ( $arr as $r )
1088 if ( ( $i %
2 ) == 1 )
1090 # If there are ever four apostrophes, assume the first is supposed to
1091 # be text, and the remaining three constitute mark-up for bold text.
1092 if ( strlen( $arr[$i] ) == 4 )
1097 # If there are more than 5 apostrophes in a row, assume they're all
1098 # text except for the last 5.
1099 else if ( strlen( $arr[$i] ) > 5 )
1101 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1104 # Count the number of occurrences of bold and italics mark-ups.
1105 # We are not counting sequences of five apostrophes.
1106 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1107 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1108 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1113 # If there is an odd number of both bold and italics, it is likely
1114 # that one of the bold ones was meant to be an apostrophe followed
1115 # by italics. Which one we cannot know for certain, but it is more
1116 # likely to be one that has a single-letter word before it.
1117 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1120 $firstsingleletterword = -1;
1121 $firstmultiletterword = -1;
1123 foreach ( $arr as $r )
1125 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1127 $x1 = substr ($arr[$i-1], -1);
1128 $x2 = substr ($arr[$i-1], -2, 1);
1130 if ($firstspace == -1) $firstspace = $i;
1131 } else if ($x2 == ' ') {
1132 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1134 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1140 # If there is a single-letter word, use it!
1141 if ($firstsingleletterword > -1)
1143 $arr [ $firstsingleletterword ] = "''";
1144 $arr [ $firstsingleletterword-1 ] .= "'";
1146 # If not, but there's a multi-letter word, use that one.
1147 else if ($firstmultiletterword > -1)
1149 $arr [ $firstmultiletterword ] = "''";
1150 $arr [ $firstmultiletterword-1 ] .= "'";
1152 # ... otherwise use the first one that has neither.
1153 # (notice that it is possible for all three to be -1 if, for example,
1154 # there is only one pentuple-apostrophe in the line)
1155 else if ($firstspace > -1)
1157 $arr [ $firstspace ] = "''";
1158 $arr [ $firstspace-1 ] .= "'";
1162 # Now let's actually convert our apostrophic mush to HTML!
1167 foreach ($arr as $r)
1171 if ($state == 'both')
1178 if (strlen ($r) == 2)
1181 { $output .= '</i>'; $state = ''; }
1182 else if ($state == 'bi')
1183 { $output .= '</i>'; $state = 'b'; }
1184 else if ($state == 'ib')
1185 { $output .= '</b></i><b>'; $state = 'b'; }
1186 else if ($state == 'both')
1187 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1188 else # $state can be 'b' or ''
1189 { $output .= '<i>'; $state .= 'i'; }
1191 else if (strlen ($r) == 3)
1194 { $output .= '</b>'; $state = ''; }
1195 else if ($state == 'bi')
1196 { $output .= '</i></b><i>'; $state = 'i'; }
1197 else if ($state == 'ib')
1198 { $output .= '</b>'; $state = 'i'; }
1199 else if ($state == 'both')
1200 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1201 else # $state can be 'i' or ''
1202 { $output .= '<b>'; $state .= 'b'; }
1204 else if (strlen ($r) == 5)
1207 { $output .= '</b><i>'; $state = 'i'; }
1208 else if ($state == 'i')
1209 { $output .= '</i><b>'; $state = 'b'; }
1210 else if ($state == 'bi')
1211 { $output .= '</i></b>'; $state = ''; }
1212 else if ($state == 'ib')
1213 { $output .= '</b></i>'; $state = ''; }
1214 else if ($state == 'both')
1215 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1216 else # ($state == '')
1217 { $buffer = ''; $state = 'both'; }
1222 # Now close all remaining tags. Notice that the order is important.
1223 if ($state == 'b' ||
$state == 'ib')
1225 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1229 if ($state == 'both')
1230 $output .= '<b><i>'.$buffer.'</i></b>';
1236 * Replace external links
1238 * Note: this is all very hackish and the order of execution matters a lot.
1239 * Make sure to run maintenance/parserTests.php if you change this code.
1243 function replaceExternalLinks( $text ) {
1245 $fname = 'Parser::replaceExternalLinks';
1246 wfProfileIn( $fname );
1248 $sk =& $this->mOptions
->getSkin();
1250 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1252 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1255 while ( $i<count( $bits ) ) {
1257 $protocol = $bits[$i++
];
1258 $text = $bits[$i++
];
1259 $trail = $bits[$i++
];
1261 # The characters '<' and '>' (which were escaped by
1262 # removeHTMLtags()) should not be included in
1263 # URLs, per RFC 2396.
1265 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1266 $text = substr($url, $m2[0][1]) . ' ' . $text;
1267 $url = substr($url, 0, $m2[0][1]);
1270 # If the link text is an image URL, replace it with an <img> tag
1271 # This happened by accident in the original parser, but some people used it extensively
1272 $img = $this->maybeMakeExternalImage( $text );
1273 if ( $img !== false ) {
1279 # Set linktype for CSS - if URL==text, link is essentially free
1280 $linktype = ($text == $url) ?
'free' : 'text';
1282 # No link text, e.g. [http://domain.tld/some.link]
1283 if ( $text == '' ) {
1284 # Autonumber if allowed. See bug #5918
1285 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1286 $text = '[' . ++
$this->mAutonumber
. ']';
1287 $linktype = 'autonumber';
1289 # Otherwise just use the URL
1290 $text = htmlspecialchars( $url );
1294 # Have link text, e.g. [http://domain.tld/some.link text]s
1296 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1299 $text = $wgContLang->markNoConversion($text);
1301 $url = Sanitizer
::cleanUrl( $url );
1303 # Process the trail (i.e. everything after this link up until start of the next link),
1304 # replacing any non-bracketed links
1305 $trail = $this->replaceFreeExternalLinks( $trail );
1307 # Use the encoded URL
1308 # This means that users can paste URLs directly into the text
1309 # Funny characters like ö aren't valid in URLs anyway
1310 # This was changed in August 2004
1311 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1313 # Register link in the output object.
1314 # Replace unnecessary URL escape codes with the referenced character
1315 # This prevents spammers from hiding links from the filters
1316 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1317 $this->mOutput
->addExternalLink( $pasteurized );
1320 wfProfileOut( $fname );
1325 * Replace anything that looks like a URL with a link
1328 function replaceFreeExternalLinks( $text ) {
1330 $fname = 'Parser::replaceFreeExternalLinks';
1331 wfProfileIn( $fname );
1333 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1334 $s = array_shift( $bits );
1337 $sk =& $this->mOptions
->getSkin();
1339 while ( $i < count( $bits ) ){
1340 $protocol = $bits[$i++
];
1341 $remainder = $bits[$i++
];
1344 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1345 # Found some characters after the protocol that look promising
1346 $url = $protocol . $m[1];
1349 # special case: handle urls as url args:
1350 # http://www.example.com/foo?=http://www.example.com/bar
1351 if(strlen($trail) == 0 &&
1353 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1354 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1357 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1362 # The characters '<' and '>' (which were escaped by
1363 # removeHTMLtags()) should not be included in
1364 # URLs, per RFC 2396.
1366 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1367 $trail = substr($url, $m2[0][1]) . $trail;
1368 $url = substr($url, 0, $m2[0][1]);
1371 # Move trailing punctuation to $trail
1373 # If there is no left bracket, then consider right brackets fair game too
1374 if ( strpos( $url, '(' ) === false ) {
1378 $numSepChars = strspn( strrev( $url ), $sep );
1379 if ( $numSepChars ) {
1380 $trail = substr( $url, -$numSepChars ) . $trail;
1381 $url = substr( $url, 0, -$numSepChars );
1384 $url = Sanitizer
::cleanUrl( $url );
1386 # Is this an external image?
1387 $text = $this->maybeMakeExternalImage( $url );
1388 if ( $text === false ) {
1389 # Not an image, make a link
1390 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1391 # Register it in the output object...
1392 # Replace unnecessary URL escape codes with their equivalent characters
1393 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1394 $this->mOutput
->addExternalLink( $pasteurized );
1396 $s .= $text . $trail;
1398 $s .= $protocol . $remainder;
1401 wfProfileOut( $fname );
1406 * Replace unusual URL escape codes with their equivalent characters
1410 * @fixme This can merge genuinely required bits in the path or query string,
1411 * breaking legit URLs. A proper fix would treat the various parts of
1412 * the URL differently; as a workaround, just use the output for
1413 * statistical records, not for actual linking/output.
1415 static function replaceUnusualEscapes( $url ) {
1416 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1417 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1421 * Callback function used in replaceUnusualEscapes().
1422 * Replaces unusual URL escape codes with their equivalent character
1426 private static function replaceUnusualEscapesCallback( $matches ) {
1427 $char = urldecode( $matches[0] );
1428 $ord = ord( $char );
1429 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1430 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1431 // No, shouldn't be escaped
1434 // Yes, leave it escaped
1440 * make an image if it's allowed, either through the global
1441 * option or through the exception
1444 function maybeMakeExternalImage( $url ) {
1445 $sk =& $this->mOptions
->getSkin();
1446 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1447 $imagesexception = !empty($imagesfrom);
1449 if ( $this->mOptions
->getAllowExternalImages()
1450 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1451 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1453 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1460 * Process [[ ]] wikilinks
1464 function replaceInternalLinks( $s ) {
1466 static $fname = 'Parser::replaceInternalLinks' ;
1468 wfProfileIn( $fname );
1470 wfProfileIn( $fname.'-setup' );
1472 # the % is needed to support urlencoded titles as well
1473 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1475 $sk =& $this->mOptions
->getSkin();
1477 #split the entire text string on occurences of [[
1478 $a = explode( '[[', ' ' . $s );
1479 #get the first element (all text up to first [[), and remove the space we added
1480 $s = array_shift( $a );
1481 $s = substr( $s, 1 );
1483 # Match a link having the form [[namespace:link|alternate]]trail
1485 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1486 # Match cases where there is no "]]", which might still be images
1487 static $e1_img = FALSE;
1488 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1489 # Match the end of a line for a word that's not followed by whitespace,
1490 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1491 $e2 = wfMsgForContent( 'linkprefix' );
1493 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1495 if( is_null( $this->mTitle
) ) {
1496 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1498 $nottalk = !$this->mTitle
->isTalkPage();
1500 if ( $useLinkPrefixExtension ) {
1502 if ( preg_match( $e2, $s, $m ) ) {
1503 $first_prefix = $m[2];
1505 $first_prefix = false;
1511 $selflink = $this->mTitle
->getPrefixedText();
1512 $useSubpages = $this->areSubpagesAllowed();
1513 wfProfileOut( $fname.'-setup' );
1515 # Loop for each link
1516 for ($k = 0; isset( $a[$k] ); $k++
) {
1518 if ( $useLinkPrefixExtension ) {
1519 wfProfileIn( $fname.'-prefixhandling' );
1520 if ( preg_match( $e2, $s, $m ) ) {
1528 $prefix = $first_prefix;
1529 $first_prefix = false;
1531 wfProfileOut( $fname.'-prefixhandling' );
1534 $might_be_img = false;
1536 wfProfileIn( "$fname-e1" );
1537 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1539 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1540 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1541 # the real problem is with the $e1 regex
1544 # Still some problems for cases where the ] is meant to be outside punctuation,
1545 # and no image is in sight. See bug 2095.
1548 substr( $m[3], 0, 1 ) === ']' &&
1549 strpos($text, '[') !== false
1552 $text .= ']'; # so that replaceExternalLinks($text) works later
1553 $m[3] = substr( $m[3], 1 );
1555 # fix up urlencoded title texts
1556 if( strpos( $m[1], '%' ) !== false ) {
1557 # Should anchors '#' also be rejected?
1558 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1561 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1562 $might_be_img = true;
1564 if ( strpos( $m[1], '%' ) !== false ) {
1565 $m[1] = urldecode($m[1]);
1568 } else { # Invalid form; output directly
1569 $s .= $prefix . '[[' . $line ;
1570 wfProfileOut( "$fname-e1" );
1573 wfProfileOut( "$fname-e1" );
1574 wfProfileIn( "$fname-misc" );
1576 # Don't allow internal links to pages containing
1577 # PROTO: where PROTO is a valid URL protocol; these
1578 # should be external links.
1579 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1580 $s .= $prefix . '[[' . $line ;
1584 # Make subpage if necessary
1585 if( $useSubpages ) {
1586 $link = $this->maybeDoSubpageLink( $m[1], $text );
1591 $noforce = (substr($m[1], 0, 1) != ':');
1593 # Strip off leading ':'
1594 $link = substr($link, 1);
1597 wfProfileOut( "$fname-misc" );
1598 wfProfileIn( "$fname-title" );
1599 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1601 $s .= $prefix . '[[' . $line;
1602 wfProfileOut( "$fname-title" );
1606 $ns = $nt->getNamespace();
1607 $iw = $nt->getInterWiki();
1608 wfProfileOut( "$fname-title" );
1610 if ($might_be_img) { # if this is actually an invalid link
1611 wfProfileIn( "$fname-might_be_img" );
1612 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1614 while (isset ($a[$k+
1]) ) {
1615 #look at the next 'line' to see if we can close it there
1616 $spliced = array_splice( $a, $k +
1, 1 );
1617 $next_line = array_shift( $spliced );
1618 $m = explode( ']]', $next_line, 3 );
1619 if ( count( $m ) == 3 ) {
1620 # the first ]] closes the inner link, the second the image
1622 $text .= "[[{$m[0]}]]{$m[1]}";
1625 } elseif ( count( $m ) == 2 ) {
1626 #if there's exactly one ]] that's fine, we'll keep looking
1627 $text .= "[[{$m[0]}]]{$m[1]}";
1629 #if $next_line is invalid too, we need look no further
1630 $text .= '[[' . $next_line;
1635 # we couldn't find the end of this imageLink, so output it raw
1636 #but don't ignore what might be perfectly normal links in the text we've examined
1637 $text = $this->replaceInternalLinks($text);
1638 $s .= "{$prefix}[[$link|$text";
1639 # note: no $trail, because without an end, there *is* no trail
1640 wfProfileOut( "$fname-might_be_img" );
1643 } else { #it's not an image, so output it raw
1644 $s .= "{$prefix}[[$link|$text";
1645 # note: no $trail, because without an end, there *is* no trail
1646 wfProfileOut( "$fname-might_be_img" );
1649 wfProfileOut( "$fname-might_be_img" );
1652 $wasblank = ( '' == $text );
1653 if( $wasblank ) $text = $link;
1655 # Link not escaped by : , create the various objects
1659 wfProfileIn( "$fname-interwiki" );
1660 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1661 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1662 $s = rtrim($s . "\n");
1663 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1664 wfProfileOut( "$fname-interwiki" );
1667 wfProfileOut( "$fname-interwiki" );
1669 if ( $ns == NS_IMAGE
) {
1670 wfProfileIn( "$fname-image" );
1671 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1672 # recursively parse links inside the image caption
1673 # actually, this will parse them in any other parameters, too,
1674 # but it might be hard to fix that, and it doesn't matter ATM
1675 $text = $this->replaceExternalLinks($text);
1676 $text = $this->replaceInternalLinks($text);
1678 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1679 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1680 $this->mOutput
->addImage( $nt->getDBkey() );
1682 wfProfileOut( "$fname-image" );
1685 # We still need to record the image's presence on the page
1686 $this->mOutput
->addImage( $nt->getDBkey() );
1688 wfProfileOut( "$fname-image" );
1692 if ( $ns == NS_CATEGORY
) {
1693 wfProfileIn( "$fname-category" );
1694 $s = rtrim($s . "\n"); # bug 87
1697 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1698 $sortkey = $this->mTitle
->getText();
1700 $sortkey = $this->mTitle
->getPrefixedText();
1705 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1706 $sortkey = str_replace( "\n", '', $sortkey );
1707 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1708 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1711 * Strip the whitespace Category links produce, see bug 87
1712 * @todo We might want to use trim($tmp, "\n") here.
1714 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1716 wfProfileOut( "$fname-category" );
1721 if( ( $nt->getPrefixedText() === $selflink ) &&
1722 ( $nt->getFragment() === '' ) ) {
1723 # Self-links are handled specially; generally de-link and change to bold.
1724 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1728 # Special and Media are pseudo-namespaces; no pages actually exist in them
1729 if( $ns == NS_MEDIA
) {
1730 $link = $sk->makeMediaLinkObj( $nt, $text );
1731 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1732 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1733 $this->mOutput
->addImage( $nt->getDBkey() );
1735 } elseif( $ns == NS_SPECIAL
) {
1736 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1738 } elseif( $ns == NS_IMAGE
) {
1739 $img = new Image( $nt );
1740 if( $img->exists() ) {
1741 // Force a blue link if the file exists; may be a remote
1742 // upload on the shared repository, and we want to see its
1743 // auto-generated page.
1744 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1745 $this->mOutput
->addLink( $nt );
1749 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1751 wfProfileOut( $fname );
1756 * Make a link placeholder. The text returned can be later resolved to a real link with
1757 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1758 * parsing of interwiki links, and secondly to allow all existence checks and
1759 * article length checks (for stub links) to be bundled into a single query.
1762 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1763 wfProfileIn( __METHOD__
);
1764 if ( ! is_object($nt) ) {
1766 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1768 # Separate the link trail from the rest of the link
1769 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1771 if ( $nt->isExternal() ) {
1772 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1773 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1774 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1776 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1777 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1778 $this->mLinkHolders
['queries'][] = $query;
1779 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1780 $this->mLinkHolders
['titles'][] = $nt;
1782 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1785 wfProfileOut( __METHOD__
);
1790 * Render a forced-blue link inline; protect against double expansion of
1791 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1792 * Since this little disaster has to split off the trail text to avoid
1793 * breaking URLs in the following text without breaking trails on the
1794 * wiki links, it's been made into a horrible function.
1797 * @param string $text
1798 * @param string $query
1799 * @param string $trail
1800 * @param string $prefix
1801 * @return string HTML-wikitext mix oh yuck
1803 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1804 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1805 $sk =& $this->mOptions
->getSkin();
1806 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1807 return $this->armorLinks( $link ) . $trail;
1811 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1812 * going to go through further parsing steps before inline URL expansion.
1814 * In particular this is important when using action=render, which causes
1815 * full URLs to be included.
1817 * Oh man I hate our multi-layer parser!
1819 * @param string more-or-less HTML
1820 * @return string less-or-more HTML with NOPARSE bits
1822 function armorLinks( $text ) {
1823 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1824 "{$this->mUniqPrefix}NOPARSE$1", $text );
1828 * Return true if subpage links should be expanded on this page.
1831 function areSubpagesAllowed() {
1832 # Some namespaces don't allow subpages
1833 global $wgNamespacesWithSubpages;
1834 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1838 * Handle link to subpage if necessary
1839 * @param string $target the source of the link
1840 * @param string &$text the link text, modified as necessary
1841 * @return string the full name of the link
1844 function maybeDoSubpageLink($target, &$text) {
1847 # :Foobar -- override special treatment of prefix (images, language links)
1848 # /Foobar -- convert to CurrentPage/Foobar
1849 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1850 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1851 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1853 $fname = 'Parser::maybeDoSubpageLink';
1854 wfProfileIn( $fname );
1855 $ret = $target; # default return value is no change
1858 $target = trim( $target );
1860 # Some namespaces don't allow subpages,
1861 # so only perform processing if subpages are allowed
1862 if( $this->areSubpagesAllowed() ) {
1863 # Look at the first character
1864 if( $target != '' && $target{0} == '/' ) {
1865 # / at end means we don't want the slash to be shown
1866 if( substr( $target, -1, 1 ) == '/' ) {
1867 $target = substr( $target, 1, -1 );
1870 $noslash = substr( $target, 1 );
1873 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1874 if( '' === $text ) {
1876 } # this might be changed for ugliness reasons
1878 # check for .. subpage backlinks
1880 $nodotdot = $target;
1881 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1883 $nodotdot = substr( $nodotdot, 3 );
1885 if($dotdotcount > 0) {
1886 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1887 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1888 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1889 # / at the end means don't show full path
1890 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1891 $nodotdot = substr( $nodotdot, 0, -1 );
1892 if( '' === $text ) {
1896 $nodotdot = trim( $nodotdot );
1897 if( $nodotdot != '' ) {
1898 $ret .= '/' . $nodotdot;
1905 wfProfileOut( $fname );
1910 * Used by doBlockLevels()
1913 /* private */ function closeParagraph() {
1915 if ( '' != $this->mLastSection
) {
1916 $result = '</' . $this->mLastSection
. ">\n";
1918 $this->mInPre
= false;
1919 $this->mLastSection
= '';
1922 # getCommon() returns the length of the longest common substring
1923 # of both arguments, starting at the beginning of both.
1925 /* private */ function getCommon( $st1, $st2 ) {
1926 $fl = strlen( $st1 );
1927 $shorter = strlen( $st2 );
1928 if ( $fl < $shorter ) { $shorter = $fl; }
1930 for ( $i = 0; $i < $shorter; ++
$i ) {
1931 if ( $st1{$i} != $st2{$i} ) { break; }
1935 # These next three functions open, continue, and close the list
1936 # element appropriate to the prefix character passed into them.
1938 /* private */ function openList( $char ) {
1939 $result = $this->closeParagraph();
1941 if ( '*' == $char ) { $result .= '<ul><li>'; }
1942 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1943 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1944 else if ( ';' == $char ) {
1945 $result .= '<dl><dt>';
1946 $this->mDTopen
= true;
1948 else { $result = '<!-- ERR 1 -->'; }
1953 /* private */ function nextItem( $char ) {
1954 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1955 else if ( ':' == $char ||
';' == $char ) {
1957 if ( $this->mDTopen
) { $close = '</dt>'; }
1958 if ( ';' == $char ) {
1959 $this->mDTopen
= true;
1960 return $close . '<dt>';
1962 $this->mDTopen
= false;
1963 return $close . '<dd>';
1966 return '<!-- ERR 2 -->';
1969 /* private */ function closeList( $char ) {
1970 if ( '*' == $char ) { $text = '</li></ul>'; }
1971 else if ( '#' == $char ) { $text = '</li></ol>'; }
1972 else if ( ':' == $char ) {
1973 if ( $this->mDTopen
) {
1974 $this->mDTopen
= false;
1975 $text = '</dt></dl>';
1977 $text = '</dd></dl>';
1980 else { return '<!-- ERR 3 -->'; }
1986 * Make lists from lines starting with ':', '*', '#', etc.
1989 * @return string the lists rendered as HTML
1991 function doBlockLevels( $text, $linestart ) {
1992 $fname = 'Parser::doBlockLevels';
1993 wfProfileIn( $fname );
1995 # Parsing through the text line by line. The main thing
1996 # happening here is handling of block-level elements p, pre,
1997 # and making lists from lines starting with * # : etc.
1999 $textLines = explode( "\n", $text );
2001 $lastPrefix = $output = '';
2002 $this->mDTopen
= $inBlockElem = false;
2004 $paragraphStack = false;
2006 if ( !$linestart ) {
2007 $output .= array_shift( $textLines );
2009 foreach ( $textLines as $oLine ) {
2010 $lastPrefixLength = strlen( $lastPrefix );
2011 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2012 $preOpenMatch = preg_match('/<pre/i', $oLine );
2013 if ( !$this->mInPre
) {
2014 # Multiple prefixes may abut each other for nested lists.
2015 $prefixLength = strspn( $oLine, '*#:;' );
2016 $pref = substr( $oLine, 0, $prefixLength );
2019 $pref2 = str_replace( ';', ':', $pref );
2020 $t = substr( $oLine, $prefixLength );
2021 $this->mInPre
= !empty($preOpenMatch);
2023 # Don't interpret any other prefixes in preformatted text
2025 $pref = $pref2 = '';
2030 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2031 # Same as the last item, so no need to deal with nesting or opening stuff
2032 $output .= $this->nextItem( substr( $pref, -1 ) );
2033 $paragraphStack = false;
2035 if ( substr( $pref, -1 ) == ';') {
2036 # The one nasty exception: definition lists work like this:
2037 # ; title : definition text
2038 # So we check for : in the remainder text to split up the
2039 # title and definition, without b0rking links.
2041 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2043 $output .= $term . $this->nextItem( ':' );
2046 } elseif( $prefixLength ||
$lastPrefixLength ) {
2047 # Either open or close a level...
2048 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2049 $paragraphStack = false;
2051 while( $commonPrefixLength < $lastPrefixLength ) {
2052 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2053 --$lastPrefixLength;
2055 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2056 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2058 while ( $prefixLength > $commonPrefixLength ) {
2059 $char = substr( $pref, $commonPrefixLength, 1 );
2060 $output .= $this->openList( $char );
2062 if ( ';' == $char ) {
2063 # FIXME: This is dupe of code above
2064 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2066 $output .= $term . $this->nextItem( ':' );
2069 ++
$commonPrefixLength;
2071 $lastPrefix = $pref2;
2073 if( 0 == $prefixLength ) {
2074 wfProfileIn( "$fname-paragraph" );
2075 # No prefix (not in list)--go to paragraph mode
2076 // XXX: use a stack for nestable elements like span, table and div
2077 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2078 $closematch = preg_match(
2079 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2080 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2081 if ( $openmatch or $closematch ) {
2082 $paragraphStack = false;
2083 #Â TODO bug 5718: paragraph closed
2084 $output .= $this->closeParagraph();
2085 if ( $preOpenMatch and !$preCloseMatch ) {
2086 $this->mInPre
= true;
2088 if ( $closematch ) {
2089 $inBlockElem = false;
2091 $inBlockElem = true;
2093 } else if ( !$inBlockElem && !$this->mInPre
) {
2094 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2096 if ($this->mLastSection
!= 'pre') {
2097 $paragraphStack = false;
2098 $output .= $this->closeParagraph().'<pre>';
2099 $this->mLastSection
= 'pre';
2101 $t = substr( $t, 1 );
2104 if ( '' == trim($t) ) {
2105 if ( $paragraphStack ) {
2106 $output .= $paragraphStack.'<br />';
2107 $paragraphStack = false;
2108 $this->mLastSection
= 'p';
2110 if ($this->mLastSection
!= 'p' ) {
2111 $output .= $this->closeParagraph();
2112 $this->mLastSection
= '';
2113 $paragraphStack = '<p>';
2115 $paragraphStack = '</p><p>';
2119 if ( $paragraphStack ) {
2120 $output .= $paragraphStack;
2121 $paragraphStack = false;
2122 $this->mLastSection
= 'p';
2123 } else if ($this->mLastSection
!= 'p') {
2124 $output .= $this->closeParagraph().'<p>';
2125 $this->mLastSection
= 'p';
2130 wfProfileOut( "$fname-paragraph" );
2132 // somewhere above we forget to get out of pre block (bug 785)
2133 if($preCloseMatch && $this->mInPre
) {
2134 $this->mInPre
= false;
2136 if ($paragraphStack === false) {
2140 while ( $prefixLength ) {
2141 $output .= $this->closeList( $pref2{$prefixLength-1} );
2144 if ( '' != $this->mLastSection
) {
2145 $output .= '</' . $this->mLastSection
. '>';
2146 $this->mLastSection
= '';
2149 wfProfileOut( $fname );
2154 * Split up a string on ':', ignoring any occurences inside tags
2155 * to prevent illegal overlapping.
2156 * @param string $str the string to split
2157 * @param string &$before set to everything before the ':'
2158 * @param string &$after set to everything after the ':'
2159 * return string the position of the ':', or false if none found
2161 function findColonNoLinks($str, &$before, &$after) {
2162 $fname = 'Parser::findColonNoLinks';
2163 wfProfileIn( $fname );
2165 $pos = strpos( $str, ':' );
2166 if( $pos === false ) {
2168 wfProfileOut( $fname );
2172 $lt = strpos( $str, '<' );
2173 if( $lt === false ||
$lt > $pos ) {
2174 // Easy; no tag nesting to worry about
2175 $before = substr( $str, 0, $pos );
2176 $after = substr( $str, $pos+
1 );
2177 wfProfileOut( $fname );
2181 // Ugly state machine to walk through avoiding tags.
2182 $state = MW_COLON_STATE_TEXT
;
2184 $len = strlen( $str );
2185 for( $i = 0; $i < $len; $i++
) {
2189 // (Using the number is a performance hack for common cases)
2190 case 0: // MW_COLON_STATE_TEXT:
2193 // Could be either a <start> tag or an </end> tag
2194 $state = MW_COLON_STATE_TAGSTART
;
2199 $before = substr( $str, 0, $i );
2200 $after = substr( $str, $i +
1 );
2201 wfProfileOut( $fname );
2204 // Embedded in a tag; don't break it.
2207 // Skip ahead looking for something interesting
2208 $colon = strpos( $str, ':', $i );
2209 if( $colon === false ) {
2210 // Nothing else interesting
2211 wfProfileOut( $fname );
2214 $lt = strpos( $str, '<', $i );
2215 if( $stack === 0 ) {
2216 if( $lt === false ||
$colon < $lt ) {
2218 $before = substr( $str, 0, $colon );
2219 $after = substr( $str, $colon +
1 );
2220 wfProfileOut( $fname );
2224 if( $lt === false ) {
2225 // Nothing else interesting to find; abort!
2226 // We're nested, but there's no close tags left. Abort!
2229 // Skip ahead to next tag start
2231 $state = MW_COLON_STATE_TAGSTART
;
2234 case 1: // MW_COLON_STATE_TAG:
2239 $state = MW_COLON_STATE_TEXT
;
2242 // Slash may be followed by >?
2243 $state = MW_COLON_STATE_TAGSLASH
;
2249 case 2: // MW_COLON_STATE_TAGSTART:
2252 $state = MW_COLON_STATE_CLOSETAG
;
2255 $state = MW_COLON_STATE_COMMENT
;
2258 // Illegal early close? This shouldn't happen D:
2259 $state = MW_COLON_STATE_TEXT
;
2262 $state = MW_COLON_STATE_TAG
;
2265 case 3: // MW_COLON_STATE_CLOSETAG:
2270 wfDebug( "Invalid input in $fname; too many close tags\n" );
2271 wfProfileOut( $fname );
2274 $state = MW_COLON_STATE_TEXT
;
2277 case MW_COLON_STATE_TAGSLASH
:
2279 // Yes, a self-closed tag <blah/>
2280 $state = MW_COLON_STATE_TEXT
;
2282 // Probably we're jumping the gun, and this is an attribute
2283 $state = MW_COLON_STATE_TAG
;
2286 case 5: // MW_COLON_STATE_COMMENT:
2288 $state = MW_COLON_STATE_COMMENTDASH
;
2291 case MW_COLON_STATE_COMMENTDASH
:
2293 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2295 $state = MW_COLON_STATE_COMMENT
;
2298 case MW_COLON_STATE_COMMENTDASHDASH
:
2300 $state = MW_COLON_STATE_TEXT
;
2302 $state = MW_COLON_STATE_COMMENT
;
2306 throw new MWException( "State machine error in $fname" );
2310 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2313 wfProfileOut( $fname );
2318 * Return value of a magic variable (like PAGENAME)
2322 function getVariableValue( $index ) {
2323 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2326 * Some of these require message or data lookups and can be
2327 * expensive to check many times.
2329 static $varCache = array();
2330 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2331 if ( isset( $varCache[$index] ) ) {
2332 return $varCache[$index];
2337 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2340 global $wgLocaltimezone;
2341 if ( isset( $wgLocaltimezone ) ) {
2342 $oldtz = getenv( 'TZ' );
2343 putenv( 'TZ='.$wgLocaltimezone );
2345 $localTimestamp = date( 'YmdHis', $ts );
2346 $localMonth = date( 'm', $ts );
2347 $localMonthName = date( 'n', $ts );
2348 $localDay = date( 'j', $ts );
2349 $localDay2 = date( 'd', $ts );
2350 $localDayOfWeek = date( 'w', $ts );
2351 $localWeek = date( 'W', $ts );
2352 $localYear = date( 'Y', $ts );
2353 $localHour = date( 'H', $ts );
2354 if ( isset( $wgLocaltimezone ) ) {
2355 putenv( 'TZ='.$oldtz );
2359 case 'currentmonth':
2360 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2361 case 'currentmonthname':
2362 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2363 case 'currentmonthnamegen':
2364 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2365 case 'currentmonthabbrev':
2366 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2368 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2370 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2372 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2373 case 'localmonthname':
2374 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2375 case 'localmonthnamegen':
2376 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2377 case 'localmonthabbrev':
2378 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2380 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2382 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2384 return $this->mTitle
->getText();
2386 return $this->mTitle
->getPartialURL();
2387 case 'fullpagename':
2388 return $this->mTitle
->getPrefixedText();
2389 case 'fullpagenamee':
2390 return $this->mTitle
->getPrefixedURL();
2392 return $this->mTitle
->getSubpageText();
2393 case 'subpagenamee':
2394 return $this->mTitle
->getSubpageUrlForm();
2395 case 'basepagename':
2396 return $this->mTitle
->getBaseText();
2397 case 'basepagenamee':
2398 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2399 case 'talkpagename':
2400 if( $this->mTitle
->canTalk() ) {
2401 $talkPage = $this->mTitle
->getTalkPage();
2402 return $talkPage->getPrefixedText();
2406 case 'talkpagenamee':
2407 if( $this->mTitle
->canTalk() ) {
2408 $talkPage = $this->mTitle
->getTalkPage();
2409 return $talkPage->getPrefixedUrl();
2413 case 'subjectpagename':
2414 $subjPage = $this->mTitle
->getSubjectPage();
2415 return $subjPage->getPrefixedText();
2416 case 'subjectpagenamee':
2417 $subjPage = $this->mTitle
->getSubjectPage();
2418 return $subjPage->getPrefixedUrl();
2420 return $this->mRevisionId
;
2422 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2423 case 'revisionday2':
2424 return substr( $this->getRevisionTimestamp(), 6, 2 );
2425 case 'revisionmonth':
2426 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2427 case 'revisionyear':
2428 return substr( $this->getRevisionTimestamp(), 0, 4 );
2429 case 'revisiontimestamp':
2430 return $this->getRevisionTimestamp();
2432 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2434 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2436 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2438 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2439 case 'subjectspace':
2440 return $this->mTitle
->getSubjectNsText();
2441 case 'subjectspacee':
2442 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2443 case 'currentdayname':
2444 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2446 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2448 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2450 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2452 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2453 // int to remove the padding
2454 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2456 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2457 case 'localdayname':
2458 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2460 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2462 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2464 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2466 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2467 // int to remove the padding
2468 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2470 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2471 case 'numberofarticles':
2472 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2473 case 'numberoffiles':
2474 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2475 case 'numberofusers':
2476 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2477 case 'numberofpages':
2478 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2479 case 'numberofadmins':
2480 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2481 case 'currenttimestamp':
2482 return $varCache[$index] = wfTimestampNow();
2483 case 'localtimestamp':
2484 return $varCache[$index] = $localTimestamp;
2485 case 'currentversion':
2486 return $varCache[$index] = SpecialVersion
::getVersion();
2492 return $wgServerName;
2494 return $wgScriptPath;
2495 case 'directionmark':
2496 return $wgContLang->getDirMark();
2497 case 'contentlanguage':
2498 global $wgContLanguageCode;
2499 return $wgContLanguageCode;
2502 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2510 * initialise the magic variables (like CURRENTMONTHNAME)
2514 function initialiseVariables() {
2515 $fname = 'Parser::initialiseVariables';
2516 wfProfileIn( $fname );
2517 $variableIDs = MagicWord
::getVariableIDs();
2519 $this->mVariables
= array();
2520 foreach ( $variableIDs as $id ) {
2521 $mw =& MagicWord
::get( $id );
2522 $mw->addToArray( $this->mVariables
, $id );
2524 wfProfileOut( $fname );
2528 * parse any parentheses in format ((title|part|part))
2529 * and call callbacks to get a replacement text for any found piece
2531 * @param string $text The text to parse
2532 * @param array $callbacks rules in form:
2533 * '{' => array( # opening parentheses
2534 * 'end' => '}', # closing parentheses
2535 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2536 * 3 => callback # replacement callback to call if {{{..}}} is found
2539 * 'min' => 2, # Minimum parenthesis count in cb
2540 * 'max' => 3, # Maximum parenthesis count in cb
2543 function replace_callback ($text, $callbacks) {
2544 wfProfileIn( __METHOD__
);
2545 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2546 $lastOpeningBrace = -1; # last not closed parentheses
2548 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2551 while ( $i < strlen( $text ) ) {
2552 # Find next opening brace, closing brace or pipe
2553 if ( $lastOpeningBrace == -1 ) {
2554 $currentClosing = '';
2555 $search = $validOpeningBraces;
2557 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2558 $search = $validOpeningBraces . '|' . $currentClosing;
2561 $i +
= strcspn( $text, $search, $i );
2562 if ( $i < strlen( $text ) ) {
2563 if ( $text[$i] == '|' ) {
2565 } elseif ( $text[$i] == $currentClosing ) {
2567 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2569 $rule = $callbacks[$text[$i]];
2571 # Some versions of PHP have a strcspn which stops on null characters
2572 # Ignore and continue
2581 if ( $found == 'open' ) {
2582 # found opening brace, let's add it to parentheses stack
2583 $piece = array('brace' => $text[$i],
2584 'braceEnd' => $rule['end'],
2588 # count opening brace characters
2589 $piece['count'] = strspn( $text, $piece['brace'], $i );
2590 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2591 $i +
= $piece['count'];
2593 # we need to add to stack only if opening brace count is enough for one of the rules
2594 if ( $piece['count'] >= $rule['min'] ) {
2595 $lastOpeningBrace ++
;
2596 $openingBraceStack[$lastOpeningBrace] = $piece;
2598 } elseif ( $found == 'close' ) {
2599 # lets check if it is enough characters for closing brace
2600 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2601 $count = strspn( $text, $text[$i], $i, $maxCount );
2603 # check for maximum matching characters (if there are 5 closing
2604 # characters, we will probably need only 3 - depending on the rules)
2606 $matchingCallback = null;
2607 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2608 if ( $count > $cbType['max'] ) {
2609 # The specified maximum exists in the callback array, unless the caller
2611 $matchingCount = $cbType['max'];
2613 # Count is less than the maximum
2614 # Skip any gaps in the callback array to find the true largest match
2615 # Need to use array_key_exists not isset because the callback can be null
2616 $matchingCount = $count;
2617 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2622 if ($matchingCount <= 0) {
2626 $matchingCallback = $cbType['cb'][$matchingCount];
2628 # let's set a title or last part (if '|' was found)
2629 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2630 $openingBraceStack[$lastOpeningBrace]['title'] =
2631 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2632 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2634 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2635 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2636 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2639 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2640 $pieceEnd = $i +
$matchingCount;
2642 if( is_callable( $matchingCallback ) ) {
2644 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2645 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2646 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2647 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2649 # finally we can call a user callback and replace piece of text
2650 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2651 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2652 $i = $pieceStart +
strlen($replaceWith);
2654 # null value for callback means that parentheses should be parsed, but not replaced
2655 $i +
= $matchingCount;
2658 # reset last opening parentheses, but keep it in case there are unused characters
2659 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2660 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2661 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2664 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2665 $openingBraceStack[$lastOpeningBrace--] = null;
2667 if ($matchingCount < $piece['count']) {
2668 $piece['count'] -= $matchingCount;
2669 $piece['startAt'] -= $matchingCount;
2670 $piece['partStart'] = $piece['startAt'];
2671 # do we still qualify for any callback with remaining count?
2672 $currentCbList = $callbacks[$piece['brace']]['cb'];
2673 while ( $piece['count'] ) {
2674 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2675 $lastOpeningBrace++
;
2676 $openingBraceStack[$lastOpeningBrace] = $piece;
2682 } elseif ( $found == 'pipe' ) {
2683 # lets set a title if it is a first separator, or next part otherwise
2684 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2685 $openingBraceStack[$lastOpeningBrace]['title'] =
2686 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2687 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2688 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2690 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2691 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2692 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2694 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2698 wfProfileOut( __METHOD__
);
2703 * Replace magic variables, templates, and template arguments
2704 * with the appropriate text. Templates are substituted recursively,
2705 * taking care to avoid infinite loops.
2707 * Note that the substitution depends on value of $mOutputType:
2708 * OT_WIKI: only {{subst:}} templates
2709 * OT_MSG: only magic variables
2710 * OT_HTML: all templates and magic variables
2712 * @param string $tex The text to transform
2713 * @param array $args Key-value pairs representing template parameters to substitute
2714 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2717 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2718 # Prevent too big inclusions
2719 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2723 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2724 wfProfileIn( $fname );
2726 # This function is called recursively. To keep track of arguments we need a stack:
2727 array_push( $this->mArgStack
, $args );
2729 $braceCallbacks = array();
2731 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2733 if ( $this->mOutputType
!= OT_MSG
) {
2734 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2736 if ( $braceCallbacks ) {
2740 'cb' => $braceCallbacks,
2741 'min' => $argsOnly ?
3 : 2,
2742 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2746 'cb' => array(2=>null),
2751 $text = $this->replace_callback ($text, $callbacks);
2753 array_pop( $this->mArgStack
);
2755 wfProfileOut( $fname );
2760 * Replace magic variables
2763 function variableSubstitution( $matches ) {
2765 $fname = 'Parser::variableSubstitution';
2766 $varname = $wgContLang->lc($matches[1]);
2767 wfProfileIn( $fname );
2769 if ( $this->mOutputType
== OT_WIKI
) {
2770 # Do only magic variables prefixed by SUBST
2771 $mwSubst =& MagicWord
::get( 'subst' );
2772 if (!$mwSubst->matchStartAndRemove( $varname ))
2774 # Note that if we don't substitute the variable below,
2775 # we don't remove the {{subst:}} magic word, in case
2776 # it is a template rather than a magic variable.
2778 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2779 $id = $this->mVariables
[$varname];
2780 # Now check if we did really match, case sensitive or not
2781 $mw =& MagicWord
::get( $id );
2782 if ($mw->match($matches[1])) {
2783 $text = $this->getVariableValue( $id );
2784 $this->mOutput
->mContainsOldMagic
= true;
2786 $text = $matches[0];
2789 $text = $matches[0];
2791 wfProfileOut( $fname );
2796 * Return the text of a template, after recursively
2797 * replacing any variables or templates within the template.
2799 * @param array $piece The parts of the template
2800 * $piece['text']: matched text
2801 * $piece['title']: the title, i.e. the part before the |
2802 * $piece['parts']: the parameter array
2803 * @return string the text of the template
2806 function braceSubstitution( $piece ) {
2807 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2808 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2809 wfProfileIn( $fname );
2810 wfProfileIn( __METHOD__
.'-setup' );
2813 $found = false; # $text has been filled
2814 $nowiki = false; # wiki markup in $text should be escaped
2815 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2816 $noargs = false; # Don't replace triple-brace arguments in $text
2817 $replaceHeadings = false; # Make the edit section links go to the template not the article
2818 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2819 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2821 # Title object, where $text came from
2827 # $part1 is the bit before the first |, and must contain only title characters
2828 # $args is a list of arguments, starting from index 0, not including $part1
2830 $titleText = $part1 = $piece['title'];
2831 # If the third subpattern matched anything, it will start with |
2833 if (null == $piece['parts']) {
2834 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2835 if ($replaceWith != $piece['text']) {
2836 $text = $replaceWith;
2843 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2844 wfProfileOut( __METHOD__
.'-setup' );
2847 wfProfileIn( __METHOD__
.'-modifiers' );
2849 $mwSubst =& MagicWord
::get( 'subst' );
2850 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2851 # One of two possibilities is true:
2852 # 1) Found SUBST but not in the PST phase
2853 # 2) Didn't find SUBST and in the PST phase
2854 # In either case, return without further processing
2855 $text = $piece['text'];
2862 # MSG, MSGNW and RAW
2865 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2866 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2869 # Remove obsolete MSG:
2870 $mwMsg =& MagicWord
::get( 'msg' );
2871 $mwMsg->matchStartAndRemove( $part1 );
2875 $mwRaw =& MagicWord
::get( 'raw' );
2876 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2877 $forceRawInterwiki = true;
2880 wfProfileOut( __METHOD__
.'-modifiers' );
2884 wfProfileIn( __METHOD__
. '-pfunc' );
2886 $colonPos = strpos( $part1, ':' );
2887 if ( $colonPos !== false ) {
2888 # Case sensitive functions
2889 $function = substr( $part1, 0, $colonPos );
2890 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2891 $function = $this->mFunctionSynonyms
[1][$function];
2893 # Case insensitive functions
2894 $function = strtolower( $function );
2895 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2896 $function = $this->mFunctionSynonyms
[0][$function];
2902 $funcArgs = array_map( 'trim', $args );
2903 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2904 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2907 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2911 if ( is_array( $result ) ) {
2912 if ( isset( $result[0] ) ) {
2913 $text = $linestart . $result[0];
2914 unset( $result[0] );
2917 // Extract flags into the local scope
2918 // This allows callers to set flags such as nowiki, noparse, found, etc.
2921 $text = $linestart . $result;
2925 wfProfileOut( __METHOD__
. '-pfunc' );
2928 # Template table test
2930 # Did we encounter this template already? If yes, it is in the cache
2931 # and we need to check for loops.
2932 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2935 # Infinite loop test
2936 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2940 $text = $linestart .
2941 "[[$part1]]<!-- WARNING: template loop detected -->";
2942 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2944 # set $text to cached message.
2945 $text = $linestart . $this->mTemplates
[$piece['title']];
2949 # Load from database
2950 $lastPathLevel = $this->mTemplatePath
;
2952 wfProfileIn( __METHOD__
. '-loadtpl' );
2954 # declaring $subpage directly in the function call
2955 # does not work correctly with references and breaks
2956 # {{/subpage}}-style inclusions
2958 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2959 if ($subpage !== '') {
2960 $ns = $this->mTitle
->getNamespace();
2962 $title = Title
::newFromText( $part1, $ns );
2965 if ( !is_null( $title ) ) {
2966 $titleText = $title->getPrefixedText();
2967 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2968 # Check for language variants if the template is not found
2969 if($checkVariantLink && $title->getArticleID() == 0){
2970 $wgContLang->findVariantLink($part1, $title);
2973 if ( !$title->isExternal() ) {
2974 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2975 $text = SpecialPage
::capturePath( $title );
2976 if ( is_string( $text ) ) {
2981 $this->disableCache();
2984 $articleContent = $this->fetchTemplate( $title );
2985 if ( $articleContent !== false ) {
2987 $text = $articleContent;
2988 $replaceHeadings = true;
2992 # If the title is valid but undisplayable, make a link to it
2993 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2994 $text = "[[:$titleText]]";
2997 } elseif ( $title->isTrans() ) {
2998 // Interwiki transclusion
2999 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3000 $text = $this->interwikiTransclude( $title, 'render' );
3004 $text = $this->interwikiTransclude( $title, 'raw' );
3005 $replaceHeadings = true;
3010 # Template cache array insertion
3011 # Use the original $piece['title'] not the mangled $part1, so that
3012 # modifiers such as RAW: produce separate cache entries
3015 // A special page; don't store it in the template cache.
3017 $this->mTemplates
[$piece['title']] = $text;
3019 $text = $linestart . $text;
3022 wfProfileOut( __METHOD__
. '-loadtpl' );
3025 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3026 # Error, oversize inclusion
3027 $text = $linestart .
3028 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3033 # Recursive parsing, escaping and link table handling
3034 # Only for HTML output
3035 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3036 $text = wfEscapeWikiText( $text );
3037 } elseif ( !$this->ot
['msg'] && $found ) {
3039 $assocArgs = array();
3041 # Clean up argument array
3042 $assocArgs = array();
3044 foreach( $args as $arg ) {
3045 $eqpos = strpos( $arg, '=' );
3046 if ( $eqpos === false ) {
3047 $assocArgs[$index++
] = $arg;
3049 $name = trim( substr( $arg, 0, $eqpos ) );
3050 $value = trim( substr( $arg, $eqpos+
1 ) );
3051 if ( $value === false ) {
3054 if ( $name !== false ) {
3055 $assocArgs[$name] = $value;
3060 # Add a new element to the templace recursion path
3061 $this->mTemplatePath
[$part1] = 1;
3065 # If there are any <onlyinclude> tags, only include them
3066 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3067 $replacer = new OnlyIncludeReplacer
;
3068 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3069 array( &$replacer, 'replace' ), $text );
3070 $text = $replacer->output
;
3072 # Remove <noinclude> sections and <includeonly> tags
3073 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3074 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3076 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3077 # Strip <nowiki>, <pre>, etc.
3078 $text = $this->strip( $text, $this->mStripState
);
3079 if ( $this->ot
['html'] ) {
3080 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3081 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3082 $text = Sanitizer
::removeHTMLcomments( $text );
3085 $text = $this->replaceVariables( $text, $assocArgs );
3087 # If the template begins with a table or block-level
3088 # element, it should be treated as beginning a new line.
3089 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3090 $text = "\n" . $text;
3092 } elseif ( !$noargs ) {
3093 # $noparse and !$noargs
3094 # Just replace the arguments, not any double-brace items
3095 # This is used for rendered interwiki transclusion
3096 $text = $this->replaceVariables( $text, $assocArgs, true );
3099 # Prune lower levels off the recursion check path
3100 $this->mTemplatePath
= $lastPathLevel;
3102 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3103 # Error, oversize inclusion
3104 $text = $linestart .
3105 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3111 wfProfileOut( $fname );
3112 return $piece['text'];
3114 wfProfileIn( __METHOD__
. '-placeholders' );
3116 # Replace raw HTML by a placeholder
3117 # Add a blank line preceding, to prevent it from mucking up
3118 # immediately preceding headings
3119 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3121 # replace ==section headers==
3122 # XXX this needs to go away once we have a better parser.
3123 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3124 if( !is_null( $title ) )
3125 $encodedname = base64_encode($title->getPrefixedDBkey());
3127 $encodedname = base64_encode("");
3128 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3129 PREG_SPLIT_DELIM_CAPTURE
);
3132 for( $i = 0; $i < count($m); $i +
= 2 ) {
3134 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3136 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3141 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3142 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3143 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3149 wfProfileOut( __METHOD__
. '-placeholders' );
3152 # Prune lower levels off the recursion check path
3153 $this->mTemplatePath
= $lastPathLevel;
3156 wfProfileOut( $fname );
3157 return $piece['text'];
3159 wfProfileOut( $fname );
3165 * Fetch the unparsed text of a template and register a reference to it.
3167 function fetchTemplate( $title ) {
3169 // Loop to fetch the article, with up to 1 redirect
3170 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3171 $rev = Revision
::newFromTitle( $title );
3172 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3176 $text = $rev->getText();
3177 if ( $text === false ) {
3181 $title = Title
::newFromRedirect( $text );
3187 * Transclude an interwiki link.
3189 function interwikiTransclude( $title, $action ) {
3190 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3192 if (!$wgEnableScaryTranscluding)
3193 return wfMsg('scarytranscludedisabled');
3195 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3196 // But we'll handle it generally anyway
3197 if ( $title->getNamespace() ) {
3198 // Use the canonical namespace, which should work anywhere
3199 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3201 $articleName = $title->getDBkey();
3204 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3205 $url .= "?action=$action";
3206 if (strlen($url) > 255)
3207 return wfMsg('scarytranscludetoolong');
3208 return $this->fetchScaryTemplateMaybeFromCache($url);
3211 function fetchScaryTemplateMaybeFromCache($url) {
3212 global $wgTranscludeCacheExpiry;
3213 $dbr =& wfGetDB(DB_SLAVE
);
3214 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3215 array('tc_url' => $url));
3217 $time = $obj->tc_time
;
3218 $text = $obj->tc_contents
;
3219 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3224 $text = Http
::get($url);
3226 return wfMsg('scarytranscludefailed', $url);
3228 $dbw =& wfGetDB(DB_MASTER
);
3229 $dbw->replace('transcache', array('tc_url'), array(
3231 'tc_time' => time(),
3232 'tc_contents' => $text));
3238 * Triple brace replacement -- used for template arguments
3241 function argSubstitution( $matches ) {
3242 $arg = trim( $matches['title'] );
3243 $text = $matches['text'];
3244 $inputArgs = end( $this->mArgStack
);
3246 if ( array_key_exists( $arg, $inputArgs ) ) {
3247 $text = $inputArgs[$arg];
3248 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3249 null != $matches['parts'] && count($matches['parts']) > 0) {
3250 $text = $matches['parts'][0];
3252 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3253 $text = $matches['text'] .
3254 '<!-- WARNING: argument omitted, expansion size too large -->';
3261 * Increment an include size counter
3263 * @param string $type The type of expansion
3264 * @param integer $size The size of the text
3265 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3267 function incrementIncludeSize( $type, $size ) {
3268 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3271 $this->mIncludeSizes
[$type] +
= $size;
3277 * Detect __NOGALLERY__ magic word and set a placeholder
3279 function stripNoGallery( &$text ) {
3280 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3282 $mw = MagicWord
::get( 'nogallery' );
3283 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3287 * Detect __TOC__ magic word and set a placeholder
3289 function stripToc( $text ) {
3290 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3292 $mw = MagicWord
::get( 'notoc' );
3293 if( $mw->matchAndRemove( $text ) ) {
3294 $this->mShowToc
= false;
3297 $mw = MagicWord
::get( 'toc' );
3298 if( $mw->match( $text ) ) {
3299 $this->mShowToc
= true;
3300 $this->mForceTocPosition
= true;
3302 // Set a placeholder. At the end we'll fill it in with the TOC.
3303 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3305 // Only keep the first one.
3306 $text = $mw->replace( '', $text );
3312 * This function accomplishes several tasks:
3313 * 1) Auto-number headings if that option is enabled
3314 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3315 * 3) Add a Table of contents on the top for users who have enabled the option
3316 * 4) Auto-anchor headings
3318 * It loops through all headlines, collects the necessary data, then splits up the
3319 * string and re-inserts the newly formatted headlines.
3321 * @param string $text
3322 * @param boolean $isMain
3325 function formatHeadings( $text, $isMain=true ) {
3326 global $wgMaxTocLevel, $wgContLang;
3328 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3329 if( !$this->mTitle
->userCanEdit() ) {
3332 $showEditLink = $this->mOptions
->getEditSection();
3335 # Inhibit editsection links if requested in the page
3336 $esw =& MagicWord
::get( 'noeditsection' );
3337 if( $esw->matchAndRemove( $text ) ) {
3341 # Get all headlines for numbering them and adding funky stuff like [edit]
3342 # links - this is for later, but we need the number of headlines right now
3344 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3346 # if there are fewer than 4 headlines in the article, do not show TOC
3347 # unless it's been explicitly enabled.
3348 $enoughToc = $this->mShowToc
&&
3349 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3351 # Allow user to stipulate that a page should have a "new section"
3352 # link added via __NEWSECTIONLINK__
3353 $mw =& MagicWord
::get( 'newsectionlink' );
3354 if( $mw->matchAndRemove( $text ) )
3355 $this->mOutput
->setNewSection( true );
3357 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3358 # override above conditions and always show TOC above first header
3359 $mw =& MagicWord
::get( 'forcetoc' );
3360 if ($mw->matchAndRemove( $text ) ) {
3361 $this->mShowToc
= true;
3365 # Never ever show TOC if no headers
3366 if( $numMatches < 1 ) {
3370 # We need this to perform operations on the HTML
3371 $sk =& $this->mOptions
->getSkin();
3375 $sectionCount = 0; # headlineCount excluding template sections
3377 # Ugh .. the TOC should have neat indentation levels which can be
3378 # passed to the skin functions. These are determined here
3382 $sublevelCount = array();
3383 $levelCount = array();
3390 foreach( $matches[3] as $headline ) {
3392 $templatetitle = '';
3393 $templatesection = 0;
3396 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3398 $templatetitle = base64_decode($mat[1]);
3399 $templatesection = 1 +
(int)base64_decode($mat[2]);
3400 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3404 $prevlevel = $level;
3405 $prevtoclevel = $toclevel;
3407 $level = $matches[1][$headlineCount];
3409 if( $doNumberHeadings ||
$enoughToc ) {
3411 if ( $level > $prevlevel ) {
3412 # Increase TOC level
3414 $sublevelCount[$toclevel] = 0;
3415 if( $toclevel<$wgMaxTocLevel ) {
3416 $toc .= $sk->tocIndent();
3419 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3420 # Decrease TOC level, find level to jump to
3422 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3423 # Can only go down to level 1
3426 for ($i = $toclevel; $i > 0; $i--) {
3427 if ( $levelCount[$i] == $level ) {
3428 # Found last matching level
3432 elseif ( $levelCount[$i] < $level ) {
3433 # Found first matching level below current level
3439 if( $toclevel<$wgMaxTocLevel ) {
3440 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3444 # No change in level, end TOC line
3445 if( $toclevel<$wgMaxTocLevel ) {
3446 $toc .= $sk->tocLineEnd();
3450 $levelCount[$toclevel] = $level;
3452 # count number of headlines for each level
3453 @$sublevelCount[$toclevel]++
;
3455 for( $i = 1; $i <= $toclevel; $i++
) {
3456 if( !empty( $sublevelCount[$i] ) ) {
3460 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3466 # The canonized header is a version of the header text safe to use for links
3467 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3468 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3470 # Remove link placeholders by the link text.
3471 # <!--LINK number-->
3473 # link text with suffix
3474 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3475 "\$this->mLinkHolders['texts'][\$1]",
3476 $canonized_headline );
3477 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3478 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3479 $canonized_headline );
3482 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3483 $tocline = trim( $canonized_headline );
3484 # Save headline for section edit hint before it's escaped
3485 $headline_hint = trim( $canonized_headline );
3486 $canonized_headline = Sanitizer
::escapeId( $tocline );
3487 $refers[$headlineCount] = $canonized_headline;
3489 # count how many in assoc. array so we can track dupes in anchors
3490 @$refers[$canonized_headline]++
;
3491 $refcount[$headlineCount]=$refers[$canonized_headline];
3493 # Don't number the heading if it is the only one (looks silly)
3494 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3495 # the two are different if the line contains a link
3496 $headline=$numbering . ' ' . $headline;
3499 # Create the anchor for linking from the TOC to the section
3500 $anchor = $canonized_headline;
3501 if($refcount[$headlineCount] > 1 ) {
3502 $anchor .= '_' . $refcount[$headlineCount];
3504 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3505 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3507 # give headline the correct <h#> tag
3508 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3510 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3511 if ( empty( $head[$headlineCount] ) ) {
3512 $head[$headlineCount] = '';
3515 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3517 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3519 // Yes, the headline logically goes before the edit section. Why isn't it there
3520 // in source? Ask the CSS people. The float gets screwed up if you do that.
3521 // This might be moved to before the editsection at some point so that it will
3522 // display a bit more prettily without CSS, so please don't rely on the order.
3523 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3531 if( $toclevel<$wgMaxTocLevel ) {
3532 $toc .= $sk->tocUnindent( $toclevel - 1 );
3534 $toc = $sk->tocList( $toc );
3537 # split up and insert constructed headlines
3539 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3542 foreach( $blocks as $block ) {
3543 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3544 # This is the [edit] link that appears for the top block of text when
3545 # section editing is enabled
3547 # Disabled because it broke block formatting
3548 # For example, a bullet point in the top line
3549 # $full .= $sk->editSectionLink(0);
3552 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3553 # Top anchor now in skin
3557 if( !empty( $head[$i] ) ) {
3562 if( $this->mForceTocPosition
) {
3563 return str_replace( '<!--MWTOC-->', $toc, $full );
3570 * Transform wiki markup when saving a page by doing \r\n -> \n
3571 * conversion, substitting signatures, {{subst:}} templates, etc.
3573 * @param string $text the text to transform
3574 * @param Title &$title the Title object for the current article
3575 * @param User &$user the User object describing the current user
3576 * @param ParserOptions $options parsing options
3577 * @param bool $clearState whether to clear the parser state first
3578 * @return string the altered wiki markup
3581 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3582 $this->mOptions
= $options;
3583 $this->mTitle
=& $title;
3584 $this->setOutputType( OT_WIKI
);
3586 if ( $clearState ) {
3587 $this->clearState();
3590 $stripState = new StripState
;
3594 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3595 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3596 $text = $this->pstPass2( $text, $stripState, $user );
3597 $text = $stripState->unstripBoth( $text );
3602 * Pre-save transform helper function
3605 function pstPass2( $text, &$stripState, $user ) {
3606 global $wgContLang, $wgLocaltimezone;
3608 /* Note: This is the timestamp saved as hardcoded wikitext to
3609 * the database, we use $wgContLang here in order to give
3610 * everyone the same signature and use the default one rather
3611 * than the one selected in each user's preferences.
3613 if ( isset( $wgLocaltimezone ) ) {
3614 $oldtz = getenv( 'TZ' );
3615 putenv( 'TZ='.$wgLocaltimezone );
3617 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3618 ' (' . date( 'T' ) . ')';
3619 if ( isset( $wgLocaltimezone ) ) {
3620 putenv( 'TZ='.$oldtz );
3623 # Variable replacement
3624 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3625 $text = $this->replaceVariables( $text );
3627 # Strip out <nowiki> etc. added via replaceVariables
3628 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3631 $sigText = $this->getUserSig( $user );
3632 $text = strtr( $text, array(
3634 '~~~~' => "$sigText $d",
3638 # Context links: [[|name]] and [[name (context)|]]
3640 global $wgLegalTitleChars;
3641 $tc = "[$wgLegalTitleChars]";
3642 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3644 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3645 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3646 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3648 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3649 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3650 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3652 $t = $this->mTitle
->getText();
3654 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3655 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3656 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3657 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3659 # if there's no context, don't bother duplicating the title
3660 $text = preg_replace( $p2, '[[\\1]]', $text );
3663 # Trim trailing whitespace
3664 # __END__ tag allows for trailing
3665 # whitespace to be deliberately included
3666 $text = rtrim( $text );
3667 $mw =& MagicWord
::get( 'end' );
3668 $mw->matchAndRemove( $text );
3674 * Fetch the user's signature text, if any, and normalize to
3675 * validated, ready-to-insert wikitext.
3681 function getUserSig( &$user ) {
3682 $username = $user->getName();
3683 $nickname = $user->getOption( 'nickname' );
3684 $nickname = $nickname === '' ?
$username : $nickname;
3686 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3687 # Sig. might contain markup; validate this
3688 if( $this->validateSig( $nickname ) !== false ) {
3689 # Validated; clean up (if needed) and return it
3690 return $this->cleanSig( $nickname, true );
3692 # Failed to validate; fall back to the default
3693 $nickname = $username;
3694 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3698 // Make sure nickname doesnt get a sig in a sig
3699 $nickname = $this->cleanSigInSig( $nickname );
3701 # If we're still here, make it a link to the user page
3702 $userpage = $user->getUserPage();
3703 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3707 * Check that the user's signature contains no bad XML
3709 * @param string $text
3710 * @return mixed An expanded string, or false if invalid.
3712 function validateSig( $text ) {
3713 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3717 * Clean up signature text
3719 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3720 * 2) Substitute all transclusions
3722 * @param string $text
3723 * @param $parsing Whether we're cleaning (preferences save) or parsing
3724 * @return string Signature text
3726 function cleanSig( $text, $parsing = false ) {
3728 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3730 $substWord = MagicWord
::get( 'subst' );
3731 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3732 $substText = '{{' . $substWord->getSynonym( 0 );
3734 $text = preg_replace( $substRegex, $substText, $text );
3735 $text = $this->cleanSigInSig( $text );
3736 $text = $this->replaceVariables( $text );
3738 $this->clearState();
3743 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3744 * @param string $text
3745 * @return string Signature text with /~{3,5}/ removed
3747 function cleanSigInSig( $text ) {
3748 $text = preg_replace( '/~{3,5}/', '', $text );
3753 * Set up some variables which are usually set up in parse()
3754 * so that an external function can call some class members with confidence
3757 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3758 $this->mTitle
=& $title;
3759 $this->mOptions
= $options;
3760 $this->setOutputType( $outputType );
3761 if ( $clearState ) {
3762 $this->clearState();
3767 * Transform a MediaWiki message by replacing magic variables.
3769 * @param string $text the text to transform
3770 * @param ParserOptions $options options
3771 * @return string the text with variables substituted
3774 function transformMsg( $text, $options ) {
3776 static $executing = false;
3778 $fname = "Parser::transformMsg";
3780 # Guard against infinite recursion
3786 wfProfileIn($fname);
3789 $this->mTitle
= $wgTitle;
3791 $this->mTitle
= Title
::newFromText('msg');
3793 $this->mOptions
= $options;
3794 $this->setOutputType( OT_MSG
);
3795 $this->clearState();
3796 $text = $this->replaceVariables( $text );
3799 wfProfileOut($fname);
3804 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3805 * The callback should have the following form:
3806 * function myParserHook( $text, $params, &$parser ) { ... }
3808 * Transform and return $text. Use $parser for any required context, e.g. use
3809 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3813 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3814 * @param mixed $callback The callback function (and object) to use for the tag
3816 * @return The old value of the mTagHooks array associated with the hook
3818 function setHook( $tag, $callback ) {
3819 $tag = strtolower( $tag );
3820 $oldVal = @$this->mTagHooks
[$tag];
3821 $this->mTagHooks
[$tag] = $callback;
3827 * Create a function, e.g. {{sum:1|2|3}}
3828 * The callback function should have the form:
3829 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3831 * The callback may either return the text result of the function, or an array with the text
3832 * in element 0, and a number of flags in the other elements. The names of the flags are
3833 * specified in the keys. Valid flags are:
3834 * found The text returned is valid, stop processing the template. This
3836 * nowiki Wiki markup in the return value should be escaped
3837 * noparse Unsafe HTML tags should not be stripped, etc.
3838 * noargs Don't replace triple-brace arguments in the return value
3839 * isHTML The returned text is HTML, armour it against wikitext transformation
3843 * @param string $id The magic word ID
3844 * @param mixed $callback The callback function (and object) to use
3845 * @param integer $flags a combination of the following flags:
3846 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3848 * @return The old callback function for this name, if any
3850 function setFunctionHook( $id, $callback, $flags = 0 ) {
3851 $oldVal = @$this->mFunctionHooks
[$id];
3852 $this->mFunctionHooks
[$id] = $callback;
3854 # Add to function cache
3855 $mw = MagicWord
::get( $id );
3857 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3859 $synonyms = $mw->getSynonyms();
3860 $sensitive = intval( $mw->isCaseSensitive() );
3862 foreach ( $synonyms as $syn ) {
3864 if ( !$sensitive ) {
3865 $syn = strtolower( $syn );
3868 if ( !( $flags & SFH_NO_HASH
) ) {
3871 # Remove trailing colon
3872 if ( substr( $syn, -1, 1 ) == ':' ) {
3873 $syn = substr( $syn, 0, -1 );
3875 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3881 * Get all registered function hook identifiers
3885 function getFunctionHooks() {
3886 return array_keys( $this->mFunctionHooks
);
3890 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3891 * Placeholders created in Skin::makeLinkObj()
3892 * Returns an array of links found, indexed by PDBK:
3896 * $options is a bit field, RLH_FOR_UPDATE to select for update
3898 function replaceLinkHolders( &$text, $options = 0 ) {
3902 $fname = 'Parser::replaceLinkHolders';
3903 wfProfileIn( $fname );
3907 $sk =& $this->mOptions
->getSkin();
3908 $linkCache =& LinkCache
::singleton();
3910 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3911 wfProfileIn( $fname.'-check' );
3912 $dbr =& wfGetDB( DB_SLAVE
);
3913 $page = $dbr->tableName( 'page' );
3914 $threshold = $wgUser->getOption('stubthreshold');
3917 asort( $this->mLinkHolders
['namespaces'] );
3922 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3924 $title = $this->mLinkHolders
['titles'][$key];
3926 # Skip invalid entries.
3927 # Result will be ugly, but prevents crash.
3928 if ( is_null( $title ) ) {
3931 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3933 # Check if it's a static known link, e.g. interwiki
3934 if ( $title->isAlwaysKnown() ) {
3935 $colours[$pdbk] = 1;
3936 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3937 $colours[$pdbk] = 1;
3938 $this->mOutput
->addLink( $title, $id );
3939 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3940 $colours[$pdbk] = 0;
3942 # Not in the link cache, add it to the query
3943 if ( !isset( $current ) ) {
3945 $query = "SELECT page_id, page_namespace, page_title";
3946 if ( $threshold > 0 ) {
3947 $query .= ', page_len, page_is_redirect';
3949 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3950 } elseif ( $current != $ns ) {
3952 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3957 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3962 if ( $options & RLH_FOR_UPDATE
) {
3963 $query .= ' FOR UPDATE';
3966 $res = $dbr->query( $query, $fname );
3968 # Fetch data and form into an associative array
3969 # non-existent = broken
3972 while ( $s = $dbr->fetchObject($res) ) {
3973 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3974 $pdbk = $title->getPrefixedDBkey();
3975 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3976 $this->mOutput
->addLink( $title, $s->page_id
);
3978 if ( $threshold > 0 ) {
3979 $size = $s->page_len
;
3980 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3981 $colours[$pdbk] = 1;
3983 $colours[$pdbk] = 2;
3986 $colours[$pdbk] = 1;
3990 wfProfileOut( $fname.'-check' );
3992 # Do a second query for different language variants of links (if needed)
3993 if($wgContLang->hasVariants()){
3994 $linkBatch = new LinkBatch();
3995 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
3997 // Add variants of links to link batch
3998 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3999 $title = $this->mLinkHolders
['titles'][$key];
4000 if ( is_null( $title ) )
4003 $pdbk = $title->getPrefixedDBkey();
4005 // generate all variants of the link title text
4006 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4008 // if link was not found (in first query), add all variants to query
4009 if ( !isset($colours[$pdbk]) ){
4010 foreach($allTextVariants as $textVariant){
4011 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4012 if(is_null($variantTitle)) continue;
4013 $linkBatch->addObj( $variantTitle );
4014 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4020 if(!$linkBatch->isEmpty()){
4022 $titleClause = $linkBatch->constructSet('page', $dbr);
4024 $variantQuery = "SELECT page_id, page_namespace, page_title";
4025 if ( $threshold > 0 ) {
4026 $variantQuery .= ', page_len, page_is_redirect';
4029 $variantQuery .= " FROM $page WHERE $titleClause";
4030 if ( $options & RLH_FOR_UPDATE
) {
4031 $variantQuery .= ' FOR UPDATE';
4034 $varRes = $dbr->query( $variantQuery, $fname );
4036 // for each found variants, figure out link holders and replace
4037 while ( $s = $dbr->fetchObject($varRes) ) {
4039 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4040 $varPdbk = $variantTitle->getPrefixedDBkey();
4041 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4042 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4044 $holderKeys = $variantMap[$varPdbk];
4046 // loop over link holders
4047 foreach($holderKeys as $key){
4048 $title = $this->mLinkHolders
['titles'][$key];
4049 if ( is_null( $title ) ) continue;
4051 $pdbk = $title->getPrefixedDBkey();
4053 if(!isset($colours[$pdbk])){
4054 // found link in some of the variants, replace the link holder data
4055 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4056 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4058 // set pdbk and colour
4059 $pdbks[$key] = $varPdbk;
4060 if ( $threshold > 0 ) {
4061 $size = $s->page_len
;
4062 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4063 $colours[$varPdbk] = 1;
4065 $colours[$varPdbk] = 2;
4069 $colours[$varPdbk] = 1;
4077 # Construct search and replace arrays
4078 wfProfileIn( $fname.'-construct' );
4079 $replacePairs = array();
4080 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4081 $pdbk = $pdbks[$key];
4082 $searchkey = "<!--LINK $key-->";
4083 $title = $this->mLinkHolders
['titles'][$key];
4084 if ( empty( $colours[$pdbk] ) ) {
4085 $linkCache->addBadLinkObj( $title );
4086 $colours[$pdbk] = 0;
4087 $this->mOutput
->addLink( $title, 0 );
4088 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4089 $this->mLinkHolders
['texts'][$key],
4090 $this->mLinkHolders
['queries'][$key] );
4091 } elseif ( $colours[$pdbk] == 1 ) {
4092 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4093 $this->mLinkHolders
['texts'][$key],
4094 $this->mLinkHolders
['queries'][$key] );
4095 } elseif ( $colours[$pdbk] == 2 ) {
4096 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4097 $this->mLinkHolders
['texts'][$key],
4098 $this->mLinkHolders
['queries'][$key] );
4101 $replacer = new HashtableReplacer( $replacePairs, 1 );
4102 wfProfileOut( $fname.'-construct' );
4105 wfProfileIn( $fname.'-replace' );
4106 $text = preg_replace_callback(
4107 '/(<!--LINK .*?-->)/',
4111 wfProfileOut( $fname.'-replace' );
4114 # Now process interwiki link holders
4115 # This is quite a bit simpler than internal links
4116 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4117 wfProfileIn( $fname.'-interwiki' );
4118 # Make interwiki link HTML
4119 $replacePairs = array();
4120 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4121 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4122 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4124 $replacer = new HashtableReplacer( $replacePairs, 1 );
4126 $text = preg_replace_callback(
4127 '/<!--IWLINK (.*?)-->/',
4130 wfProfileOut( $fname.'-interwiki' );
4133 wfProfileOut( $fname );
4138 * Replace <!--LINK--> link placeholders with plain text of links
4139 * (not HTML-formatted).
4140 * @param string $text
4143 function replaceLinkHoldersText( $text ) {
4144 $fname = 'Parser::replaceLinkHoldersText';
4145 wfProfileIn( $fname );
4147 $text = preg_replace_callback(
4148 '/<!--(LINK|IWLINK) (.*?)-->/',
4149 array( &$this, 'replaceLinkHoldersTextCallback' ),
4152 wfProfileOut( $fname );
4157 * @param array $matches
4161 function replaceLinkHoldersTextCallback( $matches ) {
4162 $type = $matches[1];
4164 if( $type == 'LINK' ) {
4165 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4166 return $this->mLinkHolders
['texts'][$key];
4168 } elseif( $type == 'IWLINK' ) {
4169 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4170 return $this->mInterwikiLinkHolders
['texts'][$key];
4177 * Tag hook handler for 'pre'.
4179 function renderPreTag( $text, $attribs ) {
4180 // Backwards-compatibility hack
4181 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4183 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4184 return wfOpenElement( 'pre', $attribs ) .
4185 Xml
::escapeTagsOnly( $content ) .
4190 * Renders an image gallery from a text with one line per image.
4191 * text labels may be given by using |-style alternative text. E.g.
4192 * Image:one.jpg|The number "1"
4193 * Image:tree.jpg|A tree
4194 * given as text will return the HTML of a gallery with two images,
4195 * labeled 'The number "1"' and
4198 function renderImageGallery( $text, $params ) {
4199 $ig = new ImageGallery();
4200 $ig->setShowBytes( false );
4201 $ig->setShowFilename( false );
4203 $ig->useSkin( $this->mOptions
->getSkin() );
4205 if( isset( $params['caption'] ) )
4206 $ig->setCaption( $params['caption'] );
4208 $lines = explode( "\n", $text );
4209 foreach ( $lines as $line ) {
4210 # match lines like these:
4211 # Image:someimage.jpg|This is some image
4213 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4215 if ( count( $matches ) == 0 ) {
4218 $tp = Title
::newFromText( $matches[1] );
4220 if( is_null( $nt ) ) {
4221 # Bogus title. Ignore these so we don't bomb out later.
4224 if ( isset( $matches[3] ) ) {
4225 $label = $matches[3];
4230 $pout = $this->parse( $label,
4233 false, // Strip whitespace...?
4234 false // Don't clear state!
4236 $html = $pout->getText();
4238 $ig->add( new Image( $nt ), $html );
4240 # Only add real images (bug #5586)
4241 if ( $nt->getNamespace() == NS_IMAGE
) {
4242 $this->mOutput
->addImage( $nt->getDBkey() );
4245 return $ig->toHTML();
4249 * Parse image options text and use it to make an image
4251 function makeImage( $nt, $options ) {
4252 global $wgUseImageResize, $wgDjvuRenderer;
4256 # Check if the options text is of the form "options|alt text"
4258 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4259 # * left no resizing, just left align. label is used for alt= only
4260 # * right same, but right aligned
4261 # * none same, but not aligned
4262 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4263 # * center center the image
4264 # * framed Keep original image size, no magnify-button.
4266 $part = explode( '|', $options);
4268 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4269 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4270 $mwLeft =& MagicWord
::get( 'img_left' );
4271 $mwRight =& MagicWord
::get( 'img_right' );
4272 $mwNone =& MagicWord
::get( 'img_none' );
4273 $mwWidth =& MagicWord
::get( 'img_width' );
4274 $mwCenter =& MagicWord
::get( 'img_center' );
4275 $mwFramed =& MagicWord
::get( 'img_framed' );
4276 $mwPage =& MagicWord
::get( 'img_page' );
4279 $width = $height = $framed = $thumb = false;
4281 $manual_thumb = '' ;
4283 foreach( $part as $val ) {
4284 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4286 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4287 # use manually specified thumbnail
4289 $manual_thumb = $match;
4290 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4291 # remember to set an alignment, don't render immediately
4293 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4294 # remember to set an alignment, don't render immediately
4296 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4297 # remember to set an alignment, don't render immediately
4299 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4300 # remember to set an alignment, don't render immediately
4302 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4303 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4304 # Select a page in a multipage document
4306 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4307 wfDebug( "img_width match: $match\n" );
4308 # $match is the image width in pixels
4310 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4311 $width = intval( $m[1] );
4312 $height = intval( $m[2] );
4314 $width = intval($match);
4316 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4322 # Strip bad stuff out of the alt text
4323 $alt = $this->replaceLinkHoldersText( $caption );
4325 # make sure there are no placeholders in thumbnail attributes
4326 # that are later expanded to html- so expand them now and
4328 $alt = $this->mStripState
->unstripBoth( $alt );
4329 $alt = Sanitizer
::stripAllTags( $alt );
4331 # Linker does the rest
4332 $sk =& $this->mOptions
->getSkin();
4333 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4337 * Set a flag in the output object indicating that the content is dynamic and
4338 * shouldn't be cached.
4340 function disableCache() {
4341 wfDebug( "Parser output marked as uncacheable.\n" );
4342 $this->mOutput
->mCacheTime
= -1;
4346 * Callback from the Sanitizer for expanding items found in HTML attribute
4347 * values, so they can be safely tested and escaped.
4348 * @param string $text
4349 * @param array $args
4353 function attributeStripCallback( &$text, $args ) {
4354 $text = $this->replaceVariables( $text, $args );
4355 $text = $this->mStripState
->unstripBoth( $text );
4364 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4365 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4366 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4372 function getTags() { return array_keys( $this->mTagHooks
); }
4377 * Break wikitext input into sections, and either pull or replace
4378 * some particular section's text.
4380 * External callers should use the getSection and replaceSection methods.
4382 * @param $text Page wikitext
4383 * @param $section Numbered section. 0 pulls the text before the first
4384 * heading; other numbers will pull the given section
4385 * along with its lower-level subsections.
4386 * @param $mode One of "get" or "replace"
4387 * @param $newtext Replacement text for section data.
4388 * @return string for "get", the extracted section text.
4389 * for "replace", the whole page with the section replaced.
4391 private function extractSections( $text, $section, $mode, $newtext='' ) {
4392 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4393 # comments to be stripped as well)
4394 $stripState = new StripState
;
4396 $oldOutputType = $this->mOutputType
;
4397 $oldOptions = $this->mOptions
;
4398 $this->mOptions
= new ParserOptions();
4399 $this->setOutputType( OT_WIKI
);
4401 $striptext = $this->strip( $text, $stripState, true );
4403 $this->setOutputType( $oldOutputType );
4404 $this->mOptions
= $oldOptions;
4406 # now that we can be sure that no pseudo-sections are in the source,
4407 # split it up by section
4408 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4409 $comment = "(?:$uniq-!--.*?QINU)";
4414 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4416 (=+) # Should this be limited to 6?
4417 .+? # Section title...
4418 \\2 # Ending = count must match start
4425 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4432 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4433 (=+) # Should this be limited to 6?
4434 .+? # Section title...
4435 \\2 # Ending = count must match start
4436 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4445 PREG_SPLIT_DELIM_CAPTURE
);
4447 if( $mode == "get" ) {
4448 if( $section == 0 ) {
4449 // "Section 0" returns the content before any other section.
4454 } elseif( $mode == "replace" ) {
4455 if( $section == 0 ) {
4456 $rv = $newtext . "\n\n";
4465 for( $index = 1; $index < count( $secs ); ) {
4466 $headerLine = $secs[$index++
];
4467 if( $secs[$index] ) {
4469 $headerLevel = strlen( $secs[$index++
] );
4473 $headerLevel = intval( $secs[$index++
] );
4475 $content = $secs[$index++
];
4478 if( $mode == "get" ) {
4479 if( $count == $section ) {
4480 $rv = $headerLine . $content;
4481 $sectionLevel = $headerLevel;
4482 } elseif( $count > $section ) {
4483 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4484 $rv .= $headerLine . $content;
4486 // Broke out to a higher-level section
4490 } elseif( $mode == "replace" ) {
4491 if( $count < $section ) {
4492 $rv .= $headerLine . $content;
4493 } elseif( $count == $section ) {
4494 $rv .= $newtext . "\n\n";
4495 $sectionLevel = $headerLevel;
4496 } elseif( $count > $section ) {
4497 if( $headerLevel <= $sectionLevel ) {
4498 // Passed the section's sub-parts.
4502 $rv .= $headerLine . $content;
4507 # reinsert stripped tags
4508 $rv = trim( $stripState->unstripBoth( $rv ) );
4513 * This function returns the text of a section, specified by a number ($section).
4514 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4515 * the first section before any such heading (section 0).
4517 * If a section contains subsections, these are also returned.
4519 * @param $text String: text to look in
4520 * @param $section Integer: section number
4521 * @return string text of the requested section
4523 function getSection( $text, $section ) {
4524 return $this->extractSections( $text, $section, "get" );
4527 function replaceSection( $oldtext, $section, $text ) {
4528 return $this->extractSections( $oldtext, $section, "replace", $text );
4532 * Get the timestamp associated with the current revision, adjusted for
4533 * the user's current timestamp
4535 function getRevisionTimestamp() {
4536 if ( is_null( $this->mRevisionTimestamp
) ) {
4537 wfProfileIn( __METHOD__
);
4539 $dbr =& wfGetDB( DB_SLAVE
);
4540 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4541 array( 'rev_id' => $id ), __METHOD__
);
4542 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp );
4544 wfProfileOut( __METHOD__
);
4546 return $this->mRevisionTimestamp
;
4552 * @package MediaWiki
4556 var $mText, # The output text
4557 $mLanguageLinks, # List of the full text of language links, in the order they appear
4558 $mCategories, # Map of category names to sort keys
4559 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4560 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4561 $mVersion, # Compatibility check
4562 $mTitleText, # title text of the chosen language variant
4563 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4564 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4565 $mImages, # DB keys of the images used, in the array key only
4566 $mExternalLinks, # External link URLs, in the key only
4567 $mHTMLtitle, # Display HTML title
4568 $mSubtitle, # Additional subtitle
4569 $mNewSection, # Show a new section link?
4570 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4572 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4573 $containsOldMagic = false, $titletext = '' )
4575 $this->mText
= $text;
4576 $this->mLanguageLinks
= $languageLinks;
4577 $this->mCategories
= $categoryLinks;
4578 $this->mContainsOldMagic
= $containsOldMagic;
4579 $this->mCacheTime
= '';
4580 $this->mVersion
= MW_PARSER_VERSION
;
4581 $this->mTitleText
= $titletext;
4582 $this->mLinks
= array();
4583 $this->mTemplates
= array();
4584 $this->mImages
= array();
4585 $this->mExternalLinks
= array();
4586 $this->mHTMLtitle
= "" ;
4587 $this->mSubtitle
= "" ;
4588 $this->mNewSection
= false;
4589 $this->mNoGallery
= false;
4592 function getText() { return $this->mText
; }
4593 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4594 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4595 function &getCategories() { return $this->mCategories
; }
4596 function getCacheTime() { return $this->mCacheTime
; }
4597 function getTitleText() { return $this->mTitleText
; }
4598 function &getLinks() { return $this->mLinks
; }
4599 function &getTemplates() { return $this->mTemplates
; }
4600 function &getImages() { return $this->mImages
; }
4601 function &getExternalLinks() { return $this->mExternalLinks
; }
4602 function getNoGallery() { return $this->mNoGallery
; }
4603 function getSubtitle() { return $this->mSubtitle
; }
4605 function containsOldMagic() { return $this->mContainsOldMagic
; }
4606 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4607 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4608 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4609 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4610 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4611 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4612 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4614 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4615 function addImage( $name ) { $this->mImages
[$name] = 1; }
4616 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4617 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4619 function setNewSection( $value ) {
4620 $this->mNewSection
= (bool)$value;
4622 function getNewSection() {
4623 return (bool)$this->mNewSection
;
4626 function addLink( $title, $id = null ) {
4627 $ns = $title->getNamespace();
4628 $dbk = $title->getDBkey();
4629 if ( !isset( $this->mLinks
[$ns] ) ) {
4630 $this->mLinks
[$ns] = array();
4632 if ( is_null( $id ) ) {
4633 $id = $title->getArticleID();
4635 $this->mLinks
[$ns][$dbk] = $id;
4638 function addTemplate( $title, $id ) {
4639 $ns = $title->getNamespace();
4640 $dbk = $title->getDBkey();
4641 if ( !isset( $this->mTemplates
[$ns] ) ) {
4642 $this->mTemplates
[$ns] = array();
4644 $this->mTemplates
[$ns][$dbk] = $id;
4648 * Return true if this cached output object predates the global or
4649 * per-article cache invalidation timestamps, or if it comes from
4650 * an incompatible older version.
4652 * @param string $touched the affected article's last touched timestamp
4656 function expired( $touched ) {
4657 global $wgCacheEpoch;
4658 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4659 $this->getCacheTime() < $touched ||
4660 $this->getCacheTime() <= $wgCacheEpoch ||
4661 !isset( $this->mVersion
) ||
4662 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4667 * Set options of the Parser
4669 * @package MediaWiki
4673 # All variables are supposed to be private in theory, although in practise this is not the case.
4674 var $mUseTeX; # Use texvc to expand <math> tags
4675 var $mUseDynamicDates; # Use DateFormatter to format dates
4676 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4677 var $mAllowExternalImages; # Allow external images inline
4678 var $mAllowExternalImagesFrom; # If not, any exception?
4679 var $mSkin; # Reference to the preferred skin
4680 var $mDateFormat; # Date format index
4681 var $mEditSection; # Create "edit section" links
4682 var $mNumberHeadings; # Automatically number headings
4683 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4684 var $mTidy; # Ask for tidy cleanup
4685 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4686 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4687 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4689 var $mUser; # Stored user object, just used to initialise the skin
4691 function getUseTeX() { return $this->mUseTeX
; }
4692 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4693 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4694 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4695 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4696 function getEditSection() { return $this->mEditSection
; }
4697 function getNumberHeadings() { return $this->mNumberHeadings
; }
4698 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4699 function getTidy() { return $this->mTidy
; }
4700 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4701 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4702 function getRemoveComments() { return $this->mRemoveComments
; }
4704 function &getSkin() {
4705 if ( !isset( $this->mSkin
) ) {
4706 $this->mSkin
= $this->mUser
->getSkin();
4708 return $this->mSkin
;
4711 function getDateFormat() {
4712 if ( !isset( $this->mDateFormat
) ) {
4713 $this->mDateFormat
= $this->mUser
->getDatePreference();
4715 return $this->mDateFormat
;
4718 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4719 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4720 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4721 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4722 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4723 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4724 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4725 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4726 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4727 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4728 function setSkin( $x ) { $this->mSkin
= $x; }
4729 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4730 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4731 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4733 function ParserOptions( $user = null ) {
4734 $this->initialiseFromUser( $user );
4738 * Get parser options
4741 static function newFromUser( $user ) {
4742 return new ParserOptions( $user );
4745 /** Get user options */
4746 function initialiseFromUser( $userInput ) {
4747 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4748 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4749 $fname = 'ParserOptions::initialiseFromUser';
4750 wfProfileIn( $fname );
4751 if ( !$userInput ) {
4753 if ( isset( $wgUser ) ) {
4759 $user =& $userInput;
4762 $this->mUser
= $user;
4764 $this->mUseTeX
= $wgUseTeX;
4765 $this->mUseDynamicDates
= $wgUseDynamicDates;
4766 $this->mInterwikiMagic
= $wgInterwikiMagic;
4767 $this->mAllowExternalImages
= $wgAllowExternalImages;
4768 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4769 $this->mSkin
= null; # Deferred
4770 $this->mDateFormat
= null; # Deferred
4771 $this->mEditSection
= true;
4772 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4773 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4774 $this->mTidy
= false;
4775 $this->mInterfaceMessage
= false;
4776 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4777 $this->mRemoveComments
= true;
4778 wfProfileOut( $fname );
4782 class OnlyIncludeReplacer
{
4785 function replace( $matches ) {
4786 if ( substr( $matches[1], -1 ) == "\n" ) {
4787 $this->output
.= substr( $matches[1], 0, -1 );
4789 $this->output
.= $matches[1];
4795 var $general, $nowiki;
4797 function __construct() {
4798 $this->general
= new ReplacementArray
;
4799 $this->nowiki
= new ReplacementArray
;
4802 function unstripGeneral( $text ) {
4803 wfProfileIn( __METHOD__
);
4804 $text = $this->general
->replace( $text );
4805 wfProfileOut( __METHOD__
);
4809 function unstripNoWiki( $text ) {
4810 wfProfileIn( __METHOD__
);
4811 $text = $this->nowiki
->replace( $text );
4812 wfProfileOut( __METHOD__
);
4816 function unstripBoth( $text ) {
4817 wfProfileIn( __METHOD__
);
4818 $text = $this->general
->replace( $text );
4819 $text = $this->nowiki
->replace( $text );
4820 wfProfileOut( __METHOD__
);