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 if($wgContLang->hasVariants())
1565 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1567 $selflink = array($this->mTitle
->getPrefixedText());
1568 $useSubpages = $this->areSubpagesAllowed();
1569 wfProfileOut( $fname.'-setup' );
1571 # Loop for each link
1572 for ($k = 0; isset( $a[$k] ); $k++
) {
1574 if ( $useLinkPrefixExtension ) {
1575 wfProfileIn( $fname.'-prefixhandling' );
1576 if ( preg_match( $e2, $s, $m ) ) {
1584 $prefix = $first_prefix;
1585 $first_prefix = false;
1587 wfProfileOut( $fname.'-prefixhandling' );
1590 $might_be_img = false;
1592 wfProfileIn( "$fname-e1" );
1593 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1595 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1596 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1597 # the real problem is with the $e1 regex
1600 # Still some problems for cases where the ] is meant to be outside punctuation,
1601 # and no image is in sight. See bug 2095.
1604 substr( $m[3], 0, 1 ) === ']' &&
1605 strpos($text, '[') !== false
1608 $text .= ']'; # so that replaceExternalLinks($text) works later
1609 $m[3] = substr( $m[3], 1 );
1611 # fix up urlencoded title texts
1612 if( strpos( $m[1], '%' ) !== false ) {
1613 # Should anchors '#' also be rejected?
1614 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1617 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1618 $might_be_img = true;
1620 if ( strpos( $m[1], '%' ) !== false ) {
1621 $m[1] = urldecode($m[1]);
1624 } else { # Invalid form; output directly
1625 $s .= $prefix . '[[' . $line ;
1626 wfProfileOut( "$fname-e1" );
1629 wfProfileOut( "$fname-e1" );
1630 wfProfileIn( "$fname-misc" );
1632 # Don't allow internal links to pages containing
1633 # PROTO: where PROTO is a valid URL protocol; these
1634 # should be external links.
1635 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1636 $s .= $prefix . '[[' . $line ;
1640 # Make subpage if necessary
1641 if( $useSubpages ) {
1642 $link = $this->maybeDoSubpageLink( $m[1], $text );
1647 $noforce = (substr($m[1], 0, 1) != ':');
1649 # Strip off leading ':'
1650 $link = substr($link, 1);
1653 wfProfileOut( "$fname-misc" );
1654 wfProfileIn( "$fname-title" );
1655 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1657 $s .= $prefix . '[[' . $line;
1658 wfProfileOut( "$fname-title" );
1662 $ns = $nt->getNamespace();
1663 $iw = $nt->getInterWiki();
1664 wfProfileOut( "$fname-title" );
1666 if ($might_be_img) { # if this is actually an invalid link
1667 wfProfileIn( "$fname-might_be_img" );
1668 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1670 while (isset ($a[$k+
1]) ) {
1671 #look at the next 'line' to see if we can close it there
1672 $spliced = array_splice( $a, $k +
1, 1 );
1673 $next_line = array_shift( $spliced );
1674 $m = explode( ']]', $next_line, 3 );
1675 if ( count( $m ) == 3 ) {
1676 # the first ]] closes the inner link, the second the image
1678 $text .= "[[{$m[0]}]]{$m[1]}";
1681 } elseif ( count( $m ) == 2 ) {
1682 #if there's exactly one ]] that's fine, we'll keep looking
1683 $text .= "[[{$m[0]}]]{$m[1]}";
1685 #if $next_line is invalid too, we need look no further
1686 $text .= '[[' . $next_line;
1691 # we couldn't find the end of this imageLink, so output it raw
1692 #but don't ignore what might be perfectly normal links in the text we've examined
1693 $text = $this->replaceInternalLinks($text);
1694 $s .= "{$prefix}[[$link|$text";
1695 # note: no $trail, because without an end, there *is* no trail
1696 wfProfileOut( "$fname-might_be_img" );
1699 } else { #it's not an image, so output it raw
1700 $s .= "{$prefix}[[$link|$text";
1701 # note: no $trail, because without an end, there *is* no trail
1702 wfProfileOut( "$fname-might_be_img" );
1705 wfProfileOut( "$fname-might_be_img" );
1708 $wasblank = ( '' == $text );
1709 if( $wasblank ) $text = $link;
1711 # Link not escaped by : , create the various objects
1715 wfProfileIn( "$fname-interwiki" );
1716 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1717 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1718 $s = rtrim($s . "\n");
1719 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1720 wfProfileOut( "$fname-interwiki" );
1723 wfProfileOut( "$fname-interwiki" );
1725 if ( $ns == NS_IMAGE
) {
1726 wfProfileIn( "$fname-image" );
1727 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1728 # recursively parse links inside the image caption
1729 # actually, this will parse them in any other parameters, too,
1730 # but it might be hard to fix that, and it doesn't matter ATM
1731 $text = $this->replaceExternalLinks($text);
1732 $text = $this->replaceInternalLinks($text);
1734 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1735 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1736 $this->mOutput
->addImage( $nt->getDBkey() );
1738 wfProfileOut( "$fname-image" );
1741 # We still need to record the image's presence on the page
1742 $this->mOutput
->addImage( $nt->getDBkey() );
1744 wfProfileOut( "$fname-image" );
1748 if ( $ns == NS_CATEGORY
) {
1749 wfProfileIn( "$fname-category" );
1750 $s = rtrim($s . "\n"); # bug 87
1753 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1754 $sortkey = $this->mTitle
->getText();
1756 $sortkey = $this->mTitle
->getPrefixedText();
1761 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1762 $sortkey = str_replace( "\n", '', $sortkey );
1763 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1764 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1767 * Strip the whitespace Category links produce, see bug 87
1768 * @todo We might want to use trim($tmp, "\n") here.
1770 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1772 wfProfileOut( "$fname-category" );
1777 if( ( in_array( $nt->getPrefixedText(), $selflink ) ) &&
1778 ( $nt->getFragment() === '' ) ) {
1779 # Self-links are handled specially; generally de-link and change to bold.
1780 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1784 # Special and Media are pseudo-namespaces; no pages actually exist in them
1785 if( $ns == NS_MEDIA
) {
1786 $link = $sk->makeMediaLinkObj( $nt, $text );
1787 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1788 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1789 $this->mOutput
->addImage( $nt->getDBkey() );
1791 } elseif( $ns == NS_SPECIAL
) {
1792 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1794 } elseif( $ns == NS_IMAGE
) {
1795 $img = new Image( $nt );
1796 if( $img->exists() ) {
1797 // Force a blue link if the file exists; may be a remote
1798 // upload on the shared repository, and we want to see its
1799 // auto-generated page.
1800 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1801 $this->mOutput
->addLink( $nt );
1805 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1807 wfProfileOut( $fname );
1812 * Make a link placeholder. The text returned can be later resolved to a real link with
1813 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1814 * parsing of interwiki links, and secondly to allow all existence checks and
1815 * article length checks (for stub links) to be bundled into a single query.
1818 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1819 wfProfileIn( __METHOD__
);
1820 if ( ! is_object($nt) ) {
1822 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1824 # Separate the link trail from the rest of the link
1825 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1827 if ( $nt->isExternal() ) {
1828 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1829 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1830 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1832 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1833 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1834 $this->mLinkHolders
['queries'][] = $query;
1835 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1836 $this->mLinkHolders
['titles'][] = $nt;
1838 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1841 wfProfileOut( __METHOD__
);
1846 * Render a forced-blue link inline; protect against double expansion of
1847 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1848 * Since this little disaster has to split off the trail text to avoid
1849 * breaking URLs in the following text without breaking trails on the
1850 * wiki links, it's been made into a horrible function.
1853 * @param string $text
1854 * @param string $query
1855 * @param string $trail
1856 * @param string $prefix
1857 * @return string HTML-wikitext mix oh yuck
1859 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1860 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1861 $sk =& $this->mOptions
->getSkin();
1862 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1863 return $this->armorLinks( $link ) . $trail;
1867 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1868 * going to go through further parsing steps before inline URL expansion.
1870 * In particular this is important when using action=render, which causes
1871 * full URLs to be included.
1873 * Oh man I hate our multi-layer parser!
1875 * @param string more-or-less HTML
1876 * @return string less-or-more HTML with NOPARSE bits
1878 function armorLinks( $text ) {
1879 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1880 "{$this->mUniqPrefix}NOPARSE$1", $text );
1884 * Return true if subpage links should be expanded on this page.
1887 function areSubpagesAllowed() {
1888 # Some namespaces don't allow subpages
1889 global $wgNamespacesWithSubpages;
1890 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1894 * Handle link to subpage if necessary
1895 * @param string $target the source of the link
1896 * @param string &$text the link text, modified as necessary
1897 * @return string the full name of the link
1900 function maybeDoSubpageLink($target, &$text) {
1903 # :Foobar -- override special treatment of prefix (images, language links)
1904 # /Foobar -- convert to CurrentPage/Foobar
1905 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1906 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1907 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1909 $fname = 'Parser::maybeDoSubpageLink';
1910 wfProfileIn( $fname );
1911 $ret = $target; # default return value is no change
1914 $target = trim( $target );
1916 # Some namespaces don't allow subpages,
1917 # so only perform processing if subpages are allowed
1918 if( $this->areSubpagesAllowed() ) {
1919 # Look at the first character
1920 if( $target != '' && $target{0} == '/' ) {
1921 # / at end means we don't want the slash to be shown
1922 if( substr( $target, -1, 1 ) == '/' ) {
1923 $target = substr( $target, 1, -1 );
1926 $noslash = substr( $target, 1 );
1929 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1930 if( '' === $text ) {
1932 } # this might be changed for ugliness reasons
1934 # check for .. subpage backlinks
1936 $nodotdot = $target;
1937 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1939 $nodotdot = substr( $nodotdot, 3 );
1941 if($dotdotcount > 0) {
1942 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1943 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1944 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1945 # / at the end means don't show full path
1946 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1947 $nodotdot = substr( $nodotdot, 0, -1 );
1948 if( '' === $text ) {
1952 $nodotdot = trim( $nodotdot );
1953 if( $nodotdot != '' ) {
1954 $ret .= '/' . $nodotdot;
1961 wfProfileOut( $fname );
1966 * Used by doBlockLevels()
1969 /* private */ function closeParagraph() {
1971 if ( '' != $this->mLastSection
) {
1972 $result = '</' . $this->mLastSection
. ">\n";
1974 $this->mInPre
= false;
1975 $this->mLastSection
= '';
1978 # getCommon() returns the length of the longest common substring
1979 # of both arguments, starting at the beginning of both.
1981 /* private */ function getCommon( $st1, $st2 ) {
1982 $fl = strlen( $st1 );
1983 $shorter = strlen( $st2 );
1984 if ( $fl < $shorter ) { $shorter = $fl; }
1986 for ( $i = 0; $i < $shorter; ++
$i ) {
1987 if ( $st1{$i} != $st2{$i} ) { break; }
1991 # These next three functions open, continue, and close the list
1992 # element appropriate to the prefix character passed into them.
1994 /* private */ function openList( $char ) {
1995 $result = $this->closeParagraph();
1997 if ( '*' == $char ) { $result .= '<ul><li>'; }
1998 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1999 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2000 else if ( ';' == $char ) {
2001 $result .= '<dl><dt>';
2002 $this->mDTopen
= true;
2004 else { $result = '<!-- ERR 1 -->'; }
2009 /* private */ function nextItem( $char ) {
2010 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2011 else if ( ':' == $char ||
';' == $char ) {
2013 if ( $this->mDTopen
) { $close = '</dt>'; }
2014 if ( ';' == $char ) {
2015 $this->mDTopen
= true;
2016 return $close . '<dt>';
2018 $this->mDTopen
= false;
2019 return $close . '<dd>';
2022 return '<!-- ERR 2 -->';
2025 /* private */ function closeList( $char ) {
2026 if ( '*' == $char ) { $text = '</li></ul>'; }
2027 else if ( '#' == $char ) { $text = '</li></ol>'; }
2028 else if ( ':' == $char ) {
2029 if ( $this->mDTopen
) {
2030 $this->mDTopen
= false;
2031 $text = '</dt></dl>';
2033 $text = '</dd></dl>';
2036 else { return '<!-- ERR 3 -->'; }
2042 * Make lists from lines starting with ':', '*', '#', etc.
2045 * @return string the lists rendered as HTML
2047 function doBlockLevels( $text, $linestart ) {
2048 $fname = 'Parser::doBlockLevels';
2049 wfProfileIn( $fname );
2051 # Parsing through the text line by line. The main thing
2052 # happening here is handling of block-level elements p, pre,
2053 # and making lists from lines starting with * # : etc.
2055 $textLines = explode( "\n", $text );
2057 $lastPrefix = $output = '';
2058 $this->mDTopen
= $inBlockElem = false;
2060 $paragraphStack = false;
2062 if ( !$linestart ) {
2063 $output .= array_shift( $textLines );
2065 foreach ( $textLines as $oLine ) {
2066 $lastPrefixLength = strlen( $lastPrefix );
2067 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2068 $preOpenMatch = preg_match('/<pre/i', $oLine );
2069 if ( !$this->mInPre
) {
2070 # Multiple prefixes may abut each other for nested lists.
2071 $prefixLength = strspn( $oLine, '*#:;' );
2072 $pref = substr( $oLine, 0, $prefixLength );
2075 $pref2 = str_replace( ';', ':', $pref );
2076 $t = substr( $oLine, $prefixLength );
2077 $this->mInPre
= !empty($preOpenMatch);
2079 # Don't interpret any other prefixes in preformatted text
2081 $pref = $pref2 = '';
2086 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2087 # Same as the last item, so no need to deal with nesting or opening stuff
2088 $output .= $this->nextItem( substr( $pref, -1 ) );
2089 $paragraphStack = false;
2091 if ( substr( $pref, -1 ) == ';') {
2092 # The one nasty exception: definition lists work like this:
2093 # ; title : definition text
2094 # So we check for : in the remainder text to split up the
2095 # title and definition, without b0rking links.
2097 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2099 $output .= $term . $this->nextItem( ':' );
2102 } elseif( $prefixLength ||
$lastPrefixLength ) {
2103 # Either open or close a level...
2104 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2105 $paragraphStack = false;
2107 while( $commonPrefixLength < $lastPrefixLength ) {
2108 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2109 --$lastPrefixLength;
2111 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2112 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2114 while ( $prefixLength > $commonPrefixLength ) {
2115 $char = substr( $pref, $commonPrefixLength, 1 );
2116 $output .= $this->openList( $char );
2118 if ( ';' == $char ) {
2119 # FIXME: This is dupe of code above
2120 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2122 $output .= $term . $this->nextItem( ':' );
2125 ++
$commonPrefixLength;
2127 $lastPrefix = $pref2;
2129 if( 0 == $prefixLength ) {
2130 wfProfileIn( "$fname-paragraph" );
2131 # No prefix (not in list)--go to paragraph mode
2132 // XXX: use a stack for nestable elements like span, table and div
2133 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2134 $closematch = preg_match(
2135 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2136 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2137 if ( $openmatch or $closematch ) {
2138 $paragraphStack = false;
2139 #Â TODO bug 5718: paragraph closed
2140 $output .= $this->closeParagraph();
2141 if ( $preOpenMatch and !$preCloseMatch ) {
2142 $this->mInPre
= true;
2144 if ( $closematch ) {
2145 $inBlockElem = false;
2147 $inBlockElem = true;
2149 } else if ( !$inBlockElem && !$this->mInPre
) {
2150 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2152 if ($this->mLastSection
!= 'pre') {
2153 $paragraphStack = false;
2154 $output .= $this->closeParagraph().'<pre>';
2155 $this->mLastSection
= 'pre';
2157 $t = substr( $t, 1 );
2160 if ( '' == trim($t) ) {
2161 if ( $paragraphStack ) {
2162 $output .= $paragraphStack.'<br />';
2163 $paragraphStack = false;
2164 $this->mLastSection
= 'p';
2166 if ($this->mLastSection
!= 'p' ) {
2167 $output .= $this->closeParagraph();
2168 $this->mLastSection
= '';
2169 $paragraphStack = '<p>';
2171 $paragraphStack = '</p><p>';
2175 if ( $paragraphStack ) {
2176 $output .= $paragraphStack;
2177 $paragraphStack = false;
2178 $this->mLastSection
= 'p';
2179 } else if ($this->mLastSection
!= 'p') {
2180 $output .= $this->closeParagraph().'<p>';
2181 $this->mLastSection
= 'p';
2186 wfProfileOut( "$fname-paragraph" );
2188 // somewhere above we forget to get out of pre block (bug 785)
2189 if($preCloseMatch && $this->mInPre
) {
2190 $this->mInPre
= false;
2192 if ($paragraphStack === false) {
2196 while ( $prefixLength ) {
2197 $output .= $this->closeList( $pref2{$prefixLength-1} );
2200 if ( '' != $this->mLastSection
) {
2201 $output .= '</' . $this->mLastSection
. '>';
2202 $this->mLastSection
= '';
2205 wfProfileOut( $fname );
2210 * Split up a string on ':', ignoring any occurences inside tags
2211 * to prevent illegal overlapping.
2212 * @param string $str the string to split
2213 * @param string &$before set to everything before the ':'
2214 * @param string &$after set to everything after the ':'
2215 * return string the position of the ':', or false if none found
2217 function findColonNoLinks($str, &$before, &$after) {
2218 $fname = 'Parser::findColonNoLinks';
2219 wfProfileIn( $fname );
2221 $pos = strpos( $str, ':' );
2222 if( $pos === false ) {
2224 wfProfileOut( $fname );
2228 $lt = strpos( $str, '<' );
2229 if( $lt === false ||
$lt > $pos ) {
2230 // Easy; no tag nesting to worry about
2231 $before = substr( $str, 0, $pos );
2232 $after = substr( $str, $pos+
1 );
2233 wfProfileOut( $fname );
2237 // Ugly state machine to walk through avoiding tags.
2238 $state = MW_COLON_STATE_TEXT
;
2240 $len = strlen( $str );
2241 for( $i = 0; $i < $len; $i++
) {
2245 // (Using the number is a performance hack for common cases)
2246 case 0: // MW_COLON_STATE_TEXT:
2249 // Could be either a <start> tag or an </end> tag
2250 $state = MW_COLON_STATE_TAGSTART
;
2255 $before = substr( $str, 0, $i );
2256 $after = substr( $str, $i +
1 );
2257 wfProfileOut( $fname );
2260 // Embedded in a tag; don't break it.
2263 // Skip ahead looking for something interesting
2264 $colon = strpos( $str, ':', $i );
2265 if( $colon === false ) {
2266 // Nothing else interesting
2267 wfProfileOut( $fname );
2270 $lt = strpos( $str, '<', $i );
2271 if( $stack === 0 ) {
2272 if( $lt === false ||
$colon < $lt ) {
2274 $before = substr( $str, 0, $colon );
2275 $after = substr( $str, $colon +
1 );
2276 wfProfileOut( $fname );
2280 if( $lt === false ) {
2281 // Nothing else interesting to find; abort!
2282 // We're nested, but there's no close tags left. Abort!
2285 // Skip ahead to next tag start
2287 $state = MW_COLON_STATE_TAGSTART
;
2290 case 1: // MW_COLON_STATE_TAG:
2295 $state = MW_COLON_STATE_TEXT
;
2298 // Slash may be followed by >?
2299 $state = MW_COLON_STATE_TAGSLASH
;
2305 case 2: // MW_COLON_STATE_TAGSTART:
2308 $state = MW_COLON_STATE_CLOSETAG
;
2311 $state = MW_COLON_STATE_COMMENT
;
2314 // Illegal early close? This shouldn't happen D:
2315 $state = MW_COLON_STATE_TEXT
;
2318 $state = MW_COLON_STATE_TAG
;
2321 case 3: // MW_COLON_STATE_CLOSETAG:
2326 wfDebug( "Invalid input in $fname; too many close tags\n" );
2327 wfProfileOut( $fname );
2330 $state = MW_COLON_STATE_TEXT
;
2333 case MW_COLON_STATE_TAGSLASH
:
2335 // Yes, a self-closed tag <blah/>
2336 $state = MW_COLON_STATE_TEXT
;
2338 // Probably we're jumping the gun, and this is an attribute
2339 $state = MW_COLON_STATE_TAG
;
2342 case 5: // MW_COLON_STATE_COMMENT:
2344 $state = MW_COLON_STATE_COMMENTDASH
;
2347 case MW_COLON_STATE_COMMENTDASH
:
2349 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2351 $state = MW_COLON_STATE_COMMENT
;
2354 case MW_COLON_STATE_COMMENTDASHDASH
:
2356 $state = MW_COLON_STATE_TEXT
;
2358 $state = MW_COLON_STATE_COMMENT
;
2362 throw new MWException( "State machine error in $fname" );
2366 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2369 wfProfileOut( $fname );
2374 * Return value of a magic variable (like PAGENAME)
2378 function getVariableValue( $index ) {
2379 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2382 * Some of these require message or data lookups and can be
2383 * expensive to check many times.
2385 static $varCache = array();
2386 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2387 if ( isset( $varCache[$index] ) ) {
2388 return $varCache[$index];
2393 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2396 global $wgLocaltimezone;
2397 if ( isset( $wgLocaltimezone ) ) {
2398 $oldtz = getenv( 'TZ' );
2399 putenv( 'TZ='.$wgLocaltimezone );
2401 $localTimestamp = date( 'YmdHis', $ts );
2402 $localMonth = date( 'm', $ts );
2403 $localMonthName = date( 'n', $ts );
2404 $localDay = date( 'j', $ts );
2405 $localDay2 = date( 'd', $ts );
2406 $localDayOfWeek = date( 'w', $ts );
2407 $localWeek = date( 'W', $ts );
2408 $localYear = date( 'Y', $ts );
2409 $localHour = date( 'H', $ts );
2410 if ( isset( $wgLocaltimezone ) ) {
2411 putenv( 'TZ='.$oldtz );
2415 case 'currentmonth':
2416 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2417 case 'currentmonthname':
2418 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2419 case 'currentmonthnamegen':
2420 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2421 case 'currentmonthabbrev':
2422 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2424 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2426 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2428 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2429 case 'localmonthname':
2430 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2431 case 'localmonthnamegen':
2432 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2433 case 'localmonthabbrev':
2434 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2436 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2438 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2440 return $this->mTitle
->getText();
2442 return $this->mTitle
->getPartialURL();
2443 case 'fullpagename':
2444 return $this->mTitle
->getPrefixedText();
2445 case 'fullpagenamee':
2446 return $this->mTitle
->getPrefixedURL();
2448 return $this->mTitle
->getSubpageText();
2449 case 'subpagenamee':
2450 return $this->mTitle
->getSubpageUrlForm();
2451 case 'basepagename':
2452 return $this->mTitle
->getBaseText();
2453 case 'basepagenamee':
2454 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2455 case 'talkpagename':
2456 if( $this->mTitle
->canTalk() ) {
2457 $talkPage = $this->mTitle
->getTalkPage();
2458 return $talkPage->getPrefixedText();
2462 case 'talkpagenamee':
2463 if( $this->mTitle
->canTalk() ) {
2464 $talkPage = $this->mTitle
->getTalkPage();
2465 return $talkPage->getPrefixedUrl();
2469 case 'subjectpagename':
2470 $subjPage = $this->mTitle
->getSubjectPage();
2471 return $subjPage->getPrefixedText();
2472 case 'subjectpagenamee':
2473 $subjPage = $this->mTitle
->getSubjectPage();
2474 return $subjPage->getPrefixedUrl();
2476 return $this->mRevisionId
;
2478 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2479 case 'revisionday2':
2480 return substr( $this->getRevisionTimestamp(), 6, 2 );
2481 case 'revisionmonth':
2482 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2483 case 'revisionyear':
2484 return substr( $this->getRevisionTimestamp(), 0, 4 );
2485 case 'revisiontimestamp':
2486 return $this->getRevisionTimestamp();
2488 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2490 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2492 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2494 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2495 case 'subjectspace':
2496 return $this->mTitle
->getSubjectNsText();
2497 case 'subjectspacee':
2498 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2499 case 'currentdayname':
2500 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2502 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2504 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2506 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2508 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2509 // int to remove the padding
2510 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2512 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2513 case 'localdayname':
2514 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2516 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2518 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2520 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2522 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2523 // int to remove the padding
2524 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2526 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2527 case 'numberofarticles':
2528 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2529 case 'numberoffiles':
2530 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2531 case 'numberofusers':
2532 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2533 case 'numberofpages':
2534 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2535 case 'numberofadmins':
2536 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2537 case 'currenttimestamp':
2538 return $varCache[$index] = wfTimestampNow();
2539 case 'localtimestamp':
2540 return $varCache[$index] = $localTimestamp;
2541 case 'currentversion':
2542 return $varCache[$index] = SpecialVersion
::getVersion();
2548 return $wgServerName;
2550 return $wgScriptPath;
2551 case 'directionmark':
2552 return $wgContLang->getDirMark();
2553 case 'contentlanguage':
2554 global $wgContLanguageCode;
2555 return $wgContLanguageCode;
2558 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2566 * initialise the magic variables (like CURRENTMONTHNAME)
2570 function initialiseVariables() {
2571 $fname = 'Parser::initialiseVariables';
2572 wfProfileIn( $fname );
2573 $variableIDs = MagicWord
::getVariableIDs();
2575 $this->mVariables
= array();
2576 foreach ( $variableIDs as $id ) {
2577 $mw =& MagicWord
::get( $id );
2578 $mw->addToArray( $this->mVariables
, $id );
2580 wfProfileOut( $fname );
2584 * parse any parentheses in format ((title|part|part))
2585 * and call callbacks to get a replacement text for any found piece
2587 * @param string $text The text to parse
2588 * @param array $callbacks rules in form:
2589 * '{' => array( # opening parentheses
2590 * 'end' => '}', # closing parentheses
2591 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2592 * 3 => callback # replacement callback to call if {{{..}}} is found
2595 * 'min' => 2, # Minimum parenthesis count in cb
2596 * 'max' => 3, # Maximum parenthesis count in cb
2599 function replace_callback ($text, $callbacks) {
2600 wfProfileIn( __METHOD__
);
2601 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2602 $lastOpeningBrace = -1; # last not closed parentheses
2604 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2607 while ( $i < strlen( $text ) ) {
2608 # Find next opening brace, closing brace or pipe
2609 if ( $lastOpeningBrace == -1 ) {
2610 $currentClosing = '';
2611 $search = $validOpeningBraces;
2613 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2614 $search = $validOpeningBraces . '|' . $currentClosing;
2617 $i +
= strcspn( $text, $search, $i );
2618 if ( $i < strlen( $text ) ) {
2619 if ( $text[$i] == '|' ) {
2621 } elseif ( $text[$i] == $currentClosing ) {
2623 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2625 $rule = $callbacks[$text[$i]];
2627 # Some versions of PHP have a strcspn which stops on null characters
2628 # Ignore and continue
2637 if ( $found == 'open' ) {
2638 # found opening brace, let's add it to parentheses stack
2639 $piece = array('brace' => $text[$i],
2640 'braceEnd' => $rule['end'],
2644 # count opening brace characters
2645 $piece['count'] = strspn( $text, $piece['brace'], $i );
2646 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2647 $i +
= $piece['count'];
2649 # we need to add to stack only if opening brace count is enough for one of the rules
2650 if ( $piece['count'] >= $rule['min'] ) {
2651 $lastOpeningBrace ++
;
2652 $openingBraceStack[$lastOpeningBrace] = $piece;
2654 } elseif ( $found == 'close' ) {
2655 # lets check if it is enough characters for closing brace
2656 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2657 $count = strspn( $text, $text[$i], $i, $maxCount );
2659 # check for maximum matching characters (if there are 5 closing
2660 # characters, we will probably need only 3 - depending on the rules)
2662 $matchingCallback = null;
2663 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2664 if ( $count > $cbType['max'] ) {
2665 # The specified maximum exists in the callback array, unless the caller
2667 $matchingCount = $cbType['max'];
2669 # Count is less than the maximum
2670 # Skip any gaps in the callback array to find the true largest match
2671 # Need to use array_key_exists not isset because the callback can be null
2672 $matchingCount = $count;
2673 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2678 if ($matchingCount <= 0) {
2682 $matchingCallback = $cbType['cb'][$matchingCount];
2684 # let's set a title or last part (if '|' was found)
2685 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2686 $openingBraceStack[$lastOpeningBrace]['title'] =
2687 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2688 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2690 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2691 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2692 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2695 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2696 $pieceEnd = $i +
$matchingCount;
2698 if( is_callable( $matchingCallback ) ) {
2700 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2701 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2702 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2703 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2705 # finally we can call a user callback and replace piece of text
2706 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2707 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2708 $i = $pieceStart +
strlen($replaceWith);
2710 # null value for callback means that parentheses should be parsed, but not replaced
2711 $i +
= $matchingCount;
2714 # reset last opening parentheses, but keep it in case there are unused characters
2715 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2716 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2717 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2720 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2721 $openingBraceStack[$lastOpeningBrace--] = null;
2723 if ($matchingCount < $piece['count']) {
2724 $piece['count'] -= $matchingCount;
2725 $piece['startAt'] -= $matchingCount;
2726 $piece['partStart'] = $piece['startAt'];
2727 # do we still qualify for any callback with remaining count?
2728 $currentCbList = $callbacks[$piece['brace']]['cb'];
2729 while ( $piece['count'] ) {
2730 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2731 $lastOpeningBrace++
;
2732 $openingBraceStack[$lastOpeningBrace] = $piece;
2738 } elseif ( $found == 'pipe' ) {
2739 # lets set a title if it is a first separator, or next part otherwise
2740 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2741 $openingBraceStack[$lastOpeningBrace]['title'] =
2742 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2743 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2744 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2746 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2747 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2748 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2750 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2754 wfProfileOut( __METHOD__
);
2759 * Replace magic variables, templates, and template arguments
2760 * with the appropriate text. Templates are substituted recursively,
2761 * taking care to avoid infinite loops.
2763 * Note that the substitution depends on value of $mOutputType:
2764 * OT_WIKI: only {{subst:}} templates
2765 * OT_MSG: only magic variables
2766 * OT_HTML: all templates and magic variables
2768 * @param string $tex The text to transform
2769 * @param array $args Key-value pairs representing template parameters to substitute
2770 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2773 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2774 # Prevent too big inclusions
2775 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2779 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2780 wfProfileIn( $fname );
2782 # This function is called recursively. To keep track of arguments we need a stack:
2783 array_push( $this->mArgStack
, $args );
2785 $braceCallbacks = array();
2787 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2789 if ( $this->mOutputType
!= OT_MSG
) {
2790 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2792 if ( $braceCallbacks ) {
2796 'cb' => $braceCallbacks,
2797 'min' => $argsOnly ?
3 : 2,
2798 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2802 'cb' => array(2=>null),
2807 $text = $this->replace_callback ($text, $callbacks);
2809 array_pop( $this->mArgStack
);
2811 wfProfileOut( $fname );
2816 * Replace magic variables
2819 function variableSubstitution( $matches ) {
2821 $fname = 'Parser::variableSubstitution';
2822 $varname = $wgContLang->lc($matches[1]);
2823 wfProfileIn( $fname );
2825 if ( $this->mOutputType
== OT_WIKI
) {
2826 # Do only magic variables prefixed by SUBST
2827 $mwSubst =& MagicWord
::get( 'subst' );
2828 if (!$mwSubst->matchStartAndRemove( $varname ))
2830 # Note that if we don't substitute the variable below,
2831 # we don't remove the {{subst:}} magic word, in case
2832 # it is a template rather than a magic variable.
2834 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2835 $id = $this->mVariables
[$varname];
2836 # Now check if we did really match, case sensitive or not
2837 $mw =& MagicWord
::get( $id );
2838 if ($mw->match($matches[1])) {
2839 $text = $this->getVariableValue( $id );
2840 $this->mOutput
->mContainsOldMagic
= true;
2842 $text = $matches[0];
2845 $text = $matches[0];
2847 wfProfileOut( $fname );
2852 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2853 static function createAssocArgs( $args ) {
2854 $assocArgs = array();
2856 foreach( $args as $arg ) {
2857 $eqpos = strpos( $arg, '=' );
2858 if ( $eqpos === false ) {
2859 $assocArgs[$index++
] = $arg;
2861 $name = trim( substr( $arg, 0, $eqpos ) );
2862 $value = trim( substr( $arg, $eqpos+
1 ) );
2863 if ( $value === false ) {
2866 if ( $name !== false ) {
2867 $assocArgs[$name] = $value;
2876 * Return the text of a template, after recursively
2877 * replacing any variables or templates within the template.
2879 * @param array $piece The parts of the template
2880 * $piece['text']: matched text
2881 * $piece['title']: the title, i.e. the part before the |
2882 * $piece['parts']: the parameter array
2883 * @return string the text of the template
2886 function braceSubstitution( $piece ) {
2887 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2888 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2889 wfProfileIn( $fname );
2890 wfProfileIn( __METHOD__
.'-setup' );
2893 $found = false; # $text has been filled
2894 $nowiki = false; # wiki markup in $text should be escaped
2895 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2896 $noargs = false; # Don't replace triple-brace arguments in $text
2897 $replaceHeadings = false; # Make the edit section links go to the template not the article
2898 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2899 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2900 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2902 # Title object, where $text came from
2908 # $part1 is the bit before the first |, and must contain only title characters
2909 # $args is a list of arguments, starting from index 0, not including $part1
2911 $titleText = $part1 = $piece['title'];
2912 # If the third subpattern matched anything, it will start with |
2914 if (null == $piece['parts']) {
2915 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2916 if ($replaceWith != $piece['text']) {
2917 $text = $replaceWith;
2924 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2925 wfProfileOut( __METHOD__
.'-setup' );
2928 wfProfileIn( __METHOD__
.'-modifiers' );
2930 $mwSubst =& MagicWord
::get( 'subst' );
2931 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2932 # One of two possibilities is true:
2933 # 1) Found SUBST but not in the PST phase
2934 # 2) Didn't find SUBST and in the PST phase
2935 # In either case, return without further processing
2936 $text = $piece['text'];
2943 # MSG, MSGNW and RAW
2946 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2947 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2950 # Remove obsolete MSG:
2951 $mwMsg =& MagicWord
::get( 'msg' );
2952 $mwMsg->matchStartAndRemove( $part1 );
2956 $mwRaw =& MagicWord
::get( 'raw' );
2957 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2958 $forceRawInterwiki = true;
2961 wfProfileOut( __METHOD__
.'-modifiers' );
2963 //save path level before recursing into functions & templates.
2964 $lastPathLevel = $this->mTemplatePath
;
2968 wfProfileIn( __METHOD__
. '-pfunc' );
2970 $colonPos = strpos( $part1, ':' );
2971 if ( $colonPos !== false ) {
2972 # Case sensitive functions
2973 $function = substr( $part1, 0, $colonPos );
2974 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2975 $function = $this->mFunctionSynonyms
[1][$function];
2977 # Case insensitive functions
2978 $function = strtolower( $function );
2979 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2980 $function = $this->mFunctionSynonyms
[0][$function];
2986 $funcArgs = array_map( 'trim', $args );
2987 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2988 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2991 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2995 if ( is_array( $result ) ) {
2996 if ( isset( $result[0] ) ) {
2997 $text = $linestart . $result[0];
2998 unset( $result[0] );
3001 // Extract flags into the local scope
3002 // This allows callers to set flags such as nowiki, noparse, found, etc.
3005 $text = $linestart . $result;
3009 wfProfileOut( __METHOD__
. '-pfunc' );
3012 # Template table test
3014 # Did we encounter this template already? If yes, it is in the cache
3015 # and we need to check for loops.
3016 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3019 # Infinite loop test
3020 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3024 $text = $linestart .
3025 "[[$part1]]<!-- WARNING: template loop detected -->";
3026 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3028 # set $text to cached message.
3029 $text = $linestart . $this->mTemplates
[$piece['title']];
3033 # Load from database
3035 wfProfileIn( __METHOD__
. '-loadtpl' );
3037 # declaring $subpage directly in the function call
3038 # does not work correctly with references and breaks
3039 # {{/subpage}}-style inclusions
3041 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3042 if ($subpage !== '') {
3043 $ns = $this->mTitle
->getNamespace();
3045 $title = Title
::newFromText( $part1, $ns );
3048 if ( !is_null( $title ) ) {
3049 $titleText = $title->getPrefixedText();
3050 # Check for language variants if the template is not found
3051 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3052 $wgContLang->findVariantLink($part1, $title);
3055 if ( !$title->isExternal() ) {
3056 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3057 $text = SpecialPage
::capturePath( $title );
3058 if ( is_string( $text ) ) {
3063 $this->disableCache();
3066 $articleContent = $this->fetchTemplate( $title );
3067 if ( $articleContent !== false ) {
3069 $text = $articleContent;
3070 $replaceHeadings = true;
3074 # If the title is valid but undisplayable, make a link to it
3075 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3076 $text = "[[:$titleText]]";
3079 } elseif ( $title->isTrans() ) {
3080 // Interwiki transclusion
3081 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3082 $text = $this->interwikiTransclude( $title, 'render' );
3086 $text = $this->interwikiTransclude( $title, 'raw' );
3087 $replaceHeadings = true;
3092 # Template cache array insertion
3093 # Use the original $piece['title'] not the mangled $part1, so that
3094 # modifiers such as RAW: produce separate cache entries
3097 // A special page; don't store it in the template cache.
3099 $this->mTemplates
[$piece['title']] = $text;
3101 $text = $linestart . $text;
3104 wfProfileOut( __METHOD__
. '-loadtpl' );
3107 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3108 # Error, oversize inclusion
3109 $text = $linestart .
3110 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3115 # Recursive parsing, escaping and link table handling
3116 # Only for HTML output
3117 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3118 $text = wfEscapeWikiText( $text );
3119 } elseif ( !$this->ot
['msg'] && $found ) {
3121 $assocArgs = array();
3123 # Clean up argument array
3124 $assocArgs = self
::createAssocArgs($args);
3125 # Add a new element to the templace recursion path
3126 $this->mTemplatePath
[$part1] = 1;
3130 # If there are any <onlyinclude> tags, only include them
3131 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3132 $replacer = new OnlyIncludeReplacer
;
3133 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3134 array( &$replacer, 'replace' ), $text );
3135 $text = $replacer->output
;
3137 # Remove <noinclude> sections and <includeonly> tags
3138 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3139 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3141 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3142 # Strip <nowiki>, <pre>, etc.
3143 $text = $this->strip( $text, $this->mStripState
);
3144 if ( $this->ot
['html'] ) {
3145 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3146 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3147 $text = Sanitizer
::removeHTMLcomments( $text );
3150 $text = $this->replaceVariables( $text, $assocArgs );
3152 # If the template begins with a table or block-level
3153 # element, it should be treated as beginning a new line.
3154 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3155 $text = "\n" . $text;
3157 } elseif ( !$noargs ) {
3158 # $noparse and !$noargs
3159 # Just replace the arguments, not any double-brace items
3160 # This is used for rendered interwiki transclusion
3161 $text = $this->replaceVariables( $text, $assocArgs, true );
3164 # Prune lower levels off the recursion check path
3165 $this->mTemplatePath
= $lastPathLevel;
3167 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3168 # Error, oversize inclusion
3169 $text = $linestart .
3170 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3176 wfProfileOut( $fname );
3177 return $piece['text'];
3179 wfProfileIn( __METHOD__
. '-placeholders' );
3181 # Replace raw HTML by a placeholder
3182 # Add a blank line preceding, to prevent it from mucking up
3183 # immediately preceding headings
3184 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3186 # replace ==section headers==
3187 # XXX this needs to go away once we have a better parser.
3188 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3189 if( !is_null( $title ) )
3190 $encodedname = base64_encode($title->getPrefixedDBkey());
3192 $encodedname = base64_encode("");
3193 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3194 PREG_SPLIT_DELIM_CAPTURE
);
3196 $nsec = $headingOffset;
3197 for( $i = 0; $i < count($m); $i +
= 2 ) {
3199 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3201 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3206 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3207 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3208 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3214 wfProfileOut( __METHOD__
. '-placeholders' );
3217 # Prune lower levels off the recursion check path
3218 $this->mTemplatePath
= $lastPathLevel;
3221 wfProfileOut( $fname );
3222 return $piece['text'];
3224 wfProfileOut( $fname );
3230 * Fetch the unparsed text of a template and register a reference to it.
3232 function fetchTemplate( $title ) {
3234 // Loop to fetch the article, with up to 1 redirect
3235 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3236 $rev = Revision
::newFromTitle( $title );
3237 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3241 $text = $rev->getText();
3242 if ( $text === false ) {
3246 $title = Title
::newFromRedirect( $text );
3252 * Transclude an interwiki link.
3254 function interwikiTransclude( $title, $action ) {
3255 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3257 if (!$wgEnableScaryTranscluding)
3258 return wfMsg('scarytranscludedisabled');
3260 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3261 // But we'll handle it generally anyway
3262 if ( $title->getNamespace() ) {
3263 // Use the canonical namespace, which should work anywhere
3264 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3266 $articleName = $title->getDBkey();
3269 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3270 $url .= "?action=$action";
3271 if (strlen($url) > 255)
3272 return wfMsg('scarytranscludetoolong');
3273 return $this->fetchScaryTemplateMaybeFromCache($url);
3276 function fetchScaryTemplateMaybeFromCache($url) {
3277 global $wgTranscludeCacheExpiry;
3278 $dbr =& wfGetDB(DB_SLAVE
);
3279 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3280 array('tc_url' => $url));
3282 $time = $obj->tc_time
;
3283 $text = $obj->tc_contents
;
3284 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3289 $text = Http
::get($url);
3291 return wfMsg('scarytranscludefailed', $url);
3293 $dbw =& wfGetDB(DB_MASTER
);
3294 $dbw->replace('transcache', array('tc_url'), array(
3296 'tc_time' => time(),
3297 'tc_contents' => $text));
3303 * Triple brace replacement -- used for template arguments
3306 function argSubstitution( $matches ) {
3307 $arg = trim( $matches['title'] );
3308 $text = $matches['text'];
3309 $inputArgs = end( $this->mArgStack
);
3311 if ( array_key_exists( $arg, $inputArgs ) ) {
3312 $text = $inputArgs[$arg];
3313 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3314 null != $matches['parts'] && count($matches['parts']) > 0) {
3315 $text = $matches['parts'][0];
3317 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3318 $text = $matches['text'] .
3319 '<!-- WARNING: argument omitted, expansion size too large -->';
3326 * Increment an include size counter
3328 * @param string $type The type of expansion
3329 * @param integer $size The size of the text
3330 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3332 function incrementIncludeSize( $type, $size ) {
3333 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3336 $this->mIncludeSizes
[$type] +
= $size;
3342 * Detect __NOGALLERY__ magic word and set a placeholder
3344 function stripNoGallery( &$text ) {
3345 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3347 $mw = MagicWord
::get( 'nogallery' );
3348 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3352 * Detect __TOC__ magic word and set a placeholder
3354 function stripToc( $text ) {
3355 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3357 $mw = MagicWord
::get( 'notoc' );
3358 if( $mw->matchAndRemove( $text ) ) {
3359 $this->mShowToc
= false;
3362 $mw = MagicWord
::get( 'toc' );
3363 if( $mw->match( $text ) ) {
3364 $this->mShowToc
= true;
3365 $this->mForceTocPosition
= true;
3367 // Set a placeholder. At the end we'll fill it in with the TOC.
3368 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3370 // Only keep the first one.
3371 $text = $mw->replace( '', $text );
3377 * This function accomplishes several tasks:
3378 * 1) Auto-number headings if that option is enabled
3379 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3380 * 3) Add a Table of contents on the top for users who have enabled the option
3381 * 4) Auto-anchor headings
3383 * It loops through all headlines, collects the necessary data, then splits up the
3384 * string and re-inserts the newly formatted headlines.
3386 * @param string $text
3387 * @param boolean $isMain
3390 function formatHeadings( $text, $isMain=true ) {
3391 global $wgMaxTocLevel, $wgContLang;
3393 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3394 if( !$this->mTitle
->userCanEdit() ) {
3397 $showEditLink = $this->mOptions
->getEditSection();
3400 # Inhibit editsection links if requested in the page
3401 $esw =& MagicWord
::get( 'noeditsection' );
3402 if( $esw->matchAndRemove( $text ) ) {
3406 # Get all headlines for numbering them and adding funky stuff like [edit]
3407 # links - this is for later, but we need the number of headlines right now
3409 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3411 # if there are fewer than 4 headlines in the article, do not show TOC
3412 # unless it's been explicitly enabled.
3413 $enoughToc = $this->mShowToc
&&
3414 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3416 # Allow user to stipulate that a page should have a "new section"
3417 # link added via __NEWSECTIONLINK__
3418 $mw =& MagicWord
::get( 'newsectionlink' );
3419 if( $mw->matchAndRemove( $text ) )
3420 $this->mOutput
->setNewSection( true );
3422 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3423 # override above conditions and always show TOC above first header
3424 $mw =& MagicWord
::get( 'forcetoc' );
3425 if ($mw->matchAndRemove( $text ) ) {
3426 $this->mShowToc
= true;
3430 # Never ever show TOC if no headers
3431 if( $numMatches < 1 ) {
3435 # We need this to perform operations on the HTML
3436 $sk =& $this->mOptions
->getSkin();
3440 $sectionCount = 0; # headlineCount excluding template sections
3442 # Ugh .. the TOC should have neat indentation levels which can be
3443 # passed to the skin functions. These are determined here
3447 $sublevelCount = array();
3448 $levelCount = array();
3455 foreach( $matches[3] as $headline ) {
3457 $templatetitle = '';
3458 $templatesection = 0;
3461 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3463 $templatetitle = base64_decode($mat[1]);
3464 $templatesection = 1 +
(int)base64_decode($mat[2]);
3465 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3469 $prevlevel = $level;
3470 $prevtoclevel = $toclevel;
3472 $level = $matches[1][$headlineCount];
3474 if( $doNumberHeadings ||
$enoughToc ) {
3476 if ( $level > $prevlevel ) {
3477 # Increase TOC level
3479 $sublevelCount[$toclevel] = 0;
3480 if( $toclevel<$wgMaxTocLevel ) {
3481 $toc .= $sk->tocIndent();
3484 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3485 # Decrease TOC level, find level to jump to
3487 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3488 # Can only go down to level 1
3491 for ($i = $toclevel; $i > 0; $i--) {
3492 if ( $levelCount[$i] == $level ) {
3493 # Found last matching level
3497 elseif ( $levelCount[$i] < $level ) {
3498 # Found first matching level below current level
3504 if( $toclevel<$wgMaxTocLevel ) {
3505 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3509 # No change in level, end TOC line
3510 if( $toclevel<$wgMaxTocLevel ) {
3511 $toc .= $sk->tocLineEnd();
3515 $levelCount[$toclevel] = $level;
3517 # count number of headlines for each level
3518 @$sublevelCount[$toclevel]++
;
3520 for( $i = 1; $i <= $toclevel; $i++
) {
3521 if( !empty( $sublevelCount[$i] ) ) {
3525 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3531 # The canonized header is a version of the header text safe to use for links
3532 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3533 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3535 # Remove link placeholders by the link text.
3536 # <!--LINK number-->
3538 # link text with suffix
3539 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3540 "\$this->mLinkHolders['texts'][\$1]",
3541 $canonized_headline );
3542 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3543 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3544 $canonized_headline );
3547 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3548 $tocline = trim( $canonized_headline );
3549 # Save headline for section edit hint before it's escaped
3550 $headline_hint = trim( $canonized_headline );
3551 $canonized_headline = Sanitizer
::escapeId( $tocline );
3552 $refers[$headlineCount] = $canonized_headline;
3554 # count how many in assoc. array so we can track dupes in anchors
3555 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3556 $refcount[$headlineCount]=$refers[$canonized_headline];
3558 # Don't number the heading if it is the only one (looks silly)
3559 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3560 # the two are different if the line contains a link
3561 $headline=$numbering . ' ' . $headline;
3564 # Create the anchor for linking from the TOC to the section
3565 $anchor = $canonized_headline;
3566 if($refcount[$headlineCount] > 1 ) {
3567 $anchor .= '_' . $refcount[$headlineCount];
3569 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3570 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3572 # give headline the correct <h#> tag
3573 $head[$headlineCount] = "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3575 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3576 if ( empty( $head[$headlineCount] ) ) {
3577 $head[$headlineCount] = '';
3580 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3582 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3584 // Yes, the headline logically goes before the edit section. Why isn't it there
3585 // in source? Ask the CSS people. The float gets screwed up if you do that.
3586 // This might be moved to before the editsection at some point so that it will
3587 // display a bit more prettily without CSS, so please don't rely on the order.
3588 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3596 if( $toclevel<$wgMaxTocLevel ) {
3597 $toc .= $sk->tocUnindent( $toclevel - 1 );
3599 $toc = $sk->tocList( $toc );
3602 # split up and insert constructed headlines
3604 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3607 foreach( $blocks as $block ) {
3608 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3609 # This is the [edit] link that appears for the top block of text when
3610 # section editing is enabled
3612 # Disabled because it broke block formatting
3613 # For example, a bullet point in the top line
3614 # $full .= $sk->editSectionLink(0);
3617 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3618 # Top anchor now in skin
3622 if( !empty( $head[$i] ) ) {
3627 if( $this->mForceTocPosition
) {
3628 return str_replace( '<!--MWTOC-->', $toc, $full );
3635 * Transform wiki markup when saving a page by doing \r\n -> \n
3636 * conversion, substitting signatures, {{subst:}} templates, etc.
3638 * @param string $text the text to transform
3639 * @param Title &$title the Title object for the current article
3640 * @param User &$user the User object describing the current user
3641 * @param ParserOptions $options parsing options
3642 * @param bool $clearState whether to clear the parser state first
3643 * @return string the altered wiki markup
3646 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3647 $this->mOptions
= $options;
3648 $this->mTitle
=& $title;
3649 $this->setOutputType( OT_WIKI
);
3651 if ( $clearState ) {
3652 $this->clearState();
3655 $stripState = new StripState
;
3659 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3660 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3661 $text = $this->pstPass2( $text, $stripState, $user );
3662 $text = $stripState->unstripBoth( $text );
3667 * Pre-save transform helper function
3670 function pstPass2( $text, &$stripState, $user ) {
3671 global $wgContLang, $wgLocaltimezone;
3673 /* Note: This is the timestamp saved as hardcoded wikitext to
3674 * the database, we use $wgContLang here in order to give
3675 * everyone the same signature and use the default one rather
3676 * than the one selected in each user's preferences.
3678 if ( isset( $wgLocaltimezone ) ) {
3679 $oldtz = getenv( 'TZ' );
3680 putenv( 'TZ='.$wgLocaltimezone );
3682 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3683 ' (' . date( 'T' ) . ')';
3684 if ( isset( $wgLocaltimezone ) ) {
3685 putenv( 'TZ='.$oldtz );
3688 # Variable replacement
3689 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3690 $text = $this->replaceVariables( $text );
3692 # Strip out <nowiki> etc. added via replaceVariables
3693 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3696 $sigText = $this->getUserSig( $user );
3697 $text = strtr( $text, array(
3699 '~~~~' => "$sigText $d",
3703 # Context links: [[|name]] and [[name (context)|]]
3705 global $wgLegalTitleChars;
3706 $tc = "[$wgLegalTitleChars]";
3707 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3709 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3710 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3711 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3713 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3714 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3715 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3717 $t = $this->mTitle
->getText();
3719 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3720 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3721 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3722 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3724 # if there's no context, don't bother duplicating the title
3725 $text = preg_replace( $p2, '[[\\1]]', $text );
3728 # Trim trailing whitespace
3729 # __END__ tag allows for trailing
3730 # whitespace to be deliberately included
3731 $text = rtrim( $text );
3732 $mw =& MagicWord
::get( 'end' );
3733 $mw->matchAndRemove( $text );
3739 * Fetch the user's signature text, if any, and normalize to
3740 * validated, ready-to-insert wikitext.
3746 function getUserSig( &$user ) {
3747 $username = $user->getName();
3748 $nickname = $user->getOption( 'nickname' );
3749 $nickname = $nickname === '' ?
$username : $nickname;
3751 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3752 # Sig. might contain markup; validate this
3753 if( $this->validateSig( $nickname ) !== false ) {
3754 # Validated; clean up (if needed) and return it
3755 return $this->cleanSig( $nickname, true );
3757 # Failed to validate; fall back to the default
3758 $nickname = $username;
3759 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3763 // Make sure nickname doesnt get a sig in a sig
3764 $nickname = $this->cleanSigInSig( $nickname );
3766 # If we're still here, make it a link to the user page
3767 $userpage = $user->getUserPage();
3768 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3772 * Check that the user's signature contains no bad XML
3774 * @param string $text
3775 * @return mixed An expanded string, or false if invalid.
3777 function validateSig( $text ) {
3778 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3782 * Clean up signature text
3784 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3785 * 2) Substitute all transclusions
3787 * @param string $text
3788 * @param $parsing Whether we're cleaning (preferences save) or parsing
3789 * @return string Signature text
3791 function cleanSig( $text, $parsing = false ) {
3793 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3795 $substWord = MagicWord
::get( 'subst' );
3796 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3797 $substText = '{{' . $substWord->getSynonym( 0 );
3799 $text = preg_replace( $substRegex, $substText, $text );
3800 $text = $this->cleanSigInSig( $text );
3801 $text = $this->replaceVariables( $text );
3803 $this->clearState();
3808 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3809 * @param string $text
3810 * @return string Signature text with /~{3,5}/ removed
3812 function cleanSigInSig( $text ) {
3813 $text = preg_replace( '/~{3,5}/', '', $text );
3818 * Set up some variables which are usually set up in parse()
3819 * so that an external function can call some class members with confidence
3822 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3823 $this->mTitle
=& $title;
3824 $this->mOptions
= $options;
3825 $this->setOutputType( $outputType );
3826 if ( $clearState ) {
3827 $this->clearState();
3832 * Transform a MediaWiki message by replacing magic variables.
3834 * @param string $text the text to transform
3835 * @param ParserOptions $options options
3836 * @return string the text with variables substituted
3839 function transformMsg( $text, $options ) {
3841 static $executing = false;
3843 $fname = "Parser::transformMsg";
3845 # Guard against infinite recursion
3851 wfProfileIn($fname);
3854 $this->mTitle
= $wgTitle;
3856 $this->mTitle
= Title
::newFromText('msg');
3858 $this->mOptions
= $options;
3859 $this->setOutputType( OT_MSG
);
3860 $this->clearState();
3861 $text = $this->replaceVariables( $text );
3864 wfProfileOut($fname);
3869 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3870 * The callback should have the following form:
3871 * function myParserHook( $text, $params, &$parser ) { ... }
3873 * Transform and return $text. Use $parser for any required context, e.g. use
3874 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3878 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3879 * @param mixed $callback The callback function (and object) to use for the tag
3881 * @return The old value of the mTagHooks array associated with the hook
3883 function setHook( $tag, $callback ) {
3884 $tag = strtolower( $tag );
3885 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3886 $this->mTagHooks
[$tag] = $callback;
3892 * Create a function, e.g. {{sum:1|2|3}}
3893 * The callback function should have the form:
3894 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3896 * The callback may either return the text result of the function, or an array with the text
3897 * in element 0, and a number of flags in the other elements. The names of the flags are
3898 * specified in the keys. Valid flags are:
3899 * found The text returned is valid, stop processing the template. This
3901 * nowiki Wiki markup in the return value should be escaped
3902 * noparse Unsafe HTML tags should not be stripped, etc.
3903 * noargs Don't replace triple-brace arguments in the return value
3904 * isHTML The returned text is HTML, armour it against wikitext transformation
3908 * @param string $id The magic word ID
3909 * @param mixed $callback The callback function (and object) to use
3910 * @param integer $flags a combination of the following flags:
3911 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3913 * @return The old callback function for this name, if any
3915 function setFunctionHook( $id, $callback, $flags = 0 ) {
3916 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3917 $this->mFunctionHooks
[$id] = $callback;
3919 # Add to function cache
3920 $mw = MagicWord
::get( $id );
3922 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3924 $synonyms = $mw->getSynonyms();
3925 $sensitive = intval( $mw->isCaseSensitive() );
3927 foreach ( $synonyms as $syn ) {
3929 if ( !$sensitive ) {
3930 $syn = strtolower( $syn );
3933 if ( !( $flags & SFH_NO_HASH
) ) {
3936 # Remove trailing colon
3937 if ( substr( $syn, -1, 1 ) == ':' ) {
3938 $syn = substr( $syn, 0, -1 );
3940 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3946 * Get all registered function hook identifiers
3950 function getFunctionHooks() {
3951 return array_keys( $this->mFunctionHooks
);
3955 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3956 * Placeholders created in Skin::makeLinkObj()
3957 * Returns an array of links found, indexed by PDBK:
3961 * $options is a bit field, RLH_FOR_UPDATE to select for update
3963 function replaceLinkHolders( &$text, $options = 0 ) {
3967 $fname = 'Parser::replaceLinkHolders';
3968 wfProfileIn( $fname );
3972 $sk =& $this->mOptions
->getSkin();
3973 $linkCache =& LinkCache
::singleton();
3975 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3976 wfProfileIn( $fname.'-check' );
3977 $dbr =& wfGetDB( DB_SLAVE
);
3978 $page = $dbr->tableName( 'page' );
3979 $threshold = $wgUser->getOption('stubthreshold');
3982 asort( $this->mLinkHolders
['namespaces'] );
3987 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3989 $title = $this->mLinkHolders
['titles'][$key];
3991 # Skip invalid entries.
3992 # Result will be ugly, but prevents crash.
3993 if ( is_null( $title ) ) {
3996 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3998 # Check if it's a static known link, e.g. interwiki
3999 if ( $title->isAlwaysKnown() ) {
4000 $colours[$pdbk] = 1;
4001 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4002 $colours[$pdbk] = 1;
4003 $this->mOutput
->addLink( $title, $id );
4004 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4005 $colours[$pdbk] = 0;
4007 # Not in the link cache, add it to the query
4008 if ( !isset( $current ) ) {
4010 $query = "SELECT page_id, page_namespace, page_title";
4011 if ( $threshold > 0 ) {
4012 $query .= ', page_len, page_is_redirect';
4014 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4015 } elseif ( $current != $ns ) {
4017 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4022 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4027 if ( $options & RLH_FOR_UPDATE
) {
4028 $query .= ' FOR UPDATE';
4031 $res = $dbr->query( $query, $fname );
4033 # Fetch data and form into an associative array
4034 # non-existent = broken
4037 while ( $s = $dbr->fetchObject($res) ) {
4038 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4039 $pdbk = $title->getPrefixedDBkey();
4040 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4041 $this->mOutput
->addLink( $title, $s->page_id
);
4043 if ( $threshold > 0 ) {
4044 $size = $s->page_len
;
4045 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4046 $colours[$pdbk] = 1;
4048 $colours[$pdbk] = 2;
4051 $colours[$pdbk] = 1;
4055 wfProfileOut( $fname.'-check' );
4057 # Do a second query for different language variants of links and categories
4058 if($wgContLang->hasVariants()){
4059 $linkBatch = new LinkBatch();
4060 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4061 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4062 $varCategories = array(); // category replacements oldDBkey => newDBkey
4064 $categories = $this->mOutput
->getCategoryLinks();
4066 // Add variants of links to link batch
4067 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4068 $title = $this->mLinkHolders
['titles'][$key];
4069 if ( is_null( $title ) )
4072 $pdbk = $title->getPrefixedDBkey();
4073 $titleText = $title->getText();
4075 // generate all variants of the link title text
4076 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4078 // if link was not found (in first query), add all variants to query
4079 if ( !isset($colours[$pdbk]) ){
4080 foreach($allTextVariants as $textVariant){
4081 if($textVariant != $titleText){
4082 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4083 if(is_null($variantTitle)) continue;
4084 $linkBatch->addObj( $variantTitle );
4085 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4091 // process categories, check if a category exists in some variant
4092 foreach( $categories as $category){
4093 $variants = $wgContLang->convertLinkToAllVariants($category);
4094 foreach($variants as $variant){
4095 if($variant != $category){
4096 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4097 if(is_null($variantTitle)) continue;
4098 $linkBatch->addObj( $variantTitle );
4099 $categoryMap[$variant] = $category;
4105 if(!$linkBatch->isEmpty()){
4107 $titleClause = $linkBatch->constructSet('page', $dbr);
4109 $variantQuery = "SELECT page_id, page_namespace, page_title";
4110 if ( $threshold > 0 ) {
4111 $variantQuery .= ', page_len, page_is_redirect';
4114 $variantQuery .= " FROM $page WHERE $titleClause";
4115 if ( $options & RLH_FOR_UPDATE
) {
4116 $variantQuery .= ' FOR UPDATE';
4119 $varRes = $dbr->query( $variantQuery, $fname );
4121 // for each found variants, figure out link holders and replace
4122 while ( $s = $dbr->fetchObject($varRes) ) {
4124 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4125 $varPdbk = $variantTitle->getPrefixedDBkey();
4126 $vardbk = $variantTitle->getDBkey();
4128 $holderKeys = array();
4129 if(isset($variantMap[$varPdbk])){
4130 $holderKeys = $variantMap[$varPdbk];
4131 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4132 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4135 // loop over link holders
4136 foreach($holderKeys as $key){
4137 $title = $this->mLinkHolders
['titles'][$key];
4138 if ( is_null( $title ) ) continue;
4140 $pdbk = $title->getPrefixedDBkey();
4142 if(!isset($colours[$pdbk])){
4143 // found link in some of the variants, replace the link holder data
4144 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4145 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4147 // set pdbk and colour
4148 $pdbks[$key] = $varPdbk;
4149 if ( $threshold > 0 ) {
4150 $size = $s->page_len
;
4151 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4152 $colours[$varPdbk] = 1;
4154 $colours[$varPdbk] = 2;
4158 $colours[$varPdbk] = 1;
4163 // check if the object is a variant of a category
4164 if(isset($categoryMap[$vardbk])){
4165 $oldkey = $categoryMap[$vardbk];
4166 if($oldkey != $vardbk)
4167 $varCategories[$oldkey]=$vardbk;
4171 // rebuild the categories in original order (if there are replacements)
4172 if(count($varCategories)>0){
4174 $originalCats = $this->mOutput
->getCategories();
4175 foreach($originalCats as $cat => $sortkey){
4176 // make the replacement
4177 if( array_key_exists($cat,$varCategories) )
4178 $newCats[$varCategories[$cat]] = $sortkey;
4179 else $newCats[$cat] = $sortkey;
4181 $this->mOutput
->setCategoryLinks($newCats);
4186 # Construct search and replace arrays
4187 wfProfileIn( $fname.'-construct' );
4188 $replacePairs = array();
4189 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4190 $pdbk = $pdbks[$key];
4191 $searchkey = "<!--LINK $key-->";
4192 $title = $this->mLinkHolders
['titles'][$key];
4193 if ( empty( $colours[$pdbk] ) ) {
4194 $linkCache->addBadLinkObj( $title );
4195 $colours[$pdbk] = 0;
4196 $this->mOutput
->addLink( $title, 0 );
4197 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4198 $this->mLinkHolders
['texts'][$key],
4199 $this->mLinkHolders
['queries'][$key] );
4200 } elseif ( $colours[$pdbk] == 1 ) {
4201 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4202 $this->mLinkHolders
['texts'][$key],
4203 $this->mLinkHolders
['queries'][$key] );
4204 } elseif ( $colours[$pdbk] == 2 ) {
4205 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4206 $this->mLinkHolders
['texts'][$key],
4207 $this->mLinkHolders
['queries'][$key] );
4210 $replacer = new HashtableReplacer( $replacePairs, 1 );
4211 wfProfileOut( $fname.'-construct' );
4214 wfProfileIn( $fname.'-replace' );
4215 $text = preg_replace_callback(
4216 '/(<!--LINK .*?-->)/',
4220 wfProfileOut( $fname.'-replace' );
4223 # Now process interwiki link holders
4224 # This is quite a bit simpler than internal links
4225 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4226 wfProfileIn( $fname.'-interwiki' );
4227 # Make interwiki link HTML
4228 $replacePairs = array();
4229 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4230 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4231 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4233 $replacer = new HashtableReplacer( $replacePairs, 1 );
4235 $text = preg_replace_callback(
4236 '/<!--IWLINK (.*?)-->/',
4239 wfProfileOut( $fname.'-interwiki' );
4242 wfProfileOut( $fname );
4247 * Replace <!--LINK--> link placeholders with plain text of links
4248 * (not HTML-formatted).
4249 * @param string $text
4252 function replaceLinkHoldersText( $text ) {
4253 $fname = 'Parser::replaceLinkHoldersText';
4254 wfProfileIn( $fname );
4256 $text = preg_replace_callback(
4257 '/<!--(LINK|IWLINK) (.*?)-->/',
4258 array( &$this, 'replaceLinkHoldersTextCallback' ),
4261 wfProfileOut( $fname );
4266 * @param array $matches
4270 function replaceLinkHoldersTextCallback( $matches ) {
4271 $type = $matches[1];
4273 if( $type == 'LINK' ) {
4274 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4275 return $this->mLinkHolders
['texts'][$key];
4277 } elseif( $type == 'IWLINK' ) {
4278 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4279 return $this->mInterwikiLinkHolders
['texts'][$key];
4286 * Tag hook handler for 'pre'.
4288 function renderPreTag( $text, $attribs ) {
4289 // Backwards-compatibility hack
4290 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4292 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4293 return wfOpenElement( 'pre', $attribs ) .
4294 Xml
::escapeTagsOnly( $content ) .
4299 * Renders an image gallery from a text with one line per image.
4300 * text labels may be given by using |-style alternative text. E.g.
4301 * Image:one.jpg|The number "1"
4302 * Image:tree.jpg|A tree
4303 * given as text will return the HTML of a gallery with two images,
4304 * labeled 'The number "1"' and
4307 function renderImageGallery( $text, $params ) {
4308 $ig = new ImageGallery();
4309 $ig->setShowBytes( false );
4310 $ig->setShowFilename( false );
4312 $ig->useSkin( $this->mOptions
->getSkin() );
4314 if( isset( $params['caption'] ) )
4315 $ig->setCaption( $params['caption'] );
4317 $lines = explode( "\n", $text );
4318 foreach ( $lines as $line ) {
4319 # match lines like these:
4320 # Image:someimage.jpg|This is some image
4322 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4324 if ( count( $matches ) == 0 ) {
4327 $tp = Title
::newFromText( $matches[1] );
4329 if( is_null( $nt ) ) {
4330 # Bogus title. Ignore these so we don't bomb out later.
4333 if ( isset( $matches[3] ) ) {
4334 $label = $matches[3];
4339 $pout = $this->parse( $label,
4342 false, // Strip whitespace...?
4343 false // Don't clear state!
4345 $html = $pout->getText();
4347 $ig->add( new Image( $nt ), $html );
4349 # Only add real images (bug #5586)
4350 if ( $nt->getNamespace() == NS_IMAGE
) {
4351 $this->mOutput
->addImage( $nt->getDBkey() );
4354 return $ig->toHTML();
4358 * Parse image options text and use it to make an image
4360 function makeImage( $nt, $options ) {
4361 global $wgUseImageResize, $wgDjvuRenderer;
4365 # Check if the options text is of the form "options|alt text"
4367 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4368 # * left no resizing, just left align. label is used for alt= only
4369 # * right same, but right aligned
4370 # * none same, but not aligned
4371 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4372 # * center center the image
4373 # * framed Keep original image size, no magnify-button.
4375 $part = explode( '|', $options);
4377 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4378 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4379 $mwLeft =& MagicWord
::get( 'img_left' );
4380 $mwRight =& MagicWord
::get( 'img_right' );
4381 $mwNone =& MagicWord
::get( 'img_none' );
4382 $mwWidth =& MagicWord
::get( 'img_width' );
4383 $mwCenter =& MagicWord
::get( 'img_center' );
4384 $mwFramed =& MagicWord
::get( 'img_framed' );
4385 $mwPage =& MagicWord
::get( 'img_page' );
4388 $width = $height = $framed = $thumb = false;
4390 $manual_thumb = '' ;
4392 foreach( $part as $val ) {
4393 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4395 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4396 # use manually specified thumbnail
4398 $manual_thumb = $match;
4399 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4400 # remember to set an alignment, don't render immediately
4402 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4403 # remember to set an alignment, don't render immediately
4405 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4406 # remember to set an alignment, don't render immediately
4408 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4409 # remember to set an alignment, don't render immediately
4411 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4412 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4413 # Select a page in a multipage document
4415 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4416 wfDebug( "img_width match: $match\n" );
4417 # $match is the image width in pixels
4419 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4420 $width = intval( $m[1] );
4421 $height = intval( $m[2] );
4423 $width = intval($match);
4425 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4431 # Strip bad stuff out of the alt text
4432 $alt = $this->replaceLinkHoldersText( $caption );
4434 # make sure there are no placeholders in thumbnail attributes
4435 # that are later expanded to html- so expand them now and
4437 $alt = $this->mStripState
->unstripBoth( $alt );
4438 $alt = Sanitizer
::stripAllTags( $alt );
4440 # Linker does the rest
4441 $sk =& $this->mOptions
->getSkin();
4442 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4446 * Set a flag in the output object indicating that the content is dynamic and
4447 * shouldn't be cached.
4449 function disableCache() {
4450 wfDebug( "Parser output marked as uncacheable.\n" );
4451 $this->mOutput
->mCacheTime
= -1;
4455 * Callback from the Sanitizer for expanding items found in HTML attribute
4456 * values, so they can be safely tested and escaped.
4457 * @param string $text
4458 * @param array $args
4462 function attributeStripCallback( &$text, $args ) {
4463 $text = $this->replaceVariables( $text, $args );
4464 $text = $this->mStripState
->unstripBoth( $text );
4473 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4474 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4475 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4481 function getTags() { return array_keys( $this->mTagHooks
); }
4486 * Break wikitext input into sections, and either pull or replace
4487 * some particular section's text.
4489 * External callers should use the getSection and replaceSection methods.
4491 * @param $text Page wikitext
4492 * @param $section Numbered section. 0 pulls the text before the first
4493 * heading; other numbers will pull the given section
4494 * along with its lower-level subsections.
4495 * @param $mode One of "get" or "replace"
4496 * @param $newtext Replacement text for section data.
4497 * @return string for "get", the extracted section text.
4498 * for "replace", the whole page with the section replaced.
4500 private function extractSections( $text, $section, $mode, $newtext='' ) {
4501 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4502 # comments to be stripped as well)
4503 $stripState = new StripState
;
4505 $oldOutputType = $this->mOutputType
;
4506 $oldOptions = $this->mOptions
;
4507 $this->mOptions
= new ParserOptions();
4508 $this->setOutputType( OT_WIKI
);
4510 $striptext = $this->strip( $text, $stripState, true );
4512 $this->setOutputType( $oldOutputType );
4513 $this->mOptions
= $oldOptions;
4515 # now that we can be sure that no pseudo-sections are in the source,
4516 # split it up by section
4517 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4518 $comment = "(?:$uniq-!--.*?QINU)";
4523 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4525 (=+) # Should this be limited to 6?
4526 .+? # Section title...
4527 \\2 # Ending = count must match start
4534 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4541 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4542 (=+) # Should this be limited to 6?
4543 .+? # Section title...
4544 \\2 # Ending = count must match start
4545 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4554 PREG_SPLIT_DELIM_CAPTURE
);
4556 if( $mode == "get" ) {
4557 if( $section == 0 ) {
4558 // "Section 0" returns the content before any other section.
4563 } elseif( $mode == "replace" ) {
4564 if( $section == 0 ) {
4565 $rv = $newtext . "\n\n";
4574 for( $index = 1; $index < count( $secs ); ) {
4575 $headerLine = $secs[$index++
];
4576 if( $secs[$index] ) {
4578 $headerLevel = strlen( $secs[$index++
] );
4582 $headerLevel = intval( $secs[$index++
] );
4584 $content = $secs[$index++
];
4587 if( $mode == "get" ) {
4588 if( $count == $section ) {
4589 $rv = $headerLine . $content;
4590 $sectionLevel = $headerLevel;
4591 } elseif( $count > $section ) {
4592 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4593 $rv .= $headerLine . $content;
4595 // Broke out to a higher-level section
4599 } elseif( $mode == "replace" ) {
4600 if( $count < $section ) {
4601 $rv .= $headerLine . $content;
4602 } elseif( $count == $section ) {
4603 $rv .= $newtext . "\n\n";
4604 $sectionLevel = $headerLevel;
4605 } elseif( $count > $section ) {
4606 if( $headerLevel <= $sectionLevel ) {
4607 // Passed the section's sub-parts.
4611 $rv .= $headerLine . $content;
4616 # reinsert stripped tags
4617 $rv = trim( $stripState->unstripBoth( $rv ) );
4622 * This function returns the text of a section, specified by a number ($section).
4623 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4624 * the first section before any such heading (section 0).
4626 * If a section contains subsections, these are also returned.
4628 * @param $text String: text to look in
4629 * @param $section Integer: section number
4630 * @return string text of the requested section
4632 function getSection( $text, $section ) {
4633 return $this->extractSections( $text, $section, "get" );
4636 function replaceSection( $oldtext, $section, $text ) {
4637 return $this->extractSections( $oldtext, $section, "replace", $text );
4641 * Get the timestamp associated with the current revision, adjusted for
4642 * the default server-local timestamp
4644 function getRevisionTimestamp() {
4645 if ( is_null( $this->mRevisionTimestamp
) ) {
4646 wfProfileIn( __METHOD__
);
4648 $dbr =& wfGetDB( DB_SLAVE
);
4649 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4650 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4652 // Normalize timestamp to internal MW format for timezone processing.
4653 // This has the added side-effect of replacing a null value with
4654 // the current time, which gives us more sensible behavior for
4656 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4658 // The cryptic '' timezone parameter tells to use the site-default
4659 // timezone offset instead of the user settings.
4661 // Since this value will be saved into the parser cache, served
4662 // to other users, and potentially even used inside links and such,
4663 // it needs to be consistent for all visitors.
4664 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4666 wfProfileOut( __METHOD__
);
4668 return $this->mRevisionTimestamp
;
4674 * @package MediaWiki
4678 var $mText, # The output text
4679 $mLanguageLinks, # List of the full text of language links, in the order they appear
4680 $mCategories, # Map of category names to sort keys
4681 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4682 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4683 $mVersion, # Compatibility check
4684 $mTitleText, # title text of the chosen language variant
4685 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4686 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4687 $mImages, # DB keys of the images used, in the array key only
4688 $mExternalLinks, # External link URLs, in the key only
4689 $mHTMLtitle, # Display HTML title
4690 $mSubtitle, # Additional subtitle
4691 $mNewSection, # Show a new section link?
4692 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4694 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4695 $containsOldMagic = false, $titletext = '' )
4697 $this->mText
= $text;
4698 $this->mLanguageLinks
= $languageLinks;
4699 $this->mCategories
= $categoryLinks;
4700 $this->mContainsOldMagic
= $containsOldMagic;
4701 $this->mCacheTime
= '';
4702 $this->mVersion
= MW_PARSER_VERSION
;
4703 $this->mTitleText
= $titletext;
4704 $this->mLinks
= array();
4705 $this->mTemplates
= array();
4706 $this->mImages
= array();
4707 $this->mExternalLinks
= array();
4708 $this->mHTMLtitle
= "" ;
4709 $this->mSubtitle
= "" ;
4710 $this->mNewSection
= false;
4711 $this->mNoGallery
= false;
4714 function getText() { return $this->mText
; }
4715 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4716 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4717 function &getCategories() { return $this->mCategories
; }
4718 function getCacheTime() { return $this->mCacheTime
; }
4719 function getTitleText() { return $this->mTitleText
; }
4720 function &getLinks() { return $this->mLinks
; }
4721 function &getTemplates() { return $this->mTemplates
; }
4722 function &getImages() { return $this->mImages
; }
4723 function &getExternalLinks() { return $this->mExternalLinks
; }
4724 function getNoGallery() { return $this->mNoGallery
; }
4725 function getSubtitle() { return $this->mSubtitle
; }
4727 function containsOldMagic() { return $this->mContainsOldMagic
; }
4728 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4729 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4730 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4731 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4732 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4733 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4734 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4736 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4737 function addImage( $name ) { $this->mImages
[$name] = 1; }
4738 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4739 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4741 function setNewSection( $value ) {
4742 $this->mNewSection
= (bool)$value;
4744 function getNewSection() {
4745 return (bool)$this->mNewSection
;
4748 function addLink( $title, $id = null ) {
4749 $ns = $title->getNamespace();
4750 $dbk = $title->getDBkey();
4751 if ( !isset( $this->mLinks
[$ns] ) ) {
4752 $this->mLinks
[$ns] = array();
4754 if ( is_null( $id ) ) {
4755 $id = $title->getArticleID();
4757 $this->mLinks
[$ns][$dbk] = $id;
4760 function addTemplate( $title, $id ) {
4761 $ns = $title->getNamespace();
4762 $dbk = $title->getDBkey();
4763 if ( !isset( $this->mTemplates
[$ns] ) ) {
4764 $this->mTemplates
[$ns] = array();
4766 $this->mTemplates
[$ns][$dbk] = $id;
4770 * Return true if this cached output object predates the global or
4771 * per-article cache invalidation timestamps, or if it comes from
4772 * an incompatible older version.
4774 * @param string $touched the affected article's last touched timestamp
4778 function expired( $touched ) {
4779 global $wgCacheEpoch;
4780 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4781 $this->getCacheTime() < $touched ||
4782 $this->getCacheTime() <= $wgCacheEpoch ||
4783 !isset( $this->mVersion
) ||
4784 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4789 * Set options of the Parser
4791 * @package MediaWiki
4795 # All variables are supposed to be private in theory, although in practise this is not the case.
4796 var $mUseTeX; # Use texvc to expand <math> tags
4797 var $mUseDynamicDates; # Use DateFormatter to format dates
4798 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4799 var $mAllowExternalImages; # Allow external images inline
4800 var $mAllowExternalImagesFrom; # If not, any exception?
4801 var $mSkin; # Reference to the preferred skin
4802 var $mDateFormat; # Date format index
4803 var $mEditSection; # Create "edit section" links
4804 var $mNumberHeadings; # Automatically number headings
4805 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4806 var $mTidy; # Ask for tidy cleanup
4807 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4808 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4809 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4811 var $mUser; # Stored user object, just used to initialise the skin
4813 function getUseTeX() { return $this->mUseTeX
; }
4814 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4815 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4816 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4817 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4818 function getEditSection() { return $this->mEditSection
; }
4819 function getNumberHeadings() { return $this->mNumberHeadings
; }
4820 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4821 function getTidy() { return $this->mTidy
; }
4822 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4823 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4824 function getRemoveComments() { return $this->mRemoveComments
; }
4826 function &getSkin() {
4827 if ( !isset( $this->mSkin
) ) {
4828 $this->mSkin
= $this->mUser
->getSkin();
4830 return $this->mSkin
;
4833 function getDateFormat() {
4834 if ( !isset( $this->mDateFormat
) ) {
4835 $this->mDateFormat
= $this->mUser
->getDatePreference();
4837 return $this->mDateFormat
;
4840 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4841 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4842 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4843 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4844 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4845 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4846 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4847 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4848 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4849 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4850 function setSkin( $x ) { $this->mSkin
= $x; }
4851 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4852 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4853 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4855 function ParserOptions( $user = null ) {
4856 $this->initialiseFromUser( $user );
4860 * Get parser options
4863 static function newFromUser( $user ) {
4864 return new ParserOptions( $user );
4867 /** Get user options */
4868 function initialiseFromUser( $userInput ) {
4869 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4870 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4871 $fname = 'ParserOptions::initialiseFromUser';
4872 wfProfileIn( $fname );
4873 if ( !$userInput ) {
4875 if ( isset( $wgUser ) ) {
4881 $user =& $userInput;
4884 $this->mUser
= $user;
4886 $this->mUseTeX
= $wgUseTeX;
4887 $this->mUseDynamicDates
= $wgUseDynamicDates;
4888 $this->mInterwikiMagic
= $wgInterwikiMagic;
4889 $this->mAllowExternalImages
= $wgAllowExternalImages;
4890 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4891 $this->mSkin
= null; # Deferred
4892 $this->mDateFormat
= null; # Deferred
4893 $this->mEditSection
= true;
4894 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4895 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4896 $this->mTidy
= false;
4897 $this->mInterfaceMessage
= false;
4898 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4899 $this->mRemoveComments
= true;
4900 wfProfileOut( $fname );
4904 class OnlyIncludeReplacer
{
4907 function replace( $matches ) {
4908 if ( substr( $matches[1], -1 ) == "\n" ) {
4909 $this->output
.= substr( $matches[1], 0, -1 );
4911 $this->output
.= $matches[1];
4917 var $general, $nowiki;
4919 function __construct() {
4920 $this->general
= new ReplacementArray
;
4921 $this->nowiki
= new ReplacementArray
;
4924 function unstripGeneral( $text ) {
4925 wfProfileIn( __METHOD__
);
4926 $text = $this->general
->replace( $text );
4927 wfProfileOut( __METHOD__
);
4931 function unstripNoWiki( $text ) {
4932 wfProfileIn( __METHOD__
);
4933 $text = $this->nowiki
->replace( $text );
4934 wfProfileOut( __METHOD__
);
4938 function unstripBoth( $text ) {
4939 wfProfileIn( __METHOD__
);
4940 $text = $this->general
->replace( $text );
4941 $text = $this->nowiki
->replace( $text );
4942 wfProfileOut( __METHOD__
);