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 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
387 $text = $this->strip( $text, $this->mStripState
);
388 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
389 $text = $this->internalParse( $text );
390 wfProfileOut( __METHOD__
);
395 * Expand templates and variables in the text, producing valid, static wikitext.
396 * Also removes comments.
398 function preprocess( $text, $title, $options ) {
399 wfProfileIn( __METHOD__
);
401 $this->setOutputType( OT_PREPROCESS
);
402 $this->mOptions
= $options;
403 $this->mTitle
= $title;
404 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
405 $text = $this->strip( $text, $this->mStripState
);
406 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
407 if ( $this->mOptions
->getRemoveComments() ) {
408 $text = Sanitizer
::removeHTMLcomments( $text );
410 $text = $this->replaceVariables( $text );
411 $text = $this->mStripState
->unstripBoth( $text );
412 wfProfileOut( __METHOD__
);
417 * Get a random string
422 function getRandomString() {
423 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
426 function &getTitle() { return $this->mTitle
; }
427 function getOptions() { return $this->mOptions
; }
429 function getFunctionLang() {
430 global $wgLang, $wgContLang;
431 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
435 * Replaces all occurrences of HTML-style comments and the given tags
436 * in the text with a random marker and returns teh next text. The output
437 * parameter $matches will be an associative array filled with data in
439 * 'UNIQ-xxxxx' => array(
442 * array( 'param' => 'x' ),
443 * '<element param="x">tag content</element>' ) )
445 * @param $elements list of element names. Comments are always extracted.
446 * @param $text Source text string.
447 * @param $uniq_prefix
452 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
457 $taglist = implode( '|', $elements );
458 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
460 while ( '' != $text ) {
461 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
463 if( count( $p ) < 5 ) {
466 if( count( $p ) > 5 ) {
480 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
481 $stripped .= $marker;
483 if ( $close === '/>' ) {
484 // Empty element tag, <tag />
489 if( $element == '!--' ) {
492 $end = "/(<\\/$element\\s*>)/i";
494 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
496 if( count( $q ) < 3 ) {
497 # No end tag -- let it run out to the end of the text.
506 $matches[$marker] = array( $element,
508 Sanitizer
::decodeTagAttributes( $attributes ),
509 "<$element$attributes$close$content$tail" );
515 * Strips and renders nowiki, pre, math, hiero
516 * If $render is set, performs necessary rendering operations on plugins
517 * Returns the text, and fills an array with data needed in unstrip()
519 * @param StripState $state
521 * @param bool $stripcomments when set, HTML comments <!-- like this -->
522 * will be stripped in addition to other tags. This is important
523 * for section editing, where these comments cause confusion when
524 * counting the sections in the wikisource
526 * @param array dontstrip contains tags which should not be stripped;
527 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
531 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 = $wgContLang->armourMath( 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 ( $text ) {
785 $fname = 'Parser::doTableStuff';
786 wfProfileIn( $fname );
788 $lines = explode ( "\n" , $text );
789 $td_history = array (); // Is currently a td tag open?
790 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
791 $tr_history = array (); // Is currently a tr tag open?
792 $tr_attributes = array (); // history of 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 ( $lines as $key => $line )
797 $line = trim ( $line );
799 if( $line == '' ) { // empty line, go to next line
802 $first_character = $line{0};
805 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
806 // First check if we are starting a new table
807 $indent_level = strlen( $matches[1] );
809 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
810 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
812 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
813 array_push ( $td_history , false );
814 array_push ( $last_tag_history , '' );
815 array_push ( $tr_history , false );
816 array_push ( $tr_attributes , '' );
817 array_push ( $has_opened_tr , false );
818 } else if ( count ( $td_history ) == 0 ) {
819 // Don't do any of the following
821 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
822 // We are ending a table
823 $line = '</table>' . substr ( $line , 2 );
824 $last_tag = array_pop ( $last_tag_history );
826 if ( !array_pop ( $has_opened_tr ) ) {
827 $line = "<tr><td></td></tr>{$line}";
830 if ( array_pop ( $tr_history ) ) {
831 $line = "</tr>{$line}";
834 if ( array_pop ( $td_history ) ) {
835 $line = "</{$last_tag}>{$line}";
837 array_pop ( $tr_attributes );
838 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
839 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
840 // Now we have a table row
841 $line = preg_replace( '#^\|-+#', '', $line );
843 // Whats after the tag is now only attributes
844 $attributes = $this->mStripState
->unstripBoth( $line );
845 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
846 array_pop ( $tr_attributes );
847 array_push ( $tr_attributes , $attributes );
850 $last_tag = array_pop ( $last_tag_history );
851 array_pop ( $has_opened_tr );
852 array_push ( $has_opened_tr , true );
854 if ( array_pop ( $tr_history ) ) {
858 if ( array_pop ( $td_history ) ) {
859 $line = "</{$last_tag}>{$line}";
862 $lines[$key] = $line;
863 array_push ( $tr_history , false );
864 array_push ( $td_history , false );
865 array_push ( $last_tag_history , '' );
867 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
868 // This might be cell elements, td, th or captions
869 if ( substr ( $line , 0 , 2 ) == '|+' ) {
870 $first_character = '+';
871 $line = substr ( $line , 1 );
874 $line = substr ( $line , 1 );
876 if ( $first_character == '!' ) {
877 $line = str_replace ( '!!' , '||' , $line );
880 // Split up multiple cells on the same line.
881 // FIXME : This can result in improper nesting of tags processed
882 // by earlier parser steps, but should avoid splitting up eg
883 // attribute values containing literal "||".
884 $cells = StringUtils
::explodeMarkup( '||' , $line );
888 // Loop through each table cell
889 foreach ( $cells as $cell )
892 if ( $first_character != '+' )
894 $tr_after = array_pop ( $tr_attributes );
895 if ( !array_pop ( $tr_history ) ) {
896 $previous = "<tr{$tr_after}>\n";
898 array_push ( $tr_history , true );
899 array_push ( $tr_attributes , '' );
900 array_pop ( $has_opened_tr );
901 array_push ( $has_opened_tr , true );
904 $last_tag = array_pop ( $last_tag_history );
906 if ( array_pop ( $td_history ) ) {
907 $previous = "</{$last_tag}>{$previous}";
910 if ( $first_character == '|' ) {
912 } else if ( $first_character == '!' ) {
914 } else if ( $first_character == '+' ) {
915 $last_tag = 'caption';
920 array_push ( $last_tag_history , $last_tag );
922 // A cell could contain both parameters and data
923 $cell_data = explode ( '|' , $cell , 2 );
925 // Bug 553: Note that a '|' inside an invalid link should not
926 // be mistaken as delimiting cell parameters
927 if ( strpos( $cell_data[0], '[[' ) !== false ) {
928 $cell = "{$previous}<{$last_tag}>{$cell}";
929 } else if ( count ( $cell_data ) == 1 )
930 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
932 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
933 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
934 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
937 $lines[$key] .= $cell;
938 array_push ( $td_history , true );
943 // Closing open td, tr && table
944 while ( count ( $td_history ) > 0 )
946 if ( array_pop ( $td_history ) ) {
949 if ( array_pop ( $tr_history ) ) {
952 if ( !array_pop ( $has_opened_tr ) ) {
953 $lines[] = "<tr><td></td></tr>" ;
956 $lines[] = '</table>' ;
959 $output = implode ( "\n" , $lines ) ;
961 // special case: don't return empty table
962 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
966 wfProfileOut( $fname );
972 * Helper function for parse() that transforms wiki markup into
973 * HTML. Only called for $mOutputType == OT_HTML.
977 function internalParse( $text ) {
980 $fname = 'Parser::internalParse';
981 wfProfileIn( $fname );
983 # Hook to suspend the parser in this state
984 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
985 wfProfileOut( $fname );
989 # Remove <noinclude> tags and <includeonly> sections
990 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
991 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
992 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
994 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
996 $text = $this->replaceVariables( $text, $args );
998 // Tables need to come after variable replacement for things to work
999 // properly; putting them before other transformations should keep
1000 // exciting things like link expansions from showing up in surprising
1002 $text = $this->doTableStuff( $text );
1004 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1006 $text = $this->stripToc( $text );
1007 $this->stripNoGallery( $text );
1008 $text = $this->doHeadings( $text );
1009 if($this->mOptions
->getUseDynamicDates()) {
1010 $df =& DateFormatter
::getInstance();
1011 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1013 $text = $this->doAllQuotes( $text );
1014 $text = $this->replaceInternalLinks( $text );
1015 $text = $this->replaceExternalLinks( $text );
1017 # replaceInternalLinks may sometimes leave behind
1018 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1019 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1021 $text = $this->doMagicLinks( $text );
1022 $text = $this->formatHeadings( $text, $isMain );
1024 wfProfileOut( $fname );
1029 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1030 * magic external links.
1034 function &doMagicLinks( &$text ) {
1035 wfProfileIn( __METHOD__
);
1036 $text = preg_replace_callback(
1038 <a.*?</a> | # Skip link text
1039 <.*?> | # Skip stuff inside HTML elements
1040 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1041 ISBN\s+(\b # ISBN, capture number as m[2]
1042 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1043 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1044 [0-9Xx] # check digit
1046 )!x', array( &$this, 'magicLinkCallback' ), $text );
1047 wfProfileOut( __METHOD__
);
1051 function magicLinkCallback( $m ) {
1052 if ( substr( $m[0], 0, 1 ) == '<' ) {
1055 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1057 $num = strtr( $isbn, array(
1062 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1063 $text = '<a href="' .
1064 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1065 "\" class=\"internal\">ISBN $isbn</a>";
1067 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1071 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1073 $urlmsg = 'pubmedurl';
1076 throw new MWException( __METHOD__
.': unrecognised match type "' .
1077 substr($m[0], 0, 20 ) . '"' );
1080 $url = wfMsg( $urlmsg, $id);
1081 $sk =& $this->mOptions
->getSkin();
1082 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1083 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1089 * Parse headers and return html
1093 function doHeadings( $text ) {
1094 $fname = 'Parser::doHeadings';
1095 wfProfileIn( $fname );
1096 for ( $i = 6; $i >= 1; --$i ) {
1097 $h = str_repeat( '=', $i );
1098 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1099 "<h{$i}>\\1</h{$i}>\\2", $text );
1101 wfProfileOut( $fname );
1106 * Replace single quotes with HTML markup
1108 * @return string the altered text
1110 function doAllQuotes( $text ) {
1111 $fname = 'Parser::doAllQuotes';
1112 wfProfileIn( $fname );
1114 $lines = explode( "\n", $text );
1115 foreach ( $lines as $line ) {
1116 $outtext .= $this->doQuotes ( $line ) . "\n";
1118 $outtext = substr($outtext, 0,-1);
1119 wfProfileOut( $fname );
1124 * Helper function for doAllQuotes()
1127 function doQuotes( $text ) {
1128 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1129 if ( count( $arr ) == 1 )
1133 # First, do some preliminary work. This may shift some apostrophes from
1134 # being mark-up to being text. It also counts the number of occurrences
1135 # of bold and italics mark-ups.
1139 foreach ( $arr as $r )
1141 if ( ( $i %
2 ) == 1 )
1143 # If there are ever four apostrophes, assume the first is supposed to
1144 # be text, and the remaining three constitute mark-up for bold text.
1145 if ( strlen( $arr[$i] ) == 4 )
1150 # If there are more than 5 apostrophes in a row, assume they're all
1151 # text except for the last 5.
1152 else if ( strlen( $arr[$i] ) > 5 )
1154 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1157 # Count the number of occurrences of bold and italics mark-ups.
1158 # We are not counting sequences of five apostrophes.
1159 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1160 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1161 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1166 # If there is an odd number of both bold and italics, it is likely
1167 # that one of the bold ones was meant to be an apostrophe followed
1168 # by italics. Which one we cannot know for certain, but it is more
1169 # likely to be one that has a single-letter word before it.
1170 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1173 $firstsingleletterword = -1;
1174 $firstmultiletterword = -1;
1176 foreach ( $arr as $r )
1178 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1180 $x1 = substr ($arr[$i-1], -1);
1181 $x2 = substr ($arr[$i-1], -2, 1);
1183 if ($firstspace == -1) $firstspace = $i;
1184 } else if ($x2 == ' ') {
1185 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1187 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1193 # If there is a single-letter word, use it!
1194 if ($firstsingleletterword > -1)
1196 $arr [ $firstsingleletterword ] = "''";
1197 $arr [ $firstsingleletterword-1 ] .= "'";
1199 # If not, but there's a multi-letter word, use that one.
1200 else if ($firstmultiletterword > -1)
1202 $arr [ $firstmultiletterword ] = "''";
1203 $arr [ $firstmultiletterword-1 ] .= "'";
1205 # ... otherwise use the first one that has neither.
1206 # (notice that it is possible for all three to be -1 if, for example,
1207 # there is only one pentuple-apostrophe in the line)
1208 else if ($firstspace > -1)
1210 $arr [ $firstspace ] = "''";
1211 $arr [ $firstspace-1 ] .= "'";
1215 # Now let's actually convert our apostrophic mush to HTML!
1220 foreach ($arr as $r)
1224 if ($state == 'both')
1231 if (strlen ($r) == 2)
1234 { $output .= '</i>'; $state = ''; }
1235 else if ($state == 'bi')
1236 { $output .= '</i>'; $state = 'b'; }
1237 else if ($state == 'ib')
1238 { $output .= '</b></i><b>'; $state = 'b'; }
1239 else if ($state == 'both')
1240 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1241 else # $state can be 'b' or ''
1242 { $output .= '<i>'; $state .= 'i'; }
1244 else if (strlen ($r) == 3)
1247 { $output .= '</b>'; $state = ''; }
1248 else if ($state == 'bi')
1249 { $output .= '</i></b><i>'; $state = 'i'; }
1250 else if ($state == 'ib')
1251 { $output .= '</b>'; $state = 'i'; }
1252 else if ($state == 'both')
1253 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1254 else # $state can be 'i' or ''
1255 { $output .= '<b>'; $state .= 'b'; }
1257 else if (strlen ($r) == 5)
1260 { $output .= '</b><i>'; $state = 'i'; }
1261 else if ($state == 'i')
1262 { $output .= '</i><b>'; $state = 'b'; }
1263 else if ($state == 'bi')
1264 { $output .= '</i></b>'; $state = ''; }
1265 else if ($state == 'ib')
1266 { $output .= '</b></i>'; $state = ''; }
1267 else if ($state == 'both')
1268 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1269 else # ($state == '')
1270 { $buffer = ''; $state = 'both'; }
1275 # Now close all remaining tags. Notice that the order is important.
1276 if ($state == 'b' ||
$state == 'ib')
1278 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1282 if ($state == 'both')
1283 $output .= '<b><i>'.$buffer.'</i></b>';
1289 * Replace external links
1291 * Note: this is all very hackish and the order of execution matters a lot.
1292 * Make sure to run maintenance/parserTests.php if you change this code.
1296 function replaceExternalLinks( $text ) {
1298 $fname = 'Parser::replaceExternalLinks';
1299 wfProfileIn( $fname );
1301 $sk =& $this->mOptions
->getSkin();
1303 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1305 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1308 while ( $i<count( $bits ) ) {
1310 $protocol = $bits[$i++
];
1311 $text = $bits[$i++
];
1312 $trail = $bits[$i++
];
1314 # The characters '<' and '>' (which were escaped by
1315 # removeHTMLtags()) should not be included in
1316 # URLs, per RFC 2396.
1318 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1319 $text = substr($url, $m2[0][1]) . ' ' . $text;
1320 $url = substr($url, 0, $m2[0][1]);
1323 # If the link text is an image URL, replace it with an <img> tag
1324 # This happened by accident in the original parser, but some people used it extensively
1325 $img = $this->maybeMakeExternalImage( $text );
1326 if ( $img !== false ) {
1332 # Set linktype for CSS - if URL==text, link is essentially free
1333 $linktype = ($text == $url) ?
'free' : 'text';
1335 # No link text, e.g. [http://domain.tld/some.link]
1336 if ( $text == '' ) {
1337 # Autonumber if allowed. See bug #5918
1338 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1339 $text = '[' . ++
$this->mAutonumber
. ']';
1340 $linktype = 'autonumber';
1342 # Otherwise just use the URL
1343 $text = htmlspecialchars( $url );
1347 # Have link text, e.g. [http://domain.tld/some.link text]s
1349 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1352 $text = $wgContLang->markNoConversion($text);
1354 $url = Sanitizer
::cleanUrl( $url );
1356 # Process the trail (i.e. everything after this link up until start of the next link),
1357 # replacing any non-bracketed links
1358 $trail = $this->replaceFreeExternalLinks( $trail );
1360 # Use the encoded URL
1361 # This means that users can paste URLs directly into the text
1362 # Funny characters like ö aren't valid in URLs anyway
1363 # This was changed in August 2004
1364 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1366 # Register link in the output object.
1367 # Replace unnecessary URL escape codes with the referenced character
1368 # This prevents spammers from hiding links from the filters
1369 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1370 $this->mOutput
->addExternalLink( $pasteurized );
1373 wfProfileOut( $fname );
1378 * Replace anything that looks like a URL with a link
1381 function replaceFreeExternalLinks( $text ) {
1383 $fname = 'Parser::replaceFreeExternalLinks';
1384 wfProfileIn( $fname );
1386 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1387 $s = array_shift( $bits );
1390 $sk =& $this->mOptions
->getSkin();
1392 while ( $i < count( $bits ) ){
1393 $protocol = $bits[$i++
];
1394 $remainder = $bits[$i++
];
1397 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1398 # Found some characters after the protocol that look promising
1399 $url = $protocol . $m[1];
1402 # special case: handle urls as url args:
1403 # http://www.example.com/foo?=http://www.example.com/bar
1404 if(strlen($trail) == 0 &&
1406 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1407 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1410 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1415 # The characters '<' and '>' (which were escaped by
1416 # removeHTMLtags()) should not be included in
1417 # URLs, per RFC 2396.
1419 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1420 $trail = substr($url, $m2[0][1]) . $trail;
1421 $url = substr($url, 0, $m2[0][1]);
1424 # Move trailing punctuation to $trail
1426 # If there is no left bracket, then consider right brackets fair game too
1427 if ( strpos( $url, '(' ) === false ) {
1431 $numSepChars = strspn( strrev( $url ), $sep );
1432 if ( $numSepChars ) {
1433 $trail = substr( $url, -$numSepChars ) . $trail;
1434 $url = substr( $url, 0, -$numSepChars );
1437 $url = Sanitizer
::cleanUrl( $url );
1439 # Is this an external image?
1440 $text = $this->maybeMakeExternalImage( $url );
1441 if ( $text === false ) {
1442 # Not an image, make a link
1443 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1444 # Register it in the output object...
1445 # Replace unnecessary URL escape codes with their equivalent characters
1446 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1447 $this->mOutput
->addExternalLink( $pasteurized );
1449 $s .= $text . $trail;
1451 $s .= $protocol . $remainder;
1454 wfProfileOut( $fname );
1459 * Replace unusual URL escape codes with their equivalent characters
1463 * @fixme This can merge genuinely required bits in the path or query string,
1464 * breaking legit URLs. A proper fix would treat the various parts of
1465 * the URL differently; as a workaround, just use the output for
1466 * statistical records, not for actual linking/output.
1468 static function replaceUnusualEscapes( $url ) {
1469 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1470 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1474 * Callback function used in replaceUnusualEscapes().
1475 * Replaces unusual URL escape codes with their equivalent character
1479 private static function replaceUnusualEscapesCallback( $matches ) {
1480 $char = urldecode( $matches[0] );
1481 $ord = ord( $char );
1482 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1483 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1484 // No, shouldn't be escaped
1487 // Yes, leave it escaped
1493 * make an image if it's allowed, either through the global
1494 * option or through the exception
1497 function maybeMakeExternalImage( $url ) {
1498 $sk =& $this->mOptions
->getSkin();
1499 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1500 $imagesexception = !empty($imagesfrom);
1502 if ( $this->mOptions
->getAllowExternalImages()
1503 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1504 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1506 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1513 * Process [[ ]] wikilinks
1517 function replaceInternalLinks( $s ) {
1519 static $fname = 'Parser::replaceInternalLinks' ;
1521 wfProfileIn( $fname );
1523 wfProfileIn( $fname.'-setup' );
1525 # the % is needed to support urlencoded titles as well
1526 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1528 $sk =& $this->mOptions
->getSkin();
1530 #split the entire text string on occurences of [[
1531 $a = explode( '[[', ' ' . $s );
1532 #get the first element (all text up to first [[), and remove the space we added
1533 $s = array_shift( $a );
1534 $s = substr( $s, 1 );
1536 # Match a link having the form [[namespace:link|alternate]]trail
1538 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1539 # Match cases where there is no "]]", which might still be images
1540 static $e1_img = FALSE;
1541 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1542 # Match the end of a line for a word that's not followed by whitespace,
1543 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1544 $e2 = wfMsgForContent( 'linkprefix' );
1546 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1548 if( is_null( $this->mTitle
) ) {
1549 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1551 $nottalk = !$this->mTitle
->isTalkPage();
1553 if ( $useLinkPrefixExtension ) {
1555 if ( preg_match( $e2, $s, $m ) ) {
1556 $first_prefix = $m[2];
1558 $first_prefix = false;
1564 $selflink = $this->mTitle
->getPrefixedText();
1565 $useSubpages = $this->areSubpagesAllowed();
1566 wfProfileOut( $fname.'-setup' );
1568 # Loop for each link
1569 for ($k = 0; isset( $a[$k] ); $k++
) {
1571 if ( $useLinkPrefixExtension ) {
1572 wfProfileIn( $fname.'-prefixhandling' );
1573 if ( preg_match( $e2, $s, $m ) ) {
1581 $prefix = $first_prefix;
1582 $first_prefix = false;
1584 wfProfileOut( $fname.'-prefixhandling' );
1587 $might_be_img = false;
1589 wfProfileIn( "$fname-e1" );
1590 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1592 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1593 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1594 # the real problem is with the $e1 regex
1597 # Still some problems for cases where the ] is meant to be outside punctuation,
1598 # and no image is in sight. See bug 2095.
1601 substr( $m[3], 0, 1 ) === ']' &&
1602 strpos($text, '[') !== false
1605 $text .= ']'; # so that replaceExternalLinks($text) works later
1606 $m[3] = substr( $m[3], 1 );
1608 # fix up urlencoded title texts
1609 if( strpos( $m[1], '%' ) !== false ) {
1610 # Should anchors '#' also be rejected?
1611 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1614 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1615 $might_be_img = true;
1617 if ( strpos( $m[1], '%' ) !== false ) {
1618 $m[1] = urldecode($m[1]);
1621 } else { # Invalid form; output directly
1622 $s .= $prefix . '[[' . $line ;
1623 wfProfileOut( "$fname-e1" );
1626 wfProfileOut( "$fname-e1" );
1627 wfProfileIn( "$fname-misc" );
1629 # Don't allow internal links to pages containing
1630 # PROTO: where PROTO is a valid URL protocol; these
1631 # should be external links.
1632 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1633 $s .= $prefix . '[[' . $line ;
1637 # Make subpage if necessary
1638 if( $useSubpages ) {
1639 $link = $this->maybeDoSubpageLink( $m[1], $text );
1644 $noforce = (substr($m[1], 0, 1) != ':');
1646 # Strip off leading ':'
1647 $link = substr($link, 1);
1650 wfProfileOut( "$fname-misc" );
1651 wfProfileIn( "$fname-title" );
1652 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1654 $s .= $prefix . '[[' . $line;
1655 wfProfileOut( "$fname-title" );
1659 $ns = $nt->getNamespace();
1660 $iw = $nt->getInterWiki();
1661 wfProfileOut( "$fname-title" );
1663 if ($might_be_img) { # if this is actually an invalid link
1664 wfProfileIn( "$fname-might_be_img" );
1665 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1667 while (isset ($a[$k+
1]) ) {
1668 #look at the next 'line' to see if we can close it there
1669 $spliced = array_splice( $a, $k +
1, 1 );
1670 $next_line = array_shift( $spliced );
1671 $m = explode( ']]', $next_line, 3 );
1672 if ( count( $m ) == 3 ) {
1673 # the first ]] closes the inner link, the second the image
1675 $text .= "[[{$m[0]}]]{$m[1]}";
1678 } elseif ( count( $m ) == 2 ) {
1679 #if there's exactly one ]] that's fine, we'll keep looking
1680 $text .= "[[{$m[0]}]]{$m[1]}";
1682 #if $next_line is invalid too, we need look no further
1683 $text .= '[[' . $next_line;
1688 # we couldn't find the end of this imageLink, so output it raw
1689 #but don't ignore what might be perfectly normal links in the text we've examined
1690 $text = $this->replaceInternalLinks($text);
1691 $s .= "{$prefix}[[$link|$text";
1692 # note: no $trail, because without an end, there *is* no trail
1693 wfProfileOut( "$fname-might_be_img" );
1696 } else { #it's not an image, so output it raw
1697 $s .= "{$prefix}[[$link|$text";
1698 # note: no $trail, because without an end, there *is* no trail
1699 wfProfileOut( "$fname-might_be_img" );
1702 wfProfileOut( "$fname-might_be_img" );
1705 $wasblank = ( '' == $text );
1706 if( $wasblank ) $text = $link;
1708 # Link not escaped by : , create the various objects
1712 wfProfileIn( "$fname-interwiki" );
1713 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1714 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1715 $s = rtrim($s . "\n");
1716 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1717 wfProfileOut( "$fname-interwiki" );
1720 wfProfileOut( "$fname-interwiki" );
1722 if ( $ns == NS_IMAGE
) {
1723 wfProfileIn( "$fname-image" );
1724 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1725 # recursively parse links inside the image caption
1726 # actually, this will parse them in any other parameters, too,
1727 # but it might be hard to fix that, and it doesn't matter ATM
1728 $text = $this->replaceExternalLinks($text);
1729 $text = $this->replaceInternalLinks($text);
1731 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1732 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1733 $this->mOutput
->addImage( $nt->getDBkey() );
1735 wfProfileOut( "$fname-image" );
1738 # We still need to record the image's presence on the page
1739 $this->mOutput
->addImage( $nt->getDBkey() );
1741 wfProfileOut( "$fname-image" );
1745 if ( $ns == NS_CATEGORY
) {
1746 wfProfileIn( "$fname-category" );
1747 $s = rtrim($s . "\n"); # bug 87
1750 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1751 $sortkey = $this->mTitle
->getText();
1753 $sortkey = $this->mTitle
->getPrefixedText();
1758 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1759 $sortkey = str_replace( "\n", '', $sortkey );
1760 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1761 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1764 * Strip the whitespace Category links produce, see bug 87
1765 * @todo We might want to use trim($tmp, "\n") here.
1767 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1769 wfProfileOut( "$fname-category" );
1774 if( ( $nt->getPrefixedText() === $selflink ) &&
1775 ( $nt->getFragment() === '' ) ) {
1776 # Self-links are handled specially; generally de-link and change to bold.
1777 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1781 # Special and Media are pseudo-namespaces; no pages actually exist in them
1782 if( $ns == NS_MEDIA
) {
1783 $link = $sk->makeMediaLinkObj( $nt, $text );
1784 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1785 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1786 $this->mOutput
->addImage( $nt->getDBkey() );
1788 } elseif( $ns == NS_SPECIAL
) {
1789 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1791 } elseif( $ns == NS_IMAGE
) {
1792 $img = new Image( $nt );
1793 if( $img->exists() ) {
1794 // Force a blue link if the file exists; may be a remote
1795 // upload on the shared repository, and we want to see its
1796 // auto-generated page.
1797 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1798 $this->mOutput
->addLink( $nt );
1802 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1804 wfProfileOut( $fname );
1809 * Make a link placeholder. The text returned can be later resolved to a real link with
1810 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1811 * parsing of interwiki links, and secondly to allow all existence checks and
1812 * article length checks (for stub links) to be bundled into a single query.
1815 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1816 wfProfileIn( __METHOD__
);
1817 if ( ! is_object($nt) ) {
1819 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1821 # Separate the link trail from the rest of the link
1822 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1824 if ( $nt->isExternal() ) {
1825 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1826 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1827 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1829 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1830 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1831 $this->mLinkHolders
['queries'][] = $query;
1832 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1833 $this->mLinkHolders
['titles'][] = $nt;
1835 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1838 wfProfileOut( __METHOD__
);
1843 * Render a forced-blue link inline; protect against double expansion of
1844 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1845 * Since this little disaster has to split off the trail text to avoid
1846 * breaking URLs in the following text without breaking trails on the
1847 * wiki links, it's been made into a horrible function.
1850 * @param string $text
1851 * @param string $query
1852 * @param string $trail
1853 * @param string $prefix
1854 * @return string HTML-wikitext mix oh yuck
1856 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1857 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1858 $sk =& $this->mOptions
->getSkin();
1859 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1860 return $this->armorLinks( $link ) . $trail;
1864 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1865 * going to go through further parsing steps before inline URL expansion.
1867 * In particular this is important when using action=render, which causes
1868 * full URLs to be included.
1870 * Oh man I hate our multi-layer parser!
1872 * @param string more-or-less HTML
1873 * @return string less-or-more HTML with NOPARSE bits
1875 function armorLinks( $text ) {
1876 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1877 "{$this->mUniqPrefix}NOPARSE$1", $text );
1881 * Return true if subpage links should be expanded on this page.
1884 function areSubpagesAllowed() {
1885 # Some namespaces don't allow subpages
1886 global $wgNamespacesWithSubpages;
1887 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1891 * Handle link to subpage if necessary
1892 * @param string $target the source of the link
1893 * @param string &$text the link text, modified as necessary
1894 * @return string the full name of the link
1897 function maybeDoSubpageLink($target, &$text) {
1900 # :Foobar -- override special treatment of prefix (images, language links)
1901 # /Foobar -- convert to CurrentPage/Foobar
1902 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1903 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1904 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1906 $fname = 'Parser::maybeDoSubpageLink';
1907 wfProfileIn( $fname );
1908 $ret = $target; # default return value is no change
1911 $target = trim( $target );
1913 # Some namespaces don't allow subpages,
1914 # so only perform processing if subpages are allowed
1915 if( $this->areSubpagesAllowed() ) {
1916 # Look at the first character
1917 if( $target != '' && $target{0} == '/' ) {
1918 # / at end means we don't want the slash to be shown
1919 if( substr( $target, -1, 1 ) == '/' ) {
1920 $target = substr( $target, 1, -1 );
1923 $noslash = substr( $target, 1 );
1926 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1927 if( '' === $text ) {
1929 } # this might be changed for ugliness reasons
1931 # check for .. subpage backlinks
1933 $nodotdot = $target;
1934 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1936 $nodotdot = substr( $nodotdot, 3 );
1938 if($dotdotcount > 0) {
1939 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1940 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1941 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1942 # / at the end means don't show full path
1943 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1944 $nodotdot = substr( $nodotdot, 0, -1 );
1945 if( '' === $text ) {
1949 $nodotdot = trim( $nodotdot );
1950 if( $nodotdot != '' ) {
1951 $ret .= '/' . $nodotdot;
1958 wfProfileOut( $fname );
1963 * Used by doBlockLevels()
1966 /* private */ function closeParagraph() {
1968 if ( '' != $this->mLastSection
) {
1969 $result = '</' . $this->mLastSection
. ">\n";
1971 $this->mInPre
= false;
1972 $this->mLastSection
= '';
1975 # getCommon() returns the length of the longest common substring
1976 # of both arguments, starting at the beginning of both.
1978 /* private */ function getCommon( $st1, $st2 ) {
1979 $fl = strlen( $st1 );
1980 $shorter = strlen( $st2 );
1981 if ( $fl < $shorter ) { $shorter = $fl; }
1983 for ( $i = 0; $i < $shorter; ++
$i ) {
1984 if ( $st1{$i} != $st2{$i} ) { break; }
1988 # These next three functions open, continue, and close the list
1989 # element appropriate to the prefix character passed into them.
1991 /* private */ function openList( $char ) {
1992 $result = $this->closeParagraph();
1994 if ( '*' == $char ) { $result .= '<ul><li>'; }
1995 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1996 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1997 else if ( ';' == $char ) {
1998 $result .= '<dl><dt>';
1999 $this->mDTopen
= true;
2001 else { $result = '<!-- ERR 1 -->'; }
2006 /* private */ function nextItem( $char ) {
2007 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2008 else if ( ':' == $char ||
';' == $char ) {
2010 if ( $this->mDTopen
) { $close = '</dt>'; }
2011 if ( ';' == $char ) {
2012 $this->mDTopen
= true;
2013 return $close . '<dt>';
2015 $this->mDTopen
= false;
2016 return $close . '<dd>';
2019 return '<!-- ERR 2 -->';
2022 /* private */ function closeList( $char ) {
2023 if ( '*' == $char ) { $text = '</li></ul>'; }
2024 else if ( '#' == $char ) { $text = '</li></ol>'; }
2025 else if ( ':' == $char ) {
2026 if ( $this->mDTopen
) {
2027 $this->mDTopen
= false;
2028 $text = '</dt></dl>';
2030 $text = '</dd></dl>';
2033 else { return '<!-- ERR 3 -->'; }
2039 * Make lists from lines starting with ':', '*', '#', etc.
2042 * @return string the lists rendered as HTML
2044 function doBlockLevels( $text, $linestart ) {
2045 $fname = 'Parser::doBlockLevels';
2046 wfProfileIn( $fname );
2048 # Parsing through the text line by line. The main thing
2049 # happening here is handling of block-level elements p, pre,
2050 # and making lists from lines starting with * # : etc.
2052 $textLines = explode( "\n", $text );
2054 $lastPrefix = $output = '';
2055 $this->mDTopen
= $inBlockElem = false;
2057 $paragraphStack = false;
2059 if ( !$linestart ) {
2060 $output .= array_shift( $textLines );
2062 foreach ( $textLines as $oLine ) {
2063 $lastPrefixLength = strlen( $lastPrefix );
2064 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2065 $preOpenMatch = preg_match('/<pre/i', $oLine );
2066 if ( !$this->mInPre
) {
2067 # Multiple prefixes may abut each other for nested lists.
2068 $prefixLength = strspn( $oLine, '*#:;' );
2069 $pref = substr( $oLine, 0, $prefixLength );
2072 $pref2 = str_replace( ';', ':', $pref );
2073 $t = substr( $oLine, $prefixLength );
2074 $this->mInPre
= !empty($preOpenMatch);
2076 # Don't interpret any other prefixes in preformatted text
2078 $pref = $pref2 = '';
2083 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2084 # Same as the last item, so no need to deal with nesting or opening stuff
2085 $output .= $this->nextItem( substr( $pref, -1 ) );
2086 $paragraphStack = false;
2088 if ( substr( $pref, -1 ) == ';') {
2089 # The one nasty exception: definition lists work like this:
2090 # ; title : definition text
2091 # So we check for : in the remainder text to split up the
2092 # title and definition, without b0rking links.
2094 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2096 $output .= $term . $this->nextItem( ':' );
2099 } elseif( $prefixLength ||
$lastPrefixLength ) {
2100 # Either open or close a level...
2101 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2102 $paragraphStack = false;
2104 while( $commonPrefixLength < $lastPrefixLength ) {
2105 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2106 --$lastPrefixLength;
2108 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2109 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2111 while ( $prefixLength > $commonPrefixLength ) {
2112 $char = substr( $pref, $commonPrefixLength, 1 );
2113 $output .= $this->openList( $char );
2115 if ( ';' == $char ) {
2116 # FIXME: This is dupe of code above
2117 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2119 $output .= $term . $this->nextItem( ':' );
2122 ++
$commonPrefixLength;
2124 $lastPrefix = $pref2;
2126 if( 0 == $prefixLength ) {
2127 wfProfileIn( "$fname-paragraph" );
2128 # No prefix (not in list)--go to paragraph mode
2129 // XXX: use a stack for nestable elements like span, table and div
2130 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2131 $closematch = preg_match(
2132 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2133 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2134 if ( $openmatch or $closematch ) {
2135 $paragraphStack = false;
2136 #Â TODO bug 5718: paragraph closed
2137 $output .= $this->closeParagraph();
2138 if ( $preOpenMatch and !$preCloseMatch ) {
2139 $this->mInPre
= true;
2141 if ( $closematch ) {
2142 $inBlockElem = false;
2144 $inBlockElem = true;
2146 } else if ( !$inBlockElem && !$this->mInPre
) {
2147 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2149 if ($this->mLastSection
!= 'pre') {
2150 $paragraphStack = false;
2151 $output .= $this->closeParagraph().'<pre>';
2152 $this->mLastSection
= 'pre';
2154 $t = substr( $t, 1 );
2157 if ( '' == trim($t) ) {
2158 if ( $paragraphStack ) {
2159 $output .= $paragraphStack.'<br />';
2160 $paragraphStack = false;
2161 $this->mLastSection
= 'p';
2163 if ($this->mLastSection
!= 'p' ) {
2164 $output .= $this->closeParagraph();
2165 $this->mLastSection
= '';
2166 $paragraphStack = '<p>';
2168 $paragraphStack = '</p><p>';
2172 if ( $paragraphStack ) {
2173 $output .= $paragraphStack;
2174 $paragraphStack = false;
2175 $this->mLastSection
= 'p';
2176 } else if ($this->mLastSection
!= 'p') {
2177 $output .= $this->closeParagraph().'<p>';
2178 $this->mLastSection
= 'p';
2183 wfProfileOut( "$fname-paragraph" );
2185 // somewhere above we forget to get out of pre block (bug 785)
2186 if($preCloseMatch && $this->mInPre
) {
2187 $this->mInPre
= false;
2189 if ($paragraphStack === false) {
2193 while ( $prefixLength ) {
2194 $output .= $this->closeList( $pref2{$prefixLength-1} );
2197 if ( '' != $this->mLastSection
) {
2198 $output .= '</' . $this->mLastSection
. '>';
2199 $this->mLastSection
= '';
2202 wfProfileOut( $fname );
2207 * Split up a string on ':', ignoring any occurences inside tags
2208 * to prevent illegal overlapping.
2209 * @param string $str the string to split
2210 * @param string &$before set to everything before the ':'
2211 * @param string &$after set to everything after the ':'
2212 * return string the position of the ':', or false if none found
2214 function findColonNoLinks($str, &$before, &$after) {
2215 $fname = 'Parser::findColonNoLinks';
2216 wfProfileIn( $fname );
2218 $pos = strpos( $str, ':' );
2219 if( $pos === false ) {
2221 wfProfileOut( $fname );
2225 $lt = strpos( $str, '<' );
2226 if( $lt === false ||
$lt > $pos ) {
2227 // Easy; no tag nesting to worry about
2228 $before = substr( $str, 0, $pos );
2229 $after = substr( $str, $pos+
1 );
2230 wfProfileOut( $fname );
2234 // Ugly state machine to walk through avoiding tags.
2235 $state = MW_COLON_STATE_TEXT
;
2237 $len = strlen( $str );
2238 for( $i = 0; $i < $len; $i++
) {
2242 // (Using the number is a performance hack for common cases)
2243 case 0: // MW_COLON_STATE_TEXT:
2246 // Could be either a <start> tag or an </end> tag
2247 $state = MW_COLON_STATE_TAGSTART
;
2252 $before = substr( $str, 0, $i );
2253 $after = substr( $str, $i +
1 );
2254 wfProfileOut( $fname );
2257 // Embedded in a tag; don't break it.
2260 // Skip ahead looking for something interesting
2261 $colon = strpos( $str, ':', $i );
2262 if( $colon === false ) {
2263 // Nothing else interesting
2264 wfProfileOut( $fname );
2267 $lt = strpos( $str, '<', $i );
2268 if( $stack === 0 ) {
2269 if( $lt === false ||
$colon < $lt ) {
2271 $before = substr( $str, 0, $colon );
2272 $after = substr( $str, $colon +
1 );
2273 wfProfileOut( $fname );
2277 if( $lt === false ) {
2278 // Nothing else interesting to find; abort!
2279 // We're nested, but there's no close tags left. Abort!
2282 // Skip ahead to next tag start
2284 $state = MW_COLON_STATE_TAGSTART
;
2287 case 1: // MW_COLON_STATE_TAG:
2292 $state = MW_COLON_STATE_TEXT
;
2295 // Slash may be followed by >?
2296 $state = MW_COLON_STATE_TAGSLASH
;
2302 case 2: // MW_COLON_STATE_TAGSTART:
2305 $state = MW_COLON_STATE_CLOSETAG
;
2308 $state = MW_COLON_STATE_COMMENT
;
2311 // Illegal early close? This shouldn't happen D:
2312 $state = MW_COLON_STATE_TEXT
;
2315 $state = MW_COLON_STATE_TAG
;
2318 case 3: // MW_COLON_STATE_CLOSETAG:
2323 wfDebug( "Invalid input in $fname; too many close tags\n" );
2324 wfProfileOut( $fname );
2327 $state = MW_COLON_STATE_TEXT
;
2330 case MW_COLON_STATE_TAGSLASH
:
2332 // Yes, a self-closed tag <blah/>
2333 $state = MW_COLON_STATE_TEXT
;
2335 // Probably we're jumping the gun, and this is an attribute
2336 $state = MW_COLON_STATE_TAG
;
2339 case 5: // MW_COLON_STATE_COMMENT:
2341 $state = MW_COLON_STATE_COMMENTDASH
;
2344 case MW_COLON_STATE_COMMENTDASH
:
2346 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2348 $state = MW_COLON_STATE_COMMENT
;
2351 case MW_COLON_STATE_COMMENTDASHDASH
:
2353 $state = MW_COLON_STATE_TEXT
;
2355 $state = MW_COLON_STATE_COMMENT
;
2359 throw new MWException( "State machine error in $fname" );
2363 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2366 wfProfileOut( $fname );
2371 * Return value of a magic variable (like PAGENAME)
2375 function getVariableValue( $index ) {
2376 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2379 * Some of these require message or data lookups and can be
2380 * expensive to check many times.
2382 static $varCache = array();
2383 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2384 if ( isset( $varCache[$index] ) ) {
2385 return $varCache[$index];
2390 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2393 global $wgLocaltimezone;
2394 if ( isset( $wgLocaltimezone ) ) {
2395 $oldtz = getenv( 'TZ' );
2396 putenv( 'TZ='.$wgLocaltimezone );
2398 $localTimestamp = date( 'YmdHis', $ts );
2399 $localMonth = date( 'm', $ts );
2400 $localMonthName = date( 'n', $ts );
2401 $localDay = date( 'j', $ts );
2402 $localDay2 = date( 'd', $ts );
2403 $localDayOfWeek = date( 'w', $ts );
2404 $localWeek = date( 'W', $ts );
2405 $localYear = date( 'Y', $ts );
2406 $localHour = date( 'H', $ts );
2407 if ( isset( $wgLocaltimezone ) ) {
2408 putenv( 'TZ='.$oldtz );
2412 case 'currentmonth':
2413 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2414 case 'currentmonthname':
2415 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2416 case 'currentmonthnamegen':
2417 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2418 case 'currentmonthabbrev':
2419 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2421 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2423 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2425 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2426 case 'localmonthname':
2427 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2428 case 'localmonthnamegen':
2429 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2430 case 'localmonthabbrev':
2431 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2433 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2435 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2437 return $this->mTitle
->getText();
2439 return $this->mTitle
->getPartialURL();
2440 case 'fullpagename':
2441 return $this->mTitle
->getPrefixedText();
2442 case 'fullpagenamee':
2443 return $this->mTitle
->getPrefixedURL();
2445 return $this->mTitle
->getSubpageText();
2446 case 'subpagenamee':
2447 return $this->mTitle
->getSubpageUrlForm();
2448 case 'basepagename':
2449 return $this->mTitle
->getBaseText();
2450 case 'basepagenamee':
2451 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2452 case 'talkpagename':
2453 if( $this->mTitle
->canTalk() ) {
2454 $talkPage = $this->mTitle
->getTalkPage();
2455 return $talkPage->getPrefixedText();
2459 case 'talkpagenamee':
2460 if( $this->mTitle
->canTalk() ) {
2461 $talkPage = $this->mTitle
->getTalkPage();
2462 return $talkPage->getPrefixedUrl();
2466 case 'subjectpagename':
2467 $subjPage = $this->mTitle
->getSubjectPage();
2468 return $subjPage->getPrefixedText();
2469 case 'subjectpagenamee':
2470 $subjPage = $this->mTitle
->getSubjectPage();
2471 return $subjPage->getPrefixedUrl();
2473 return $this->mRevisionId
;
2475 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2476 case 'revisionday2':
2477 return substr( $this->getRevisionTimestamp(), 6, 2 );
2478 case 'revisionmonth':
2479 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2480 case 'revisionyear':
2481 return substr( $this->getRevisionTimestamp(), 0, 4 );
2482 case 'revisiontimestamp':
2483 return $this->getRevisionTimestamp();
2485 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2487 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2489 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2491 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2492 case 'subjectspace':
2493 return $this->mTitle
->getSubjectNsText();
2494 case 'subjectspacee':
2495 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2496 case 'currentdayname':
2497 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2499 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2501 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2503 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2505 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2506 // int to remove the padding
2507 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2509 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2510 case 'localdayname':
2511 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2513 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2515 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2517 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2519 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2520 // int to remove the padding
2521 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2523 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2524 case 'numberofarticles':
2525 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2526 case 'numberoffiles':
2527 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2528 case 'numberofusers':
2529 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2530 case 'numberofpages':
2531 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2532 case 'numberofadmins':
2533 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2534 case 'currenttimestamp':
2535 return $varCache[$index] = wfTimestampNow();
2536 case 'localtimestamp':
2537 return $varCache[$index] = $localTimestamp;
2538 case 'currentversion':
2539 return $varCache[$index] = SpecialVersion
::getVersion();
2545 return $wgServerName;
2547 return $wgScriptPath;
2548 case 'directionmark':
2549 return $wgContLang->getDirMark();
2550 case 'contentlanguage':
2551 global $wgContLanguageCode;
2552 return $wgContLanguageCode;
2555 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2563 * initialise the magic variables (like CURRENTMONTHNAME)
2567 function initialiseVariables() {
2568 $fname = 'Parser::initialiseVariables';
2569 wfProfileIn( $fname );
2570 $variableIDs = MagicWord
::getVariableIDs();
2572 $this->mVariables
= array();
2573 foreach ( $variableIDs as $id ) {
2574 $mw =& MagicWord
::get( $id );
2575 $mw->addToArray( $this->mVariables
, $id );
2577 wfProfileOut( $fname );
2581 * parse any parentheses in format ((title|part|part))
2582 * and call callbacks to get a replacement text for any found piece
2584 * @param string $text The text to parse
2585 * @param array $callbacks rules in form:
2586 * '{' => array( # opening parentheses
2587 * 'end' => '}', # closing parentheses
2588 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2589 * 3 => callback # replacement callback to call if {{{..}}} is found
2592 * 'min' => 2, # Minimum parenthesis count in cb
2593 * 'max' => 3, # Maximum parenthesis count in cb
2596 function replace_callback ($text, $callbacks) {
2597 wfProfileIn( __METHOD__
);
2598 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2599 $lastOpeningBrace = -1; # last not closed parentheses
2601 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2604 while ( $i < strlen( $text ) ) {
2605 # Find next opening brace, closing brace or pipe
2606 if ( $lastOpeningBrace == -1 ) {
2607 $currentClosing = '';
2608 $search = $validOpeningBraces;
2610 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2611 $search = $validOpeningBraces . '|' . $currentClosing;
2614 $i +
= strcspn( $text, $search, $i );
2615 if ( $i < strlen( $text ) ) {
2616 if ( $text[$i] == '|' ) {
2618 } elseif ( $text[$i] == $currentClosing ) {
2620 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2622 $rule = $callbacks[$text[$i]];
2624 # Some versions of PHP have a strcspn which stops on null characters
2625 # Ignore and continue
2634 if ( $found == 'open' ) {
2635 # found opening brace, let's add it to parentheses stack
2636 $piece = array('brace' => $text[$i],
2637 'braceEnd' => $rule['end'],
2641 # count opening brace characters
2642 $piece['count'] = strspn( $text, $piece['brace'], $i );
2643 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2644 $i +
= $piece['count'];
2646 # we need to add to stack only if opening brace count is enough for one of the rules
2647 if ( $piece['count'] >= $rule['min'] ) {
2648 $lastOpeningBrace ++
;
2649 $openingBraceStack[$lastOpeningBrace] = $piece;
2651 } elseif ( $found == 'close' ) {
2652 # lets check if it is enough characters for closing brace
2653 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2654 $count = strspn( $text, $text[$i], $i, $maxCount );
2656 # check for maximum matching characters (if there are 5 closing
2657 # characters, we will probably need only 3 - depending on the rules)
2659 $matchingCallback = null;
2660 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2661 if ( $count > $cbType['max'] ) {
2662 # The specified maximum exists in the callback array, unless the caller
2664 $matchingCount = $cbType['max'];
2666 # Count is less than the maximum
2667 # Skip any gaps in the callback array to find the true largest match
2668 # Need to use array_key_exists not isset because the callback can be null
2669 $matchingCount = $count;
2670 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2675 if ($matchingCount <= 0) {
2679 $matchingCallback = $cbType['cb'][$matchingCount];
2681 # let's set a title or last part (if '|' was found)
2682 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2683 $openingBraceStack[$lastOpeningBrace]['title'] =
2684 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2685 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2687 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2688 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2689 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2692 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2693 $pieceEnd = $i +
$matchingCount;
2695 if( is_callable( $matchingCallback ) ) {
2697 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2698 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2699 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2700 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2702 # finally we can call a user callback and replace piece of text
2703 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2704 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2705 $i = $pieceStart +
strlen($replaceWith);
2707 # null value for callback means that parentheses should be parsed, but not replaced
2708 $i +
= $matchingCount;
2711 # reset last opening parentheses, but keep it in case there are unused characters
2712 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2713 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2714 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2717 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2718 $openingBraceStack[$lastOpeningBrace--] = null;
2720 if ($matchingCount < $piece['count']) {
2721 $piece['count'] -= $matchingCount;
2722 $piece['startAt'] -= $matchingCount;
2723 $piece['partStart'] = $piece['startAt'];
2724 # do we still qualify for any callback with remaining count?
2725 $currentCbList = $callbacks[$piece['brace']]['cb'];
2726 while ( $piece['count'] ) {
2727 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2728 $lastOpeningBrace++
;
2729 $openingBraceStack[$lastOpeningBrace] = $piece;
2735 } elseif ( $found == 'pipe' ) {
2736 # lets set a title if it is a first separator, or next part otherwise
2737 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2738 $openingBraceStack[$lastOpeningBrace]['title'] =
2739 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2740 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2741 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2743 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2744 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2745 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2751 wfProfileOut( __METHOD__
);
2756 * Replace magic variables, templates, and template arguments
2757 * with the appropriate text. Templates are substituted recursively,
2758 * taking care to avoid infinite loops.
2760 * Note that the substitution depends on value of $mOutputType:
2761 * OT_WIKI: only {{subst:}} templates
2762 * OT_MSG: only magic variables
2763 * OT_HTML: all templates and magic variables
2765 * @param string $tex The text to transform
2766 * @param array $args Key-value pairs representing template parameters to substitute
2767 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2770 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2771 # Prevent too big inclusions
2772 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2776 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2777 wfProfileIn( $fname );
2779 # This function is called recursively. To keep track of arguments we need a stack:
2780 array_push( $this->mArgStack
, $args );
2782 $braceCallbacks = array();
2784 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2786 if ( $this->mOutputType
!= OT_MSG
) {
2787 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2789 if ( $braceCallbacks ) {
2793 'cb' => $braceCallbacks,
2794 'min' => $argsOnly ?
3 : 2,
2795 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2799 'cb' => array(2=>null),
2804 $text = $this->replace_callback ($text, $callbacks);
2806 array_pop( $this->mArgStack
);
2808 wfProfileOut( $fname );
2813 * Replace magic variables
2816 function variableSubstitution( $matches ) {
2818 $fname = 'Parser::variableSubstitution';
2819 $varname = $wgContLang->lc($matches[1]);
2820 wfProfileIn( $fname );
2822 if ( $this->mOutputType
== OT_WIKI
) {
2823 # Do only magic variables prefixed by SUBST
2824 $mwSubst =& MagicWord
::get( 'subst' );
2825 if (!$mwSubst->matchStartAndRemove( $varname ))
2827 # Note that if we don't substitute the variable below,
2828 # we don't remove the {{subst:}} magic word, in case
2829 # it is a template rather than a magic variable.
2831 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2832 $id = $this->mVariables
[$varname];
2833 # Now check if we did really match, case sensitive or not
2834 $mw =& MagicWord
::get( $id );
2835 if ($mw->match($matches[1])) {
2836 $text = $this->getVariableValue( $id );
2837 $this->mOutput
->mContainsOldMagic
= true;
2839 $text = $matches[0];
2842 $text = $matches[0];
2844 wfProfileOut( $fname );
2849 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2850 static function createAssocArgs( $args ) {
2851 $assocArgs = array();
2853 foreach( $args as $arg ) {
2854 $eqpos = strpos( $arg, '=' );
2855 if ( $eqpos === false ) {
2856 $assocArgs[$index++
] = $arg;
2858 $name = trim( substr( $arg, 0, $eqpos ) );
2859 $value = trim( substr( $arg, $eqpos+
1 ) );
2860 if ( $value === false ) {
2863 if ( $name !== false ) {
2864 $assocArgs[$name] = $value;
2873 * Return the text of a template, after recursively
2874 * replacing any variables or templates within the template.
2876 * @param array $piece The parts of the template
2877 * $piece['text']: matched text
2878 * $piece['title']: the title, i.e. the part before the |
2879 * $piece['parts']: the parameter array
2880 * @return string the text of the template
2883 function braceSubstitution( $piece ) {
2884 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2885 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2886 wfProfileIn( $fname );
2887 wfProfileIn( __METHOD__
.'-setup' );
2890 $found = false; # $text has been filled
2891 $nowiki = false; # wiki markup in $text should be escaped
2892 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2893 $noargs = false; # Don't replace triple-brace arguments in $text
2894 $replaceHeadings = false; # Make the edit section links go to the template not the article
2895 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2896 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2897 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2899 # Title object, where $text came from
2905 # $part1 is the bit before the first |, and must contain only title characters
2906 # $args is a list of arguments, starting from index 0, not including $part1
2908 $titleText = $part1 = $piece['title'];
2909 # If the third subpattern matched anything, it will start with |
2911 if (null == $piece['parts']) {
2912 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2913 if ($replaceWith != $piece['text']) {
2914 $text = $replaceWith;
2921 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2922 wfProfileOut( __METHOD__
.'-setup' );
2925 wfProfileIn( __METHOD__
.'-modifiers' );
2927 $mwSubst =& MagicWord
::get( 'subst' );
2928 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2929 # One of two possibilities is true:
2930 # 1) Found SUBST but not in the PST phase
2931 # 2) Didn't find SUBST and in the PST phase
2932 # In either case, return without further processing
2933 $text = $piece['text'];
2940 # MSG, MSGNW and RAW
2943 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2944 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2947 # Remove obsolete MSG:
2948 $mwMsg =& MagicWord
::get( 'msg' );
2949 $mwMsg->matchStartAndRemove( $part1 );
2953 $mwRaw =& MagicWord
::get( 'raw' );
2954 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2955 $forceRawInterwiki = true;
2958 wfProfileOut( __METHOD__
.'-modifiers' );
2960 //save path level before recursing into functions & templates.
2961 $lastPathLevel = $this->mTemplatePath
;
2965 wfProfileIn( __METHOD__
. '-pfunc' );
2967 $colonPos = strpos( $part1, ':' );
2968 if ( $colonPos !== false ) {
2969 # Case sensitive functions
2970 $function = substr( $part1, 0, $colonPos );
2971 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2972 $function = $this->mFunctionSynonyms
[1][$function];
2974 # Case insensitive functions
2975 $function = strtolower( $function );
2976 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2977 $function = $this->mFunctionSynonyms
[0][$function];
2983 $funcArgs = array_map( 'trim', $args );
2984 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2985 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2988 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2992 if ( is_array( $result ) ) {
2993 if ( isset( $result[0] ) ) {
2994 $text = $linestart . $result[0];
2995 unset( $result[0] );
2998 // Extract flags into the local scope
2999 // This allows callers to set flags such as nowiki, noparse, found, etc.
3002 $text = $linestart . $result;
3006 wfProfileOut( __METHOD__
. '-pfunc' );
3009 # Template table test
3011 # Did we encounter this template already? If yes, it is in the cache
3012 # and we need to check for loops.
3013 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3016 # Infinite loop test
3017 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3021 $text = $linestart .
3022 "[[$part1]]<!-- WARNING: template loop detected -->";
3023 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3025 # set $text to cached message.
3026 $text = $linestart . $this->mTemplates
[$piece['title']];
3030 # Load from database
3032 wfProfileIn( __METHOD__
. '-loadtpl' );
3034 # declaring $subpage directly in the function call
3035 # does not work correctly with references and breaks
3036 # {{/subpage}}-style inclusions
3038 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3039 if ($subpage !== '') {
3040 $ns = $this->mTitle
->getNamespace();
3042 $title = Title
::newFromText( $part1, $ns );
3045 if ( !is_null( $title ) ) {
3046 $titleText = $title->getPrefixedText();
3047 # Check for language variants if the template is not found
3048 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3049 $wgContLang->findVariantLink($part1, $title);
3052 if ( !$title->isExternal() ) {
3053 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3054 $text = SpecialPage
::capturePath( $title );
3055 if ( is_string( $text ) ) {
3060 $this->disableCache();
3063 $articleContent = $this->fetchTemplate( $title );
3064 if ( $articleContent !== false ) {
3066 $text = $articleContent;
3067 $replaceHeadings = true;
3071 # If the title is valid but undisplayable, make a link to it
3072 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3073 $text = "[[:$titleText]]";
3076 } elseif ( $title->isTrans() ) {
3077 // Interwiki transclusion
3078 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3079 $text = $this->interwikiTransclude( $title, 'render' );
3083 $text = $this->interwikiTransclude( $title, 'raw' );
3084 $replaceHeadings = true;
3089 # Template cache array insertion
3090 # Use the original $piece['title'] not the mangled $part1, so that
3091 # modifiers such as RAW: produce separate cache entries
3094 // A special page; don't store it in the template cache.
3096 $this->mTemplates
[$piece['title']] = $text;
3098 $text = $linestart . $text;
3101 wfProfileOut( __METHOD__
. '-loadtpl' );
3104 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3105 # Error, oversize inclusion
3106 $text = $linestart .
3107 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3112 # Recursive parsing, escaping and link table handling
3113 # Only for HTML output
3114 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3115 $text = wfEscapeWikiText( $text );
3116 } elseif ( !$this->ot
['msg'] && $found ) {
3118 $assocArgs = array();
3120 # Clean up argument array
3121 $assocArgs = self
::createAssocArgs($args);
3122 # Add a new element to the templace recursion path
3123 $this->mTemplatePath
[$part1] = 1;
3127 # If there are any <onlyinclude> tags, only include them
3128 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3129 $replacer = new OnlyIncludeReplacer
;
3130 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3131 array( &$replacer, 'replace' ), $text );
3132 $text = $replacer->output
;
3134 # Remove <noinclude> sections and <includeonly> tags
3135 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3136 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3138 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3139 # Strip <nowiki>, <pre>, etc.
3140 $text = $this->strip( $text, $this->mStripState
);
3141 if ( $this->ot
['html'] ) {
3142 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3143 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3144 $text = Sanitizer
::removeHTMLcomments( $text );
3147 $text = $this->replaceVariables( $text, $assocArgs );
3149 # If the template begins with a table or block-level
3150 # element, it should be treated as beginning a new line.
3151 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3152 $text = "\n" . $text;
3154 } elseif ( !$noargs ) {
3155 # $noparse and !$noargs
3156 # Just replace the arguments, not any double-brace items
3157 # This is used for rendered interwiki transclusion
3158 $text = $this->replaceVariables( $text, $assocArgs, true );
3161 # Prune lower levels off the recursion check path
3162 $this->mTemplatePath
= $lastPathLevel;
3164 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3165 # Error, oversize inclusion
3166 $text = $linestart .
3167 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3173 wfProfileOut( $fname );
3174 return $piece['text'];
3176 wfProfileIn( __METHOD__
. '-placeholders' );
3178 # Replace raw HTML by a placeholder
3179 # Add a blank line preceding, to prevent it from mucking up
3180 # immediately preceding headings
3181 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3183 # replace ==section headers==
3184 # XXX this needs to go away once we have a better parser.
3185 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3186 if( !is_null( $title ) )
3187 $encodedname = base64_encode($title->getPrefixedDBkey());
3189 $encodedname = base64_encode("");
3190 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3191 PREG_SPLIT_DELIM_CAPTURE
);
3193 $nsec = $headingOffset;
3194 for( $i = 0; $i < count($m); $i +
= 2 ) {
3196 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3198 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3203 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3204 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3205 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3211 wfProfileOut( __METHOD__
. '-placeholders' );
3214 # Prune lower levels off the recursion check path
3215 $this->mTemplatePath
= $lastPathLevel;
3218 wfProfileOut( $fname );
3219 return $piece['text'];
3221 wfProfileOut( $fname );
3227 * Fetch the unparsed text of a template and register a reference to it.
3229 function fetchTemplate( $title ) {
3231 // Loop to fetch the article, with up to 1 redirect
3232 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3233 $rev = Revision
::newFromTitle( $title );
3234 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3238 $text = $rev->getText();
3239 if ( $text === false ) {
3243 $title = Title
::newFromRedirect( $text );
3249 * Transclude an interwiki link.
3251 function interwikiTransclude( $title, $action ) {
3252 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3254 if (!$wgEnableScaryTranscluding)
3255 return wfMsg('scarytranscludedisabled');
3257 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3258 // But we'll handle it generally anyway
3259 if ( $title->getNamespace() ) {
3260 // Use the canonical namespace, which should work anywhere
3261 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3263 $articleName = $title->getDBkey();
3266 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3267 $url .= "?action=$action";
3268 if (strlen($url) > 255)
3269 return wfMsg('scarytranscludetoolong');
3270 return $this->fetchScaryTemplateMaybeFromCache($url);
3273 function fetchScaryTemplateMaybeFromCache($url) {
3274 global $wgTranscludeCacheExpiry;
3275 $dbr =& wfGetDB(DB_SLAVE
);
3276 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3277 array('tc_url' => $url));
3279 $time = $obj->tc_time
;
3280 $text = $obj->tc_contents
;
3281 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3286 $text = Http
::get($url);
3288 return wfMsg('scarytranscludefailed', $url);
3290 $dbw =& wfGetDB(DB_MASTER
);
3291 $dbw->replace('transcache', array('tc_url'), array(
3293 'tc_time' => time(),
3294 'tc_contents' => $text));
3300 * Triple brace replacement -- used for template arguments
3303 function argSubstitution( $matches ) {
3304 $arg = trim( $matches['title'] );
3305 $text = $matches['text'];
3306 $inputArgs = end( $this->mArgStack
);
3308 if ( array_key_exists( $arg, $inputArgs ) ) {
3309 $text = $inputArgs[$arg];
3310 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3311 null != $matches['parts'] && count($matches['parts']) > 0) {
3312 $text = $matches['parts'][0];
3314 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3315 $text = $matches['text'] .
3316 '<!-- WARNING: argument omitted, expansion size too large -->';
3323 * Increment an include size counter
3325 * @param string $type The type of expansion
3326 * @param integer $size The size of the text
3327 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3329 function incrementIncludeSize( $type, $size ) {
3330 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3333 $this->mIncludeSizes
[$type] +
= $size;
3339 * Detect __NOGALLERY__ magic word and set a placeholder
3341 function stripNoGallery( &$text ) {
3342 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3344 $mw = MagicWord
::get( 'nogallery' );
3345 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3349 * Detect __TOC__ magic word and set a placeholder
3351 function stripToc( $text ) {
3352 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3354 $mw = MagicWord
::get( 'notoc' );
3355 if( $mw->matchAndRemove( $text ) ) {
3356 $this->mShowToc
= false;
3359 $mw = MagicWord
::get( 'toc' );
3360 if( $mw->match( $text ) ) {
3361 $this->mShowToc
= true;
3362 $this->mForceTocPosition
= true;
3364 // Set a placeholder. At the end we'll fill it in with the TOC.
3365 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3367 // Only keep the first one.
3368 $text = $mw->replace( '', $text );
3374 * This function accomplishes several tasks:
3375 * 1) Auto-number headings if that option is enabled
3376 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3377 * 3) Add a Table of contents on the top for users who have enabled the option
3378 * 4) Auto-anchor headings
3380 * It loops through all headlines, collects the necessary data, then splits up the
3381 * string and re-inserts the newly formatted headlines.
3383 * @param string $text
3384 * @param boolean $isMain
3387 function formatHeadings( $text, $isMain=true ) {
3388 global $wgMaxTocLevel, $wgContLang;
3390 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3391 if( !$this->mTitle
->userCanEdit() ) {
3394 $showEditLink = $this->mOptions
->getEditSection();
3397 # Inhibit editsection links if requested in the page
3398 $esw =& MagicWord
::get( 'noeditsection' );
3399 if( $esw->matchAndRemove( $text ) ) {
3403 # Get all headlines for numbering them and adding funky stuff like [edit]
3404 # links - this is for later, but we need the number of headlines right now
3406 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3408 # if there are fewer than 4 headlines in the article, do not show TOC
3409 # unless it's been explicitly enabled.
3410 $enoughToc = $this->mShowToc
&&
3411 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3413 # Allow user to stipulate that a page should have a "new section"
3414 # link added via __NEWSECTIONLINK__
3415 $mw =& MagicWord
::get( 'newsectionlink' );
3416 if( $mw->matchAndRemove( $text ) )
3417 $this->mOutput
->setNewSection( true );
3419 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3420 # override above conditions and always show TOC above first header
3421 $mw =& MagicWord
::get( 'forcetoc' );
3422 if ($mw->matchAndRemove( $text ) ) {
3423 $this->mShowToc
= true;
3427 # Never ever show TOC if no headers
3428 if( $numMatches < 1 ) {
3432 # We need this to perform operations on the HTML
3433 $sk =& $this->mOptions
->getSkin();
3437 $sectionCount = 0; # headlineCount excluding template sections
3439 # Ugh .. the TOC should have neat indentation levels which can be
3440 # passed to the skin functions. These are determined here
3444 $sublevelCount = array();
3445 $levelCount = array();
3452 foreach( $matches[3] as $headline ) {
3454 $templatetitle = '';
3455 $templatesection = 0;
3458 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3460 $templatetitle = base64_decode($mat[1]);
3461 $templatesection = 1 +
(int)base64_decode($mat[2]);
3462 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3466 $prevlevel = $level;
3467 $prevtoclevel = $toclevel;
3469 $level = $matches[1][$headlineCount];
3471 if( $doNumberHeadings ||
$enoughToc ) {
3473 if ( $level > $prevlevel ) {
3474 # Increase TOC level
3476 $sublevelCount[$toclevel] = 0;
3477 if( $toclevel<$wgMaxTocLevel ) {
3478 $toc .= $sk->tocIndent();
3481 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3482 # Decrease TOC level, find level to jump to
3484 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3485 # Can only go down to level 1
3488 for ($i = $toclevel; $i > 0; $i--) {
3489 if ( $levelCount[$i] == $level ) {
3490 # Found last matching level
3494 elseif ( $levelCount[$i] < $level ) {
3495 # Found first matching level below current level
3501 if( $toclevel<$wgMaxTocLevel ) {
3502 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3506 # No change in level, end TOC line
3507 if( $toclevel<$wgMaxTocLevel ) {
3508 $toc .= $sk->tocLineEnd();
3512 $levelCount[$toclevel] = $level;
3514 # count number of headlines for each level
3515 @$sublevelCount[$toclevel]++
;
3517 for( $i = 1; $i <= $toclevel; $i++
) {
3518 if( !empty( $sublevelCount[$i] ) ) {
3522 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3528 # The canonized header is a version of the header text safe to use for links
3529 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3530 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3532 # Remove link placeholders by the link text.
3533 # <!--LINK number-->
3535 # link text with suffix
3536 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3537 "\$this->mLinkHolders['texts'][\$1]",
3538 $canonized_headline );
3539 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3540 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3541 $canonized_headline );
3544 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3545 $tocline = trim( $canonized_headline );
3546 # Save headline for section edit hint before it's escaped
3547 $headline_hint = trim( $canonized_headline );
3548 $canonized_headline = Sanitizer
::escapeId( $tocline );
3549 $refers[$headlineCount] = $canonized_headline;
3551 # count how many in assoc. array so we can track dupes in anchors
3552 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3553 $refcount[$headlineCount]=$refers[$canonized_headline];
3555 # Don't number the heading if it is the only one (looks silly)
3556 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3557 # the two are different if the line contains a link
3558 $headline=$numbering . ' ' . $headline;
3561 # Create the anchor for linking from the TOC to the section
3562 $anchor = $canonized_headline;
3563 if($refcount[$headlineCount] > 1 ) {
3564 $anchor .= '_' . $refcount[$headlineCount];
3566 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3567 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3569 # give headline the correct <h#> tag
3570 $head[$headlineCount] = "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3572 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3573 if ( empty( $head[$headlineCount] ) ) {
3574 $head[$headlineCount] = '';
3577 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3579 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3581 // Yes, the headline logically goes before the edit section. Why isn't it there
3582 // in source? Ask the CSS people. The float gets screwed up if you do that.
3583 // This might be moved to before the editsection at some point so that it will
3584 // display a bit more prettily without CSS, so please don't rely on the order.
3585 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3593 if( $toclevel<$wgMaxTocLevel ) {
3594 $toc .= $sk->tocUnindent( $toclevel - 1 );
3596 $toc = $sk->tocList( $toc );
3599 # split up and insert constructed headlines
3601 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3604 foreach( $blocks as $block ) {
3605 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3606 # This is the [edit] link that appears for the top block of text when
3607 # section editing is enabled
3609 # Disabled because it broke block formatting
3610 # For example, a bullet point in the top line
3611 # $full .= $sk->editSectionLink(0);
3614 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3615 # Top anchor now in skin
3619 if( !empty( $head[$i] ) ) {
3624 if( $this->mForceTocPosition
) {
3625 return str_replace( '<!--MWTOC-->', $toc, $full );
3632 * Transform wiki markup when saving a page by doing \r\n -> \n
3633 * conversion, substitting signatures, {{subst:}} templates, etc.
3635 * @param string $text the text to transform
3636 * @param Title &$title the Title object for the current article
3637 * @param User &$user the User object describing the current user
3638 * @param ParserOptions $options parsing options
3639 * @param bool $clearState whether to clear the parser state first
3640 * @return string the altered wiki markup
3643 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3644 $this->mOptions
= $options;
3645 $this->mTitle
=& $title;
3646 $this->setOutputType( OT_WIKI
);
3648 if ( $clearState ) {
3649 $this->clearState();
3652 $stripState = new StripState
;
3656 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3657 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3658 $text = $this->pstPass2( $text, $stripState, $user );
3659 $text = $stripState->unstripBoth( $text );
3664 * Pre-save transform helper function
3667 function pstPass2( $text, &$stripState, $user ) {
3668 global $wgContLang, $wgLocaltimezone;
3670 /* Note: This is the timestamp saved as hardcoded wikitext to
3671 * the database, we use $wgContLang here in order to give
3672 * everyone the same signature and use the default one rather
3673 * than the one selected in each user's preferences.
3675 if ( isset( $wgLocaltimezone ) ) {
3676 $oldtz = getenv( 'TZ' );
3677 putenv( 'TZ='.$wgLocaltimezone );
3679 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3680 ' (' . date( 'T' ) . ')';
3681 if ( isset( $wgLocaltimezone ) ) {
3682 putenv( 'TZ='.$oldtz );
3685 # Variable replacement
3686 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3687 $text = $this->replaceVariables( $text );
3689 # Strip out <nowiki> etc. added via replaceVariables
3690 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3693 $sigText = $this->getUserSig( $user );
3694 $text = strtr( $text, array(
3696 '~~~~' => "$sigText $d",
3700 # Context links: [[|name]] and [[name (context)|]]
3702 global $wgLegalTitleChars;
3703 $tc = "[$wgLegalTitleChars]";
3704 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3706 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3707 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3708 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3710 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3711 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3712 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3714 $t = $this->mTitle
->getText();
3716 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3717 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3718 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3719 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3721 # if there's no context, don't bother duplicating the title
3722 $text = preg_replace( $p2, '[[\\1]]', $text );
3725 # Trim trailing whitespace
3726 # __END__ tag allows for trailing
3727 # whitespace to be deliberately included
3728 $text = rtrim( $text );
3729 $mw =& MagicWord
::get( 'end' );
3730 $mw->matchAndRemove( $text );
3736 * Fetch the user's signature text, if any, and normalize to
3737 * validated, ready-to-insert wikitext.
3743 function getUserSig( &$user ) {
3744 $username = $user->getName();
3745 $nickname = $user->getOption( 'nickname' );
3746 $nickname = $nickname === '' ?
$username : $nickname;
3748 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3749 # Sig. might contain markup; validate this
3750 if( $this->validateSig( $nickname ) !== false ) {
3751 # Validated; clean up (if needed) and return it
3752 return $this->cleanSig( $nickname, true );
3754 # Failed to validate; fall back to the default
3755 $nickname = $username;
3756 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3760 // Make sure nickname doesnt get a sig in a sig
3761 $nickname = $this->cleanSigInSig( $nickname );
3763 # If we're still here, make it a link to the user page
3764 $userpage = $user->getUserPage();
3765 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3769 * Check that the user's signature contains no bad XML
3771 * @param string $text
3772 * @return mixed An expanded string, or false if invalid.
3774 function validateSig( $text ) {
3775 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3779 * Clean up signature text
3781 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3782 * 2) Substitute all transclusions
3784 * @param string $text
3785 * @param $parsing Whether we're cleaning (preferences save) or parsing
3786 * @return string Signature text
3788 function cleanSig( $text, $parsing = false ) {
3790 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3792 $substWord = MagicWord
::get( 'subst' );
3793 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3794 $substText = '{{' . $substWord->getSynonym( 0 );
3796 $text = preg_replace( $substRegex, $substText, $text );
3797 $text = $this->cleanSigInSig( $text );
3798 $text = $this->replaceVariables( $text );
3800 $this->clearState();
3805 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3806 * @param string $text
3807 * @return string Signature text with /~{3,5}/ removed
3809 function cleanSigInSig( $text ) {
3810 $text = preg_replace( '/~{3,5}/', '', $text );
3815 * Set up some variables which are usually set up in parse()
3816 * so that an external function can call some class members with confidence
3819 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3820 $this->mTitle
=& $title;
3821 $this->mOptions
= $options;
3822 $this->setOutputType( $outputType );
3823 if ( $clearState ) {
3824 $this->clearState();
3829 * Transform a MediaWiki message by replacing magic variables.
3831 * @param string $text the text to transform
3832 * @param ParserOptions $options options
3833 * @return string the text with variables substituted
3836 function transformMsg( $text, $options ) {
3838 static $executing = false;
3840 $fname = "Parser::transformMsg";
3842 # Guard against infinite recursion
3848 wfProfileIn($fname);
3851 $this->mTitle
= $wgTitle;
3853 $this->mTitle
= Title
::newFromText('msg');
3855 $this->mOptions
= $options;
3856 $this->setOutputType( OT_MSG
);
3857 $this->clearState();
3858 $text = $this->replaceVariables( $text );
3861 wfProfileOut($fname);
3866 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3867 * The callback should have the following form:
3868 * function myParserHook( $text, $params, &$parser ) { ... }
3870 * Transform and return $text. Use $parser for any required context, e.g. use
3871 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3875 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3876 * @param mixed $callback The callback function (and object) to use for the tag
3878 * @return The old value of the mTagHooks array associated with the hook
3880 function setHook( $tag, $callback ) {
3881 $tag = strtolower( $tag );
3882 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3883 $this->mTagHooks
[$tag] = $callback;
3889 * Create a function, e.g. {{sum:1|2|3}}
3890 * The callback function should have the form:
3891 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3893 * The callback may either return the text result of the function, or an array with the text
3894 * in element 0, and a number of flags in the other elements. The names of the flags are
3895 * specified in the keys. Valid flags are:
3896 * found The text returned is valid, stop processing the template. This
3898 * nowiki Wiki markup in the return value should be escaped
3899 * noparse Unsafe HTML tags should not be stripped, etc.
3900 * noargs Don't replace triple-brace arguments in the return value
3901 * isHTML The returned text is HTML, armour it against wikitext transformation
3905 * @param string $id The magic word ID
3906 * @param mixed $callback The callback function (and object) to use
3907 * @param integer $flags a combination of the following flags:
3908 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3910 * @return The old callback function for this name, if any
3912 function setFunctionHook( $id, $callback, $flags = 0 ) {
3913 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3914 $this->mFunctionHooks
[$id] = $callback;
3916 # Add to function cache
3917 $mw = MagicWord
::get( $id );
3919 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3921 $synonyms = $mw->getSynonyms();
3922 $sensitive = intval( $mw->isCaseSensitive() );
3924 foreach ( $synonyms as $syn ) {
3926 if ( !$sensitive ) {
3927 $syn = strtolower( $syn );
3930 if ( !( $flags & SFH_NO_HASH
) ) {
3933 # Remove trailing colon
3934 if ( substr( $syn, -1, 1 ) == ':' ) {
3935 $syn = substr( $syn, 0, -1 );
3937 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3943 * Get all registered function hook identifiers
3947 function getFunctionHooks() {
3948 return array_keys( $this->mFunctionHooks
);
3952 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3953 * Placeholders created in Skin::makeLinkObj()
3954 * Returns an array of links found, indexed by PDBK:
3958 * $options is a bit field, RLH_FOR_UPDATE to select for update
3960 function replaceLinkHolders( &$text, $options = 0 ) {
3964 $fname = 'Parser::replaceLinkHolders';
3965 wfProfileIn( $fname );
3969 $sk =& $this->mOptions
->getSkin();
3970 $linkCache =& LinkCache
::singleton();
3972 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3973 wfProfileIn( $fname.'-check' );
3974 $dbr =& wfGetDB( DB_SLAVE
);
3975 $page = $dbr->tableName( 'page' );
3976 $threshold = $wgUser->getOption('stubthreshold');
3979 asort( $this->mLinkHolders
['namespaces'] );
3984 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3986 $title = $this->mLinkHolders
['titles'][$key];
3988 # Skip invalid entries.
3989 # Result will be ugly, but prevents crash.
3990 if ( is_null( $title ) ) {
3993 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3995 # Check if it's a static known link, e.g. interwiki
3996 if ( $title->isAlwaysKnown() ) {
3997 $colours[$pdbk] = 1;
3998 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3999 $colours[$pdbk] = 1;
4000 $this->mOutput
->addLink( $title, $id );
4001 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4002 $colours[$pdbk] = 0;
4004 # Not in the link cache, add it to the query
4005 if ( !isset( $current ) ) {
4007 $query = "SELECT page_id, page_namespace, page_title";
4008 if ( $threshold > 0 ) {
4009 $query .= ', page_len, page_is_redirect';
4011 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4012 } elseif ( $current != $ns ) {
4014 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4019 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4024 if ( $options & RLH_FOR_UPDATE
) {
4025 $query .= ' FOR UPDATE';
4028 $res = $dbr->query( $query, $fname );
4030 # Fetch data and form into an associative array
4031 # non-existent = broken
4034 while ( $s = $dbr->fetchObject($res) ) {
4035 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4036 $pdbk = $title->getPrefixedDBkey();
4037 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4038 $this->mOutput
->addLink( $title, $s->page_id
);
4040 if ( $threshold > 0 ) {
4041 $size = $s->page_len
;
4042 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4043 $colours[$pdbk] = 1;
4045 $colours[$pdbk] = 2;
4048 $colours[$pdbk] = 1;
4052 wfProfileOut( $fname.'-check' );
4054 # Do a second query for different language variants of links and categories
4055 if($wgContLang->hasVariants()){
4056 $linkBatch = new LinkBatch();
4057 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4058 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4059 $varCategories = array(); // category replacements oldDBkey => newDBkey
4061 $categories = $this->mOutput
->getCategoryLinks();
4063 // Add variants of links to link batch
4064 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4065 $title = $this->mLinkHolders
['titles'][$key];
4066 if ( is_null( $title ) )
4069 $pdbk = $title->getPrefixedDBkey();
4070 $titleText = $title->getText();
4072 // generate all variants of the link title text
4073 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4075 // if link was not found (in first query), add all variants to query
4076 if ( !isset($colours[$pdbk]) ){
4077 foreach($allTextVariants as $textVariant){
4078 if($textVariant != $titleText){
4079 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4080 if(is_null($variantTitle)) continue;
4081 $linkBatch->addObj( $variantTitle );
4082 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4088 // process categories, check if a category exists in some variant
4089 foreach( $categories as $category){
4090 $variants = $wgContLang->convertLinkToAllVariants($category);
4091 foreach($variants as $variant){
4092 if($variant != $category){
4093 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4094 if(is_null($variantTitle)) continue;
4095 $linkBatch->addObj( $variantTitle );
4096 $categoryMap[$variant] = $category;
4102 if(!$linkBatch->isEmpty()){
4104 $titleClause = $linkBatch->constructSet('page', $dbr);
4106 $variantQuery = "SELECT page_id, page_namespace, page_title";
4107 if ( $threshold > 0 ) {
4108 $variantQuery .= ', page_len, page_is_redirect';
4111 $variantQuery .= " FROM $page WHERE $titleClause";
4112 if ( $options & RLH_FOR_UPDATE
) {
4113 $variantQuery .= ' FOR UPDATE';
4116 $varRes = $dbr->query( $variantQuery, $fname );
4118 // for each found variants, figure out link holders and replace
4119 while ( $s = $dbr->fetchObject($varRes) ) {
4121 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4122 $varPdbk = $variantTitle->getPrefixedDBkey();
4123 $vardbk = $variantTitle->getDBkey();
4125 $holderKeys = array();
4126 if(isset($variantMap[$varPdbk])){
4127 $holderKeys = $variantMap[$varPdbk];
4128 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4129 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4132 // loop over link holders
4133 foreach($holderKeys as $key){
4134 $title = $this->mLinkHolders
['titles'][$key];
4135 if ( is_null( $title ) ) continue;
4137 $pdbk = $title->getPrefixedDBkey();
4139 if(!isset($colours[$pdbk])){
4140 // found link in some of the variants, replace the link holder data
4141 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4142 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4144 // set pdbk and colour
4145 $pdbks[$key] = $varPdbk;
4146 if ( $threshold > 0 ) {
4147 $size = $s->page_len
;
4148 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4149 $colours[$varPdbk] = 1;
4151 $colours[$varPdbk] = 2;
4155 $colours[$varPdbk] = 1;
4160 // check if the object is a variant of a category
4161 if(isset($categoryMap[$vardbk])){
4162 $oldkey = $categoryMap[$vardbk];
4163 if($oldkey != $vardbk)
4164 $varCategories[$oldkey]=$vardbk;
4168 // rebuild the categories in original order (if there are replacements)
4169 if(count($varCategories)>0){
4171 $originalCats = $this->mOutput
->getCategories();
4172 foreach($originalCats as $cat => $sortkey){
4173 // make the replacement
4174 if( array_key_exists($cat,$varCategories) )
4175 $newCats[$varCategories[$cat]] = $sortkey;
4176 else $newCats[$cat] = $sortkey;
4178 $this->mOutput
->setCategoryLinks($newCats);
4183 # Construct search and replace arrays
4184 wfProfileIn( $fname.'-construct' );
4185 $replacePairs = array();
4186 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4187 $pdbk = $pdbks[$key];
4188 $searchkey = "<!--LINK $key-->";
4189 $title = $this->mLinkHolders
['titles'][$key];
4190 if ( empty( $colours[$pdbk] ) ) {
4191 $linkCache->addBadLinkObj( $title );
4192 $colours[$pdbk] = 0;
4193 $this->mOutput
->addLink( $title, 0 );
4194 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4195 $this->mLinkHolders
['texts'][$key],
4196 $this->mLinkHolders
['queries'][$key] );
4197 } elseif ( $colours[$pdbk] == 1 ) {
4198 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4199 $this->mLinkHolders
['texts'][$key],
4200 $this->mLinkHolders
['queries'][$key] );
4201 } elseif ( $colours[$pdbk] == 2 ) {
4202 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4203 $this->mLinkHolders
['texts'][$key],
4204 $this->mLinkHolders
['queries'][$key] );
4207 $replacer = new HashtableReplacer( $replacePairs, 1 );
4208 wfProfileOut( $fname.'-construct' );
4211 wfProfileIn( $fname.'-replace' );
4212 $text = preg_replace_callback(
4213 '/(<!--LINK .*?-->)/',
4217 wfProfileOut( $fname.'-replace' );
4220 # Now process interwiki link holders
4221 # This is quite a bit simpler than internal links
4222 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4223 wfProfileIn( $fname.'-interwiki' );
4224 # Make interwiki link HTML
4225 $replacePairs = array();
4226 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4227 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4228 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4230 $replacer = new HashtableReplacer( $replacePairs, 1 );
4232 $text = preg_replace_callback(
4233 '/<!--IWLINK (.*?)-->/',
4236 wfProfileOut( $fname.'-interwiki' );
4239 wfProfileOut( $fname );
4244 * Replace <!--LINK--> link placeholders with plain text of links
4245 * (not HTML-formatted).
4246 * @param string $text
4249 function replaceLinkHoldersText( $text ) {
4250 $fname = 'Parser::replaceLinkHoldersText';
4251 wfProfileIn( $fname );
4253 $text = preg_replace_callback(
4254 '/<!--(LINK|IWLINK) (.*?)-->/',
4255 array( &$this, 'replaceLinkHoldersTextCallback' ),
4258 wfProfileOut( $fname );
4263 * @param array $matches
4267 function replaceLinkHoldersTextCallback( $matches ) {
4268 $type = $matches[1];
4270 if( $type == 'LINK' ) {
4271 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4272 return $this->mLinkHolders
['texts'][$key];
4274 } elseif( $type == 'IWLINK' ) {
4275 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4276 return $this->mInterwikiLinkHolders
['texts'][$key];
4283 * Tag hook handler for 'pre'.
4285 function renderPreTag( $text, $attribs ) {
4286 // Backwards-compatibility hack
4287 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4289 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4290 return wfOpenElement( 'pre', $attribs ) .
4291 Xml
::escapeTagsOnly( $content ) .
4296 * Renders an image gallery from a text with one line per image.
4297 * text labels may be given by using |-style alternative text. E.g.
4298 * Image:one.jpg|The number "1"
4299 * Image:tree.jpg|A tree
4300 * given as text will return the HTML of a gallery with two images,
4301 * labeled 'The number "1"' and
4304 function renderImageGallery( $text, $params ) {
4305 $ig = new ImageGallery();
4306 $ig->setShowBytes( false );
4307 $ig->setShowFilename( false );
4309 $ig->useSkin( $this->mOptions
->getSkin() );
4311 if( isset( $params['caption'] ) )
4312 $ig->setCaption( $params['caption'] );
4314 $lines = explode( "\n", $text );
4315 foreach ( $lines as $line ) {
4316 # match lines like these:
4317 # Image:someimage.jpg|This is some image
4319 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4321 if ( count( $matches ) == 0 ) {
4324 $tp = Title
::newFromText( $matches[1] );
4326 if( is_null( $nt ) ) {
4327 # Bogus title. Ignore these so we don't bomb out later.
4330 if ( isset( $matches[3] ) ) {
4331 $label = $matches[3];
4336 $pout = $this->parse( $label,
4339 false, // Strip whitespace...?
4340 false // Don't clear state!
4342 $html = $pout->getText();
4344 $ig->add( new Image( $nt ), $html );
4346 # Only add real images (bug #5586)
4347 if ( $nt->getNamespace() == NS_IMAGE
) {
4348 $this->mOutput
->addImage( $nt->getDBkey() );
4351 return $ig->toHTML();
4355 * Parse image options text and use it to make an image
4357 function makeImage( $nt, $options ) {
4358 global $wgUseImageResize, $wgDjvuRenderer;
4362 # Check if the options text is of the form "options|alt text"
4364 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4365 # * left no resizing, just left align. label is used for alt= only
4366 # * right same, but right aligned
4367 # * none same, but not aligned
4368 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4369 # * center center the image
4370 # * framed Keep original image size, no magnify-button.
4372 $part = explode( '|', $options);
4374 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4375 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4376 $mwLeft =& MagicWord
::get( 'img_left' );
4377 $mwRight =& MagicWord
::get( 'img_right' );
4378 $mwNone =& MagicWord
::get( 'img_none' );
4379 $mwWidth =& MagicWord
::get( 'img_width' );
4380 $mwCenter =& MagicWord
::get( 'img_center' );
4381 $mwFramed =& MagicWord
::get( 'img_framed' );
4382 $mwPage =& MagicWord
::get( 'img_page' );
4385 $width = $height = $framed = $thumb = false;
4387 $manual_thumb = '' ;
4389 foreach( $part as $val ) {
4390 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4392 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4393 # use manually specified thumbnail
4395 $manual_thumb = $match;
4396 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4397 # remember to set an alignment, don't render immediately
4399 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4400 # remember to set an alignment, don't render immediately
4402 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4403 # remember to set an alignment, don't render immediately
4405 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4406 # remember to set an alignment, don't render immediately
4408 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4409 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4410 # Select a page in a multipage document
4412 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4413 wfDebug( "img_width match: $match\n" );
4414 # $match is the image width in pixels
4416 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4417 $width = intval( $m[1] );
4418 $height = intval( $m[2] );
4420 $width = intval($match);
4422 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4428 # Strip bad stuff out of the alt text
4429 $alt = $this->replaceLinkHoldersText( $caption );
4431 # make sure there are no placeholders in thumbnail attributes
4432 # that are later expanded to html- so expand them now and
4434 $alt = $this->mStripState
->unstripBoth( $alt );
4435 $alt = Sanitizer
::stripAllTags( $alt );
4437 # Linker does the rest
4438 $sk =& $this->mOptions
->getSkin();
4439 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4443 * Set a flag in the output object indicating that the content is dynamic and
4444 * shouldn't be cached.
4446 function disableCache() {
4447 wfDebug( "Parser output marked as uncacheable.\n" );
4448 $this->mOutput
->mCacheTime
= -1;
4452 * Callback from the Sanitizer for expanding items found in HTML attribute
4453 * values, so they can be safely tested and escaped.
4454 * @param string $text
4455 * @param array $args
4459 function attributeStripCallback( &$text, $args ) {
4460 $text = $this->replaceVariables( $text, $args );
4461 $text = $this->mStripState
->unstripBoth( $text );
4470 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4471 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4472 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4478 function getTags() { return array_keys( $this->mTagHooks
); }
4483 * Break wikitext input into sections, and either pull or replace
4484 * some particular section's text.
4486 * External callers should use the getSection and replaceSection methods.
4488 * @param $text Page wikitext
4489 * @param $section Numbered section. 0 pulls the text before the first
4490 * heading; other numbers will pull the given section
4491 * along with its lower-level subsections.
4492 * @param $mode One of "get" or "replace"
4493 * @param $newtext Replacement text for section data.
4494 * @return string for "get", the extracted section text.
4495 * for "replace", the whole page with the section replaced.
4497 private function extractSections( $text, $section, $mode, $newtext='' ) {
4498 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4499 # comments to be stripped as well)
4500 $stripState = new StripState
;
4502 $oldOutputType = $this->mOutputType
;
4503 $oldOptions = $this->mOptions
;
4504 $this->mOptions
= new ParserOptions();
4505 $this->setOutputType( OT_WIKI
);
4507 $striptext = $this->strip( $text, $stripState, true );
4509 $this->setOutputType( $oldOutputType );
4510 $this->mOptions
= $oldOptions;
4512 # now that we can be sure that no pseudo-sections are in the source,
4513 # split it up by section
4514 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4515 $comment = "(?:$uniq-!--.*?QINU)";
4520 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4522 (=+) # Should this be limited to 6?
4523 .+? # Section title...
4524 \\2 # Ending = count must match start
4531 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4538 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4539 (=+) # Should this be limited to 6?
4540 .+? # Section title...
4541 \\2 # Ending = count must match start
4542 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4551 PREG_SPLIT_DELIM_CAPTURE
);
4553 if( $mode == "get" ) {
4554 if( $section == 0 ) {
4555 // "Section 0" returns the content before any other section.
4560 } elseif( $mode == "replace" ) {
4561 if( $section == 0 ) {
4562 $rv = $newtext . "\n\n";
4571 for( $index = 1; $index < count( $secs ); ) {
4572 $headerLine = $secs[$index++
];
4573 if( $secs[$index] ) {
4575 $headerLevel = strlen( $secs[$index++
] );
4579 $headerLevel = intval( $secs[$index++
] );
4581 $content = $secs[$index++
];
4584 if( $mode == "get" ) {
4585 if( $count == $section ) {
4586 $rv = $headerLine . $content;
4587 $sectionLevel = $headerLevel;
4588 } elseif( $count > $section ) {
4589 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4590 $rv .= $headerLine . $content;
4592 // Broke out to a higher-level section
4596 } elseif( $mode == "replace" ) {
4597 if( $count < $section ) {
4598 $rv .= $headerLine . $content;
4599 } elseif( $count == $section ) {
4600 $rv .= $newtext . "\n\n";
4601 $sectionLevel = $headerLevel;
4602 } elseif( $count > $section ) {
4603 if( $headerLevel <= $sectionLevel ) {
4604 // Passed the section's sub-parts.
4608 $rv .= $headerLine . $content;
4613 # reinsert stripped tags
4614 $rv = trim( $stripState->unstripBoth( $rv ) );
4619 * This function returns the text of a section, specified by a number ($section).
4620 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4621 * the first section before any such heading (section 0).
4623 * If a section contains subsections, these are also returned.
4625 * @param $text String: text to look in
4626 * @param $section Integer: section number
4627 * @return string text of the requested section
4629 function getSection( $text, $section ) {
4630 return $this->extractSections( $text, $section, "get" );
4633 function replaceSection( $oldtext, $section, $text ) {
4634 return $this->extractSections( $oldtext, $section, "replace", $text );
4638 * Get the timestamp associated with the current revision, adjusted for
4639 * the default server-local timestamp
4641 function getRevisionTimestamp() {
4642 if ( is_null( $this->mRevisionTimestamp
) ) {
4643 wfProfileIn( __METHOD__
);
4645 $dbr =& wfGetDB( DB_SLAVE
);
4646 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4647 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4649 // Normalize timestamp to internal MW format for timezone processing.
4650 // This has the added side-effect of replacing a null value with
4651 // the current time, which gives us more sensible behavior for
4653 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4655 // The cryptic '' timezone parameter tells to use the site-default
4656 // timezone offset instead of the user settings.
4658 // Since this value will be saved into the parser cache, served
4659 // to other users, and potentially even used inside links and such,
4660 // it needs to be consistent for all visitors.
4661 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4663 wfProfileOut( __METHOD__
);
4665 return $this->mRevisionTimestamp
;
4671 * @package MediaWiki
4675 var $mText, # The output text
4676 $mLanguageLinks, # List of the full text of language links, in the order they appear
4677 $mCategories, # Map of category names to sort keys
4678 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4679 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4680 $mVersion, # Compatibility check
4681 $mTitleText, # title text of the chosen language variant
4682 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4683 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4684 $mImages, # DB keys of the images used, in the array key only
4685 $mExternalLinks, # External link URLs, in the key only
4686 $mHTMLtitle, # Display HTML title
4687 $mSubtitle, # Additional subtitle
4688 $mNewSection, # Show a new section link?
4689 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4691 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4692 $containsOldMagic = false, $titletext = '' )
4694 $this->mText
= $text;
4695 $this->mLanguageLinks
= $languageLinks;
4696 $this->mCategories
= $categoryLinks;
4697 $this->mContainsOldMagic
= $containsOldMagic;
4698 $this->mCacheTime
= '';
4699 $this->mVersion
= MW_PARSER_VERSION
;
4700 $this->mTitleText
= $titletext;
4701 $this->mLinks
= array();
4702 $this->mTemplates
= array();
4703 $this->mImages
= array();
4704 $this->mExternalLinks
= array();
4705 $this->mHTMLtitle
= "" ;
4706 $this->mSubtitle
= "" ;
4707 $this->mNewSection
= false;
4708 $this->mNoGallery
= false;
4711 function getText() { return $this->mText
; }
4712 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4713 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4714 function &getCategories() { return $this->mCategories
; }
4715 function getCacheTime() { return $this->mCacheTime
; }
4716 function getTitleText() { return $this->mTitleText
; }
4717 function &getLinks() { return $this->mLinks
; }
4718 function &getTemplates() { return $this->mTemplates
; }
4719 function &getImages() { return $this->mImages
; }
4720 function &getExternalLinks() { return $this->mExternalLinks
; }
4721 function getNoGallery() { return $this->mNoGallery
; }
4722 function getSubtitle() { return $this->mSubtitle
; }
4724 function containsOldMagic() { return $this->mContainsOldMagic
; }
4725 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4726 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4727 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4728 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4729 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4730 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4731 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4733 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4734 function addImage( $name ) { $this->mImages
[$name] = 1; }
4735 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4736 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4738 function setNewSection( $value ) {
4739 $this->mNewSection
= (bool)$value;
4741 function getNewSection() {
4742 return (bool)$this->mNewSection
;
4745 function addLink( $title, $id = null ) {
4746 $ns = $title->getNamespace();
4747 $dbk = $title->getDBkey();
4748 if ( !isset( $this->mLinks
[$ns] ) ) {
4749 $this->mLinks
[$ns] = array();
4751 if ( is_null( $id ) ) {
4752 $id = $title->getArticleID();
4754 $this->mLinks
[$ns][$dbk] = $id;
4757 function addTemplate( $title, $id ) {
4758 $ns = $title->getNamespace();
4759 $dbk = $title->getDBkey();
4760 if ( !isset( $this->mTemplates
[$ns] ) ) {
4761 $this->mTemplates
[$ns] = array();
4763 $this->mTemplates
[$ns][$dbk] = $id;
4767 * Return true if this cached output object predates the global or
4768 * per-article cache invalidation timestamps, or if it comes from
4769 * an incompatible older version.
4771 * @param string $touched the affected article's last touched timestamp
4775 function expired( $touched ) {
4776 global $wgCacheEpoch;
4777 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4778 $this->getCacheTime() < $touched ||
4779 $this->getCacheTime() <= $wgCacheEpoch ||
4780 !isset( $this->mVersion
) ||
4781 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4786 * Set options of the Parser
4788 * @package MediaWiki
4792 # All variables are supposed to be private in theory, although in practise this is not the case.
4793 var $mUseTeX; # Use texvc to expand <math> tags
4794 var $mUseDynamicDates; # Use DateFormatter to format dates
4795 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4796 var $mAllowExternalImages; # Allow external images inline
4797 var $mAllowExternalImagesFrom; # If not, any exception?
4798 var $mSkin; # Reference to the preferred skin
4799 var $mDateFormat; # Date format index
4800 var $mEditSection; # Create "edit section" links
4801 var $mNumberHeadings; # Automatically number headings
4802 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4803 var $mTidy; # Ask for tidy cleanup
4804 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4805 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4806 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4808 var $mUser; # Stored user object, just used to initialise the skin
4810 function getUseTeX() { return $this->mUseTeX
; }
4811 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4812 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4813 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4814 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4815 function getEditSection() { return $this->mEditSection
; }
4816 function getNumberHeadings() { return $this->mNumberHeadings
; }
4817 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4818 function getTidy() { return $this->mTidy
; }
4819 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4820 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4821 function getRemoveComments() { return $this->mRemoveComments
; }
4823 function &getSkin() {
4824 if ( !isset( $this->mSkin
) ) {
4825 $this->mSkin
= $this->mUser
->getSkin();
4827 return $this->mSkin
;
4830 function getDateFormat() {
4831 if ( !isset( $this->mDateFormat
) ) {
4832 $this->mDateFormat
= $this->mUser
->getDatePreference();
4834 return $this->mDateFormat
;
4837 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4838 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4839 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4840 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4841 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4842 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4843 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4844 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4845 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4846 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4847 function setSkin( $x ) { $this->mSkin
= $x; }
4848 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4849 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4850 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4852 function ParserOptions( $user = null ) {
4853 $this->initialiseFromUser( $user );
4857 * Get parser options
4860 static function newFromUser( $user ) {
4861 return new ParserOptions( $user );
4864 /** Get user options */
4865 function initialiseFromUser( $userInput ) {
4866 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4867 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4868 $fname = 'ParserOptions::initialiseFromUser';
4869 wfProfileIn( $fname );
4870 if ( !$userInput ) {
4872 if ( isset( $wgUser ) ) {
4878 $user =& $userInput;
4881 $this->mUser
= $user;
4883 $this->mUseTeX
= $wgUseTeX;
4884 $this->mUseDynamicDates
= $wgUseDynamicDates;
4885 $this->mInterwikiMagic
= $wgInterwikiMagic;
4886 $this->mAllowExternalImages
= $wgAllowExternalImages;
4887 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4888 $this->mSkin
= null; # Deferred
4889 $this->mDateFormat
= null; # Deferred
4890 $this->mEditSection
= true;
4891 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4892 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4893 $this->mTidy
= false;
4894 $this->mInterfaceMessage
= false;
4895 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4896 $this->mRemoveComments
= true;
4897 wfProfileOut( $fname );
4901 class OnlyIncludeReplacer
{
4904 function replace( $matches ) {
4905 if ( substr( $matches[1], -1 ) == "\n" ) {
4906 $this->output
.= substr( $matches[1], 0, -1 );
4908 $this->output
.= $matches[1];
4914 var $general, $nowiki;
4916 function __construct() {
4917 $this->general
= new ReplacementArray
;
4918 $this->nowiki
= new ReplacementArray
;
4921 function unstripGeneral( $text ) {
4922 wfProfileIn( __METHOD__
);
4923 $text = $this->general
->replace( $text );
4924 wfProfileOut( __METHOD__
);
4928 function unstripNoWiki( $text ) {
4929 wfProfileIn( __METHOD__
);
4930 $text = $this->nowiki
->replace( $text );
4931 wfProfileOut( __METHOD__
);
4935 function unstripBoth( $text ) {
4936 wfProfileIn( __METHOD__
);
4937 $text = $this->general
->replace( $text );
4938 $text = $this->nowiki
->replace( $text );
4939 wfProfileOut( __METHOD__
);