5 * File for Parser and related classes
11 * Update this version number when the ParserOutput format
12 * changes in an incompatible way, so the parser cache
13 * can automatically discard old data.
15 define( 'MW_PARSER_VERSION', '1.6.1' );
17 define( 'RLH_FOR_UPDATE', 1 );
19 # Allowed values for $mOutputType
20 define( 'OT_HTML', 1 );
21 define( 'OT_WIKI', 2 );
22 define( 'OT_MSG' , 3 );
23 define( 'OT_PREPROCESS', 4 );
25 # Flags for setFunctionHook
26 define( 'SFH_NO_HASH', 1 );
28 # string parameter for extractTags which will cause it
29 # to strip HTML comments in addition to regular
30 # <XML>-style tags. This should not be anything we
31 # may want to use in wikisyntax
32 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
34 # Constants needed for external link processing
35 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
36 # Everything except bracket, space, or control characters
37 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
38 # Including space, but excluding newlines
39 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
40 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
41 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
42 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
43 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
44 define( 'EXT_IMAGE_REGEX',
45 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
46 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
47 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
50 // State constants for the definition list colon extraction
51 define( 'MW_COLON_STATE_TEXT', 0 );
52 define( 'MW_COLON_STATE_TAG', 1 );
53 define( 'MW_COLON_STATE_TAGSTART', 2 );
54 define( 'MW_COLON_STATE_CLOSETAG', 3 );
55 define( 'MW_COLON_STATE_TAGSLASH', 4 );
56 define( 'MW_COLON_STATE_COMMENT', 5 );
57 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
58 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
61 * PHP Parser - Processes wiki markup (which uses a more user-friendly
62 * syntax, such as "[[link]]" for making links), and provides a one-way
63 * transformation of that wiki markup it into XHTML output / markup
64 * (which in turn the browser understands, and can display).
67 * There are four main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
75 * removes HTML comments and expands templates
78 * objects: $wgLang, $wgContLang
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
85 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
88 * * only within ParserOptions
95 const VERSION
= MW_PARSER_VERSION
;
100 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
102 # Cleared with clearState():
103 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
104 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
106 var $mIncludeSizes, $mDefaultSort;
107 var $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
113 # These are variables reset at least once per parse regardless of $clearState
114 var $mOptions, // ParserOptions object
115 $mTitle, // Title context, used for self-link rendering and similar things
116 $mOutputType, // Output type, one of the OT_xxx constants
117 $ot, // Shortcut alias, see setOutputType()
118 $mRevisionId, // ID to display in {{REVISIONID}} tags
119 $mRevisionTimestamp, // The timestamp of the specified revision ID
120 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
130 $this->mTagHooks
= array();
131 $this->mFunctionHooks
= array();
132 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
133 $this->mFirstCall
= true;
137 * Do various kinds of initialisation on the first call of the parser
139 function firstCallInit() {
140 if ( !$this->mFirstCall
) {
144 wfProfileIn( __METHOD__
);
145 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
147 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
149 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
174 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
176 if ( $wgAllowDisplayTitle ) {
177 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
179 if ( $wgAllowSlowParserFunctions ) {
180 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
183 $this->initialiseVariables();
184 $this->mFirstCall
= false;
185 wfProfileOut( __METHOD__
);
193 function clearState() {
194 wfProfileIn( __METHOD__
);
195 if ( $this->mFirstCall
) {
196 $this->firstCallInit();
198 $this->mOutput
= new ParserOutput
;
199 $this->mAutonumber
= 0;
200 $this->mLastSection
= '';
201 $this->mDTopen
= false;
202 $this->mIncludeCount
= array();
203 $this->mStripState
= new StripState
;
204 $this->mArgStack
= array();
205 $this->mInPre
= false;
206 $this->mInterwikiLinkHolders
= array(
210 $this->mLinkHolders
= array(
211 'namespaces' => array(),
213 'queries' => array(),
217 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
220 * Prefix for temporary replacement strings for the multipass parser.
221 * \x07 should never appear in input as it's disallowed in XML.
222 * Using it at the front also gives us a little extra robustness
223 * since it shouldn't match when butted up against identifier-like
226 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
228 # Clear these on every parse, bug 4549
229 $this->mTemplates
= array();
230 $this->mTemplatePath
= array();
232 $this->mShowToc
= true;
233 $this->mForceTocPosition
= false;
234 $this->mIncludeSizes
= array(
239 $this->mDefaultSort
= false;
241 wfRunHooks( 'ParserClearState', array( &$this ) );
242 wfProfileOut( __METHOD__
);
245 function setOutputType( $ot ) {
246 $this->mOutputType
= $ot;
249 'html' => $ot == OT_HTML
,
250 'wiki' => $ot == OT_WIKI
,
251 'msg' => $ot == OT_MSG
,
252 'pre' => $ot == OT_PREPROCESS
,
257 * Accessor for mUniqPrefix.
261 function uniqPrefix() {
262 return $this->mUniqPrefix
;
266 * Convert wikitext to HTML
267 * Do not call this function recursively.
269 * @param string $text Text we want to parse
270 * @param Title &$title A title object
271 * @param array $options
272 * @param boolean $linestart
273 * @param boolean $clearState
274 * @param int $revid number to pass in {{REVISIONID}}
275 * @return ParserOutput a ParserOutput
277 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
279 * First pass--just handle <nowiki> sections, pass the rest off
280 * to internalParse() which does all the real work.
283 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
284 $fname = 'Parser::parse-' . wfGetCaller();
285 wfProfileIn( __METHOD__
);
286 wfProfileIn( $fname );
292 $this->mOptions
= $options;
293 $this->mTitle
=& $title;
294 $oldRevisionId = $this->mRevisionId
;
295 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
296 if( $revid !== null ) {
297 $this->mRevisionId
= $revid;
298 $this->mRevisionTimestamp
= null;
300 $this->setOutputType( OT_HTML
);
301 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
302 $text = $this->strip( $text, $this->mStripState
);
303 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
304 $text = $this->internalParse( $text );
305 $text = $this->mStripState
->unstripGeneral( $text );
307 # Clean up special characters, only run once, next-to-last before doBlockLevels
309 # french spaces, last one Guillemet-left
310 # only if there is something before the space
311 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
312 # french spaces, Guillemet-right
313 '/(\\302\\253) /' => '\\1 ',
315 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
318 $text = $this->doBlockLevels( $text, $linestart );
320 $this->replaceLinkHolders( $text );
322 # the position of the parserConvert() call should not be changed. it
323 # assumes that the links are all replaced and the only thing left
324 # is the <nowiki> mark.
325 # Side-effects: this calls $this->mOutput->setTitleText()
326 $text = $wgContLang->parserConvert( $text, $this );
328 $text = $this->mStripState
->unstripNoWiki( $text );
330 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
332 $text = Sanitizer
::normalizeCharReferences( $text );
334 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
335 $text = Parser
::tidy($text);
337 # attempt to sanitize at least some nesting problems
338 # (bug #2702 and quite a few others)
340 # ''Something [http://www.cool.com cool''] -->
341 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
342 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
343 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
344 # fix up an anchor inside another anchor, only
345 # at least for a single single nested link (bug 3695)
346 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
347 '\\1\\2</a>\\3</a>\\1\\4</a>',
348 # fix div inside inline elements- doBlockLevels won't wrap a line which
349 # contains a div, so fix it up here; replace
350 # div with escaped text
351 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
352 '\\1\\3<div\\5>\\6</div>\\8\\9',
353 # remove empty italic or bold tag pairs, some
354 # introduced by rules above
355 '/<([bi])><\/\\1>/' => '',
358 $text = preg_replace(
359 array_keys( $tidyregs ),
360 array_values( $tidyregs ),
364 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
366 # Information on include size limits, for the benefit of users who try to skirt them
367 if ( max( $this->mIncludeSizes
) > 1000 ) {
368 $max = $this->mOptions
->getMaxIncludeSize();
370 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
371 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
372 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
373 "Maximum: $max bytes\n" .
376 $this->mOutput
->setText( $text );
377 $this->mRevisionId
= $oldRevisionId;
378 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
379 wfProfileOut( $fname );
380 wfProfileOut( __METHOD__
);
382 return $this->mOutput
;
386 * Recursive parser entry point that can be called from an extension tag
389 function recursiveTagParse( $text ) {
390 wfProfileIn( __METHOD__
);
391 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
392 $text = $this->strip( $text, $this->mStripState
);
393 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
394 $text = $this->internalParse( $text );
395 wfProfileOut( __METHOD__
);
400 * Expand templates and variables in the text, producing valid, static wikitext.
401 * Also removes comments.
403 function preprocess( $text, $title, $options ) {
404 wfProfileIn( __METHOD__
);
406 $this->setOutputType( OT_PREPROCESS
);
407 $this->mOptions
= $options;
408 $this->mTitle
= $title;
409 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
410 $text = $this->strip( $text, $this->mStripState
);
411 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
412 if ( $this->mOptions
->getRemoveComments() ) {
413 $text = Sanitizer
::removeHTMLcomments( $text );
415 $text = $this->replaceVariables( $text );
416 $text = $this->mStripState
->unstripBoth( $text );
417 wfProfileOut( __METHOD__
);
422 * Get a random string
427 function getRandomString() {
428 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
431 function &getTitle() { return $this->mTitle
; }
432 function getOptions() { return $this->mOptions
; }
434 function getFunctionLang() {
435 global $wgLang, $wgContLang;
436 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
440 * Replaces all occurrences of HTML-style comments and the given tags
441 * in the text with a random marker and returns teh next text. The output
442 * parameter $matches will be an associative array filled with data in
444 * 'UNIQ-xxxxx' => array(
447 * array( 'param' => 'x' ),
448 * '<element param="x">tag content</element>' ) )
450 * @param $elements list of element names. Comments are always extracted.
451 * @param $text Source text string.
452 * @param $uniq_prefix
457 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
462 $taglist = implode( '|', $elements );
463 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
465 while ( '' != $text ) {
466 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
468 if( count( $p ) < 5 ) {
471 if( count( $p ) > 5 ) {
485 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
486 $stripped .= $marker;
488 if ( $close === '/>' ) {
489 // Empty element tag, <tag />
494 if( $element == '!--' ) {
497 $end = "/(<\\/$element\\s*>)/i";
499 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
501 if( count( $q ) < 3 ) {
502 # No end tag -- let it run out to the end of the text.
511 $matches[$marker] = array( $element,
513 Sanitizer
::decodeTagAttributes( $attributes ),
514 "<$element$attributes$close$content$tail" );
520 * Strips and renders nowiki, pre, math, hiero
521 * If $render is set, performs necessary rendering operations on plugins
522 * Returns the text, and fills an array with data needed in unstrip()
524 * @param StripState $state
526 * @param bool $stripcomments when set, HTML comments <!-- like this -->
527 * will be stripped in addition to other tags. This is important
528 * for section editing, where these comments cause confusion when
529 * counting the sections in the wikisource
531 * @param array dontstrip contains tags which should not be stripped;
532 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
536 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
538 wfProfileIn( __METHOD__
);
539 $render = ($this->mOutputType
== OT_HTML
);
541 $uniq_prefix = $this->mUniqPrefix
;
542 $commentState = new ReplacementArray
;
543 $nowikiItems = array();
544 $generalItems = array();
546 $elements = array_merge(
547 array( 'nowiki', 'gallery' ),
548 array_keys( $this->mTagHooks
) );
551 $elements[] = 'html';
553 if( $this->mOptions
->getUseTeX() ) {
554 $elements[] = 'math';
557 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
558 foreach ( $elements AS $k => $v ) {
559 if ( !in_array ( $v , $dontstrip ) ) continue;
560 unset ( $elements[$k] );
564 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
566 foreach( $matches as $marker => $data ) {
567 list( $element, $content, $params, $tag ) = $data;
569 $tagName = strtolower( $element );
570 wfProfileIn( __METHOD__
."-render-$tagName" );
574 if( substr( $tag, -3 ) == '-->' ) {
577 // Unclosed comment in input.
578 // Close it so later stripping can remove it
587 // Shouldn't happen otherwise. :)
589 $output = Xml
::escapeTagsOnly( $content );
592 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
595 $output = $this->renderImageGallery( $content, $params );
598 if( isset( $this->mTagHooks
[$tagName] ) ) {
599 $output = call_user_func_array( $this->mTagHooks
[$tagName],
600 array( $content, $params, $this ) );
602 throw new MWException( "Invalid call hook $element" );
605 wfProfileOut( __METHOD__
."-render-$tagName" );
607 // Just stripping tags; keep the source
611 // Unstrip the output, to support recursive strip() calls
612 $output = $state->unstripBoth( $output );
614 if( !$stripcomments && $element == '!--' ) {
615 $commentState->setPair( $marker, $output );
616 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
617 $nowikiItems[$marker] = $output;
619 $generalItems[$marker] = $output;
622 # Add the new items to the state
623 # We do this after the loop instead of during it to avoid slowing
624 # down the recursive unstrip
625 $state->nowiki
->mergeArray( $nowikiItems );
626 $state->general
->mergeArray( $generalItems );
628 # Unstrip comments unless explicitly told otherwise.
629 # (The comments are always stripped prior to this point, so as to
630 # not invoke any extension tags / parser hooks contained within
632 if ( !$stripcomments ) {
633 // Put them all back and forget them
634 $text = $commentState->replace( $text );
637 wfProfileOut( __METHOD__
);
642 * Restores pre, math, and other extensions removed by strip()
644 * always call unstripNoWiki() after this one
646 * @deprecated use $this->mStripState->unstrip()
648 function unstrip( $text, $state ) {
649 return $state->unstripGeneral( $text );
653 * Always call this after unstrip() to preserve the order
656 * @deprecated use $this->mStripState->unstrip()
658 function unstripNoWiki( $text, $state ) {
659 return $state->unstripNoWiki( $text );
663 * @deprecated use $this->mStripState->unstripBoth()
665 function unstripForHTML( $text ) {
666 return $this->mStripState
->unstripBoth( $text );
670 * Add an item to the strip state
671 * Returns the unique tag which must be inserted into the stripped text
672 * The tag will be replaced with the original text in unstrip()
676 function insertStripItem( $text, &$state ) {
677 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
678 $state->general
->setPair( $rnd, $text );
683 * Interface with html tidy, used if $wgUseTidy = true.
684 * If tidy isn't able to correct the markup, the original will be
685 * returned in all its glory with a warning comment appended.
687 * Either the external tidy program or the in-process tidy extension
688 * will be used depending on availability. Override the default
689 * $wgTidyInternal setting to disable the internal if it's not working.
691 * @param string $text Hideous HTML input
692 * @return string Corrected HTML output
696 function tidy( $text ) {
697 global $wgTidyInternal;
698 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
699 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
700 '<head><title>test</title></head><body>'.$text.'</body></html>';
701 if( $wgTidyInternal ) {
702 $correctedtext = Parser
::internalTidy( $wrappedtext );
704 $correctedtext = Parser
::externalTidy( $wrappedtext );
706 if( is_null( $correctedtext ) ) {
707 wfDebug( "Tidy error detected!\n" );
708 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
710 return $correctedtext;
714 * Spawn an external HTML tidy process and get corrected markup back from it.
719 function externalTidy( $text ) {
720 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
721 $fname = 'Parser::externalTidy';
722 wfProfileIn( $fname );
727 $descriptorspec = array(
728 0 => array('pipe', 'r'),
729 1 => array('pipe', 'w'),
730 2 => array('file', '/dev/null', 'a') // FIXME: this line in UNIX-specific, it generates a warning on Windows, because /dev/null is not a valid Windows file.
733 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
734 if (is_resource($process)) {
735 // Theoretically, this style of communication could cause a deadlock
736 // here. If the stdout buffer fills up, then writes to stdin could
737 // block. This doesn't appear to happen with tidy, because tidy only
738 // writes to stdout after it's finished reading from stdin. Search
739 // for tidyParseStdin and tidySaveStdout in console/tidy.c
740 fwrite($pipes[0], $text);
742 while (!feof($pipes[1])) {
743 $cleansource .= fgets($pipes[1], 1024);
746 proc_close($process);
749 wfProfileOut( $fname );
751 if( $cleansource == '' && $text != '') {
752 // Some kind of error happened, so we couldn't get the corrected text.
753 // Just give up; we'll use the source text and append a warning.
761 * Use the HTML tidy PECL extension to use the tidy library in-process,
762 * saving the overhead of spawning a new process. Currently written to
763 * the PHP 4.3.x version of the extension, may not work on PHP 5.
765 * 'pear install tidy' should be able to compile the extension module.
770 function internalTidy( $text ) {
772 $fname = 'Parser::internalTidy';
773 wfProfileIn( $fname );
775 tidy_load_config( $wgTidyConf );
776 tidy_set_encoding( 'utf8' );
777 tidy_parse_string( $text );
779 if( tidy_get_status() == 2 ) {
780 // 2 is magic number for fatal error
781 // http://www.php.net/manual/en/function.tidy-get-status.php
784 $cleansource = tidy_get_output();
786 wfProfileOut( $fname );
791 * parse the wiki syntax used to render tables
795 function doTableStuff ( $text ) {
796 $fname = 'Parser::doTableStuff';
797 wfProfileIn( $fname );
799 $lines = explode ( "\n" , $text );
800 $td_history = array (); // Is currently a td tag open?
801 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
802 $tr_history = array (); // Is currently a tr tag open?
803 $tr_attributes = array (); // history of tr attributes
804 $has_opened_tr = array(); // Did this table open a <tr> element?
805 $indent_level = 0; // indent level of the table
806 foreach ( $lines as $key => $line )
808 $line = trim ( $line );
810 if( $line == '' ) { // empty line, go to next line
813 $first_character = $line{0};
816 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
817 // First check if we are starting a new table
818 $indent_level = strlen( $matches[1] );
820 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
821 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
823 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
824 array_push ( $td_history , false );
825 array_push ( $last_tag_history , '' );
826 array_push ( $tr_history , false );
827 array_push ( $tr_attributes , '' );
828 array_push ( $has_opened_tr , false );
829 } else if ( count ( $td_history ) == 0 ) {
830 // Don't do any of the following
832 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
833 // We are ending a table
834 $line = '</table>' . substr ( $line , 2 );
835 $last_tag = array_pop ( $last_tag_history );
837 if ( !array_pop ( $has_opened_tr ) ) {
838 $line = "<tr><td></td></tr>{$line}";
841 if ( array_pop ( $tr_history ) ) {
842 $line = "</tr>{$line}";
845 if ( array_pop ( $td_history ) ) {
846 $line = "</{$last_tag}>{$line}";
848 array_pop ( $tr_attributes );
849 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
850 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
851 // Now we have a table row
852 $line = preg_replace( '#^\|-+#', '', $line );
854 // Whats after the tag is now only attributes
855 $attributes = $this->mStripState
->unstripBoth( $line );
856 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
857 array_pop ( $tr_attributes );
858 array_push ( $tr_attributes , $attributes );
861 $last_tag = array_pop ( $last_tag_history );
862 array_pop ( $has_opened_tr );
863 array_push ( $has_opened_tr , true );
865 if ( array_pop ( $tr_history ) ) {
869 if ( array_pop ( $td_history ) ) {
870 $line = "</{$last_tag}>{$line}";
873 $lines[$key] = $line;
874 array_push ( $tr_history , false );
875 array_push ( $td_history , false );
876 array_push ( $last_tag_history , '' );
878 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
879 // This might be cell elements, td, th or captions
880 if ( substr ( $line , 0 , 2 ) == '|+' ) {
881 $first_character = '+';
882 $line = substr ( $line , 1 );
885 $line = substr ( $line , 1 );
887 if ( $first_character == '!' ) {
888 $line = str_replace ( '!!' , '||' , $line );
891 // Split up multiple cells on the same line.
892 // FIXME : This can result in improper nesting of tags processed
893 // by earlier parser steps, but should avoid splitting up eg
894 // attribute values containing literal "||".
895 $cells = StringUtils
::explodeMarkup( '||' , $line );
899 // Loop through each table cell
900 foreach ( $cells as $cell )
903 if ( $first_character != '+' )
905 $tr_after = array_pop ( $tr_attributes );
906 if ( !array_pop ( $tr_history ) ) {
907 $previous = "<tr{$tr_after}>\n";
909 array_push ( $tr_history , true );
910 array_push ( $tr_attributes , '' );
911 array_pop ( $has_opened_tr );
912 array_push ( $has_opened_tr , true );
915 $last_tag = array_pop ( $last_tag_history );
917 if ( array_pop ( $td_history ) ) {
918 $previous = "</{$last_tag}>{$previous}";
921 if ( $first_character == '|' ) {
923 } else if ( $first_character == '!' ) {
925 } else if ( $first_character == '+' ) {
926 $last_tag = 'caption';
931 array_push ( $last_tag_history , $last_tag );
933 // A cell could contain both parameters and data
934 $cell_data = explode ( '|' , $cell , 2 );
936 // Bug 553: Note that a '|' inside an invalid link should not
937 // be mistaken as delimiting cell parameters
938 if ( strpos( $cell_data[0], '[[' ) !== false ) {
939 $cell = "{$previous}<{$last_tag}>{$cell}";
940 } else if ( count ( $cell_data ) == 1 )
941 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
943 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
944 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
945 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
948 $lines[$key] .= $cell;
949 array_push ( $td_history , true );
954 // Closing open td, tr && table
955 while ( count ( $td_history ) > 0 )
957 if ( array_pop ( $td_history ) ) {
960 if ( array_pop ( $tr_history ) ) {
963 if ( !array_pop ( $has_opened_tr ) ) {
964 $lines[] = "<tr><td></td></tr>" ;
967 $lines[] = '</table>' ;
970 $output = implode ( "\n" , $lines ) ;
972 // special case: don't return empty table
973 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
977 wfProfileOut( $fname );
983 * Helper function for parse() that transforms wiki markup into
984 * HTML. Only called for $mOutputType == OT_HTML.
988 function internalParse( $text ) {
991 $fname = 'Parser::internalParse';
992 wfProfileIn( $fname );
994 # Hook to suspend the parser in this state
995 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
996 wfProfileOut( $fname );
1000 # Remove <noinclude> tags and <includeonly> sections
1001 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
1002 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1003 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1005 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1007 $text = $this->replaceVariables( $text, $args );
1008 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1010 // Tables need to come after variable replacement for things to work
1011 // properly; putting them before other transformations should keep
1012 // exciting things like link expansions from showing up in surprising
1014 $text = $this->doTableStuff( $text );
1016 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1018 $text = $this->stripToc( $text );
1019 $this->stripNoGallery( $text );
1020 $text = $this->doHeadings( $text );
1021 if($this->mOptions
->getUseDynamicDates()) {
1022 $df =& DateFormatter
::getInstance();
1023 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1025 $text = $this->doAllQuotes( $text );
1026 $text = $this->replaceInternalLinks( $text );
1027 $text = $this->replaceExternalLinks( $text );
1029 # replaceInternalLinks may sometimes leave behind
1030 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1031 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1033 $text = $this->doMagicLinks( $text );
1034 $text = $this->formatHeadings( $text, $isMain );
1036 wfProfileOut( $fname );
1041 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1042 * magic external links.
1046 function &doMagicLinks( &$text ) {
1047 wfProfileIn( __METHOD__
);
1048 $text = preg_replace_callback(
1050 <a.*?</a> | # Skip link text
1051 <.*?> | # Skip stuff inside HTML elements
1052 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1053 ISBN\s+(\b # ISBN, capture number as m[2]
1054 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1055 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1056 [0-9Xx] # check digit
1058 )!x', array( &$this, 'magicLinkCallback' ), $text );
1059 wfProfileOut( __METHOD__
);
1063 function magicLinkCallback( $m ) {
1064 if ( substr( $m[0], 0, 1 ) == '<' ) {
1067 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1069 $num = strtr( $isbn, array(
1074 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1075 $text = '<a href="' .
1076 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1077 "\" class=\"internal\">ISBN $isbn</a>";
1079 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1083 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1085 $urlmsg = 'pubmedurl';
1088 throw new MWException( __METHOD__
.': unrecognised match type "' .
1089 substr($m[0], 0, 20 ) . '"' );
1092 $url = wfMsg( $urlmsg, $id);
1093 $sk = $this->mOptions
->getSkin();
1094 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1095 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1101 * Parse headers and return html
1105 function doHeadings( $text ) {
1106 $fname = 'Parser::doHeadings';
1107 wfProfileIn( $fname );
1108 for ( $i = 6; $i >= 1; --$i ) {
1109 $h = str_repeat( '=', $i );
1110 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1111 "<h{$i}>\\1</h{$i}>\\2", $text );
1113 wfProfileOut( $fname );
1118 * Replace single quotes with HTML markup
1120 * @return string the altered text
1122 function doAllQuotes( $text ) {
1123 $fname = 'Parser::doAllQuotes';
1124 wfProfileIn( $fname );
1126 $lines = explode( "\n", $text );
1127 foreach ( $lines as $line ) {
1128 $outtext .= $this->doQuotes ( $line ) . "\n";
1130 $outtext = substr($outtext, 0,-1);
1131 wfProfileOut( $fname );
1136 * Helper function for doAllQuotes()
1139 function doQuotes( $text ) {
1140 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1141 if ( count( $arr ) == 1 )
1145 # First, do some preliminary work. This may shift some apostrophes from
1146 # being mark-up to being text. It also counts the number of occurrences
1147 # of bold and italics mark-ups.
1151 foreach ( $arr as $r )
1153 if ( ( $i %
2 ) == 1 )
1155 # If there are ever four apostrophes, assume the first is supposed to
1156 # be text, and the remaining three constitute mark-up for bold text.
1157 if ( strlen( $arr[$i] ) == 4 )
1162 # If there are more than 5 apostrophes in a row, assume they're all
1163 # text except for the last 5.
1164 else if ( strlen( $arr[$i] ) > 5 )
1166 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1169 # Count the number of occurrences of bold and italics mark-ups.
1170 # We are not counting sequences of five apostrophes.
1171 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1172 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1173 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1178 # If there is an odd number of both bold and italics, it is likely
1179 # that one of the bold ones was meant to be an apostrophe followed
1180 # by italics. Which one we cannot know for certain, but it is more
1181 # likely to be one that has a single-letter word before it.
1182 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1185 $firstsingleletterword = -1;
1186 $firstmultiletterword = -1;
1188 foreach ( $arr as $r )
1190 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1192 $x1 = substr ($arr[$i-1], -1);
1193 $x2 = substr ($arr[$i-1], -2, 1);
1195 if ($firstspace == -1) $firstspace = $i;
1196 } else if ($x2 == ' ') {
1197 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1199 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1205 # If there is a single-letter word, use it!
1206 if ($firstsingleletterword > -1)
1208 $arr [ $firstsingleletterword ] = "''";
1209 $arr [ $firstsingleletterword-1 ] .= "'";
1211 # If not, but there's a multi-letter word, use that one.
1212 else if ($firstmultiletterword > -1)
1214 $arr [ $firstmultiletterword ] = "''";
1215 $arr [ $firstmultiletterword-1 ] .= "'";
1217 # ... otherwise use the first one that has neither.
1218 # (notice that it is possible for all three to be -1 if, for example,
1219 # there is only one pentuple-apostrophe in the line)
1220 else if ($firstspace > -1)
1222 $arr [ $firstspace ] = "''";
1223 $arr [ $firstspace-1 ] .= "'";
1227 # Now let's actually convert our apostrophic mush to HTML!
1232 foreach ($arr as $r)
1236 if ($state == 'both')
1243 if (strlen ($r) == 2)
1246 { $output .= '</i>'; $state = ''; }
1247 else if ($state == 'bi')
1248 { $output .= '</i>'; $state = 'b'; }
1249 else if ($state == 'ib')
1250 { $output .= '</b></i><b>'; $state = 'b'; }
1251 else if ($state == 'both')
1252 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1253 else # $state can be 'b' or ''
1254 { $output .= '<i>'; $state .= 'i'; }
1256 else if (strlen ($r) == 3)
1259 { $output .= '</b>'; $state = ''; }
1260 else if ($state == 'bi')
1261 { $output .= '</i></b><i>'; $state = 'i'; }
1262 else if ($state == 'ib')
1263 { $output .= '</b>'; $state = 'i'; }
1264 else if ($state == 'both')
1265 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1266 else # $state can be 'i' or ''
1267 { $output .= '<b>'; $state .= 'b'; }
1269 else if (strlen ($r) == 5)
1272 { $output .= '</b><i>'; $state = 'i'; }
1273 else if ($state == 'i')
1274 { $output .= '</i><b>'; $state = 'b'; }
1275 else if ($state == 'bi')
1276 { $output .= '</i></b>'; $state = ''; }
1277 else if ($state == 'ib')
1278 { $output .= '</b></i>'; $state = ''; }
1279 else if ($state == 'both')
1280 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1281 else # ($state == '')
1282 { $buffer = ''; $state = 'both'; }
1287 # Now close all remaining tags. Notice that the order is important.
1288 if ($state == 'b' ||
$state == 'ib')
1290 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1294 # There might be lonely ''''', so make sure we have a buffer
1295 if ($state == 'both' && $buffer)
1296 $output .= '<b><i>'.$buffer.'</i></b>';
1302 * Replace external links
1304 * Note: this is all very hackish and the order of execution matters a lot.
1305 * Make sure to run maintenance/parserTests.php if you change this code.
1309 function replaceExternalLinks( $text ) {
1311 $fname = 'Parser::replaceExternalLinks';
1312 wfProfileIn( $fname );
1314 $sk = $this->mOptions
->getSkin();
1316 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1318 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1321 while ( $i<count( $bits ) ) {
1323 $protocol = $bits[$i++
];
1324 $text = $bits[$i++
];
1325 $trail = $bits[$i++
];
1327 # The characters '<' and '>' (which were escaped by
1328 # removeHTMLtags()) should not be included in
1329 # URLs, per RFC 2396.
1331 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1332 $text = substr($url, $m2[0][1]) . ' ' . $text;
1333 $url = substr($url, 0, $m2[0][1]);
1336 # If the link text is an image URL, replace it with an <img> tag
1337 # This happened by accident in the original parser, but some people used it extensively
1338 $img = $this->maybeMakeExternalImage( $text );
1339 if ( $img !== false ) {
1345 # Set linktype for CSS - if URL==text, link is essentially free
1346 $linktype = ($text == $url) ?
'free' : 'text';
1348 # No link text, e.g. [http://domain.tld/some.link]
1349 if ( $text == '' ) {
1350 # Autonumber if allowed. See bug #5918
1351 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1352 $text = '[' . ++
$this->mAutonumber
. ']';
1353 $linktype = 'autonumber';
1355 # Otherwise just use the URL
1356 $text = htmlspecialchars( $url );
1360 # Have link text, e.g. [http://domain.tld/some.link text]s
1362 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1365 $text = $wgContLang->markNoConversion($text);
1367 $url = Sanitizer
::cleanUrl( $url );
1369 # Process the trail (i.e. everything after this link up until start of the next link),
1370 # replacing any non-bracketed links
1371 $trail = $this->replaceFreeExternalLinks( $trail );
1373 # Use the encoded URL
1374 # This means that users can paste URLs directly into the text
1375 # Funny characters like ö aren't valid in URLs anyway
1376 # This was changed in August 2004
1377 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1379 # Register link in the output object.
1380 # Replace unnecessary URL escape codes with the referenced character
1381 # This prevents spammers from hiding links from the filters
1382 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1383 $this->mOutput
->addExternalLink( $pasteurized );
1386 wfProfileOut( $fname );
1391 * Replace anything that looks like a URL with a link
1394 function replaceFreeExternalLinks( $text ) {
1396 $fname = 'Parser::replaceFreeExternalLinks';
1397 wfProfileIn( $fname );
1399 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1400 $s = array_shift( $bits );
1403 $sk = $this->mOptions
->getSkin();
1405 while ( $i < count( $bits ) ){
1406 $protocol = $bits[$i++
];
1407 $remainder = $bits[$i++
];
1410 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1411 # Found some characters after the protocol that look promising
1412 $url = $protocol . $m[1];
1415 # special case: handle urls as url args:
1416 # http://www.example.com/foo?=http://www.example.com/bar
1417 if(strlen($trail) == 0 &&
1419 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1420 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1423 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1428 # The characters '<' and '>' (which were escaped by
1429 # removeHTMLtags()) should not be included in
1430 # URLs, per RFC 2396.
1432 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1433 $trail = substr($url, $m2[0][1]) . $trail;
1434 $url = substr($url, 0, $m2[0][1]);
1437 # Move trailing punctuation to $trail
1439 # If there is no left bracket, then consider right brackets fair game too
1440 if ( strpos( $url, '(' ) === false ) {
1444 $numSepChars = strspn( strrev( $url ), $sep );
1445 if ( $numSepChars ) {
1446 $trail = substr( $url, -$numSepChars ) . $trail;
1447 $url = substr( $url, 0, -$numSepChars );
1450 $url = Sanitizer
::cleanUrl( $url );
1452 # Is this an external image?
1453 $text = $this->maybeMakeExternalImage( $url );
1454 if ( $text === false ) {
1455 # Not an image, make a link
1456 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1457 # Register it in the output object...
1458 # Replace unnecessary URL escape codes with their equivalent characters
1459 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1460 $this->mOutput
->addExternalLink( $pasteurized );
1462 $s .= $text . $trail;
1464 $s .= $protocol . $remainder;
1467 wfProfileOut( $fname );
1472 * Replace unusual URL escape codes with their equivalent characters
1476 * @todo This can merge genuinely required bits in the path or query string,
1477 * breaking legit URLs. A proper fix would treat the various parts of
1478 * the URL differently; as a workaround, just use the output for
1479 * statistical records, not for actual linking/output.
1481 static function replaceUnusualEscapes( $url ) {
1482 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1483 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1487 * Callback function used in replaceUnusualEscapes().
1488 * Replaces unusual URL escape codes with their equivalent character
1492 private static function replaceUnusualEscapesCallback( $matches ) {
1493 $char = urldecode( $matches[0] );
1494 $ord = ord( $char );
1495 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1496 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1497 // No, shouldn't be escaped
1500 // Yes, leave it escaped
1506 * make an image if it's allowed, either through the global
1507 * option or through the exception
1510 function maybeMakeExternalImage( $url ) {
1511 $sk = $this->mOptions
->getSkin();
1512 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1513 $imagesexception = !empty($imagesfrom);
1515 if ( $this->mOptions
->getAllowExternalImages()
1516 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1517 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1519 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1526 * Process [[ ]] wikilinks
1530 function replaceInternalLinks( $s ) {
1532 static $fname = 'Parser::replaceInternalLinks' ;
1534 wfProfileIn( $fname );
1536 wfProfileIn( $fname.'-setup' );
1538 # the % is needed to support urlencoded titles as well
1539 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1541 $sk = $this->mOptions
->getSkin();
1543 #split the entire text string on occurences of [[
1544 $a = explode( '[[', ' ' . $s );
1545 #get the first element (all text up to first [[), and remove the space we added
1546 $s = array_shift( $a );
1547 $s = substr( $s, 1 );
1549 # Match a link having the form [[namespace:link|alternate]]trail
1551 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1552 # Match cases where there is no "]]", which might still be images
1553 static $e1_img = FALSE;
1554 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1555 # Match the end of a line for a word that's not followed by whitespace,
1556 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1557 $e2 = wfMsgForContent( 'linkprefix' );
1559 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1560 if( is_null( $this->mTitle
) ) {
1561 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1563 $nottalk = !$this->mTitle
->isTalkPage();
1565 if ( $useLinkPrefixExtension ) {
1567 if ( preg_match( $e2, $s, $m ) ) {
1568 $first_prefix = $m[2];
1570 $first_prefix = false;
1576 if($wgContLang->hasVariants()) {
1577 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1579 $selflink = array($this->mTitle
->getPrefixedText());
1581 $useSubpages = $this->areSubpagesAllowed();
1582 wfProfileOut( $fname.'-setup' );
1584 # Loop for each link
1585 for ($k = 0; isset( $a[$k] ); $k++
) {
1587 if ( $useLinkPrefixExtension ) {
1588 wfProfileIn( $fname.'-prefixhandling' );
1589 if ( preg_match( $e2, $s, $m ) ) {
1597 $prefix = $first_prefix;
1598 $first_prefix = false;
1600 wfProfileOut( $fname.'-prefixhandling' );
1603 $might_be_img = false;
1605 wfProfileIn( "$fname-e1" );
1606 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1608 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1609 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1610 # the real problem is with the $e1 regex
1613 # Still some problems for cases where the ] is meant to be outside punctuation,
1614 # and no image is in sight. See bug 2095.
1617 substr( $m[3], 0, 1 ) === ']' &&
1618 strpos($text, '[') !== false
1621 $text .= ']'; # so that replaceExternalLinks($text) works later
1622 $m[3] = substr( $m[3], 1 );
1624 # fix up urlencoded title texts
1625 if( strpos( $m[1], '%' ) !== false ) {
1626 # Should anchors '#' also be rejected?
1627 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1630 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1631 $might_be_img = true;
1633 if ( strpos( $m[1], '%' ) !== false ) {
1634 $m[1] = urldecode($m[1]);
1637 } else { # Invalid form; output directly
1638 $s .= $prefix . '[[' . $line ;
1639 wfProfileOut( "$fname-e1" );
1642 wfProfileOut( "$fname-e1" );
1643 wfProfileIn( "$fname-misc" );
1645 # Don't allow internal links to pages containing
1646 # PROTO: where PROTO is a valid URL protocol; these
1647 # should be external links.
1648 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1649 $s .= $prefix . '[[' . $line ;
1653 # Make subpage if necessary
1654 if( $useSubpages ) {
1655 $link = $this->maybeDoSubpageLink( $m[1], $text );
1660 $noforce = (substr($m[1], 0, 1) != ':');
1662 # Strip off leading ':'
1663 $link = substr($link, 1);
1666 wfProfileOut( "$fname-misc" );
1667 wfProfileIn( "$fname-title" );
1668 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1670 $s .= $prefix . '[[' . $line;
1671 wfProfileOut( "$fname-title" );
1675 $ns = $nt->getNamespace();
1676 $iw = $nt->getInterWiki();
1677 wfProfileOut( "$fname-title" );
1679 if ($might_be_img) { # if this is actually an invalid link
1680 wfProfileIn( "$fname-might_be_img" );
1681 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1683 while (isset ($a[$k+
1]) ) {
1684 #look at the next 'line' to see if we can close it there
1685 $spliced = array_splice( $a, $k +
1, 1 );
1686 $next_line = array_shift( $spliced );
1687 $m = explode( ']]', $next_line, 3 );
1688 if ( count( $m ) == 3 ) {
1689 # the first ]] closes the inner link, the second the image
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1694 } elseif ( count( $m ) == 2 ) {
1695 #if there's exactly one ]] that's fine, we'll keep looking
1696 $text .= "[[{$m[0]}]]{$m[1]}";
1698 #if $next_line is invalid too, we need look no further
1699 $text .= '[[' . $next_line;
1704 # we couldn't find the end of this imageLink, so output it raw
1705 #but don't ignore what might be perfectly normal links in the text we've examined
1706 $text = $this->replaceInternalLinks($text);
1707 $s .= "{$prefix}[[$link|$text";
1708 # note: no $trail, because without an end, there *is* no trail
1709 wfProfileOut( "$fname-might_be_img" );
1712 } else { #it's not an image, so output it raw
1713 $s .= "{$prefix}[[$link|$text";
1714 # note: no $trail, because without an end, there *is* no trail
1715 wfProfileOut( "$fname-might_be_img" );
1718 wfProfileOut( "$fname-might_be_img" );
1721 $wasblank = ( '' == $text );
1722 if( $wasblank ) $text = $link;
1724 # Link not escaped by : , create the various objects
1728 wfProfileIn( "$fname-interwiki" );
1729 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1730 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1731 $s = rtrim($s . $prefix);
1732 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1733 wfProfileOut( "$fname-interwiki" );
1736 wfProfileOut( "$fname-interwiki" );
1738 if ( $ns == NS_IMAGE
) {
1739 wfProfileIn( "$fname-image" );
1740 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1741 # recursively parse links inside the image caption
1742 # actually, this will parse them in any other parameters, too,
1743 # but it might be hard to fix that, and it doesn't matter ATM
1744 $text = $this->replaceExternalLinks($text);
1745 $text = $this->replaceInternalLinks($text);
1747 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1748 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1749 $this->mOutput
->addImage( $nt->getDBkey() );
1751 wfProfileOut( "$fname-image" );
1754 # We still need to record the image's presence on the page
1755 $this->mOutput
->addImage( $nt->getDBkey() );
1757 wfProfileOut( "$fname-image" );
1761 if ( $ns == NS_CATEGORY
) {
1762 wfProfileIn( "$fname-category" );
1763 $s = rtrim($s . "\n"); # bug 87
1766 $sortkey = $this->getDefaultSort();
1770 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1771 $sortkey = str_replace( "\n", '', $sortkey );
1772 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1773 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1776 * Strip the whitespace Category links produce, see bug 87
1777 * @todo We might want to use trim($tmp, "\n") here.
1779 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1781 wfProfileOut( "$fname-category" );
1786 # Self-link checking
1787 if( $nt->getFragment() === '' ) {
1788 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1789 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1794 # Special and Media are pseudo-namespaces; no pages actually exist in them
1795 if( $ns == NS_MEDIA
) {
1796 $link = $sk->makeMediaLinkObj( $nt, $text );
1797 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1798 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1799 $this->mOutput
->addImage( $nt->getDBkey() );
1801 } elseif( $ns == NS_SPECIAL
) {
1802 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1804 } elseif( $ns == NS_IMAGE
) {
1805 $img = new Image( $nt );
1806 if( $img->exists() ) {
1807 // Force a blue link if the file exists; may be a remote
1808 // upload on the shared repository, and we want to see its
1809 // auto-generated page.
1810 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1811 $this->mOutput
->addLink( $nt );
1815 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1817 wfProfileOut( $fname );
1822 * Make a link placeholder. The text returned can be later resolved to a real link with
1823 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1824 * parsing of interwiki links, and secondly to allow all existence checks and
1825 * article length checks (for stub links) to be bundled into a single query.
1828 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1829 wfProfileIn( __METHOD__
);
1830 if ( ! is_object($nt) ) {
1832 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1834 # Separate the link trail from the rest of the link
1835 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1837 if ( $nt->isExternal() ) {
1838 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1839 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1840 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1842 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1843 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1844 $this->mLinkHolders
['queries'][] = $query;
1845 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1846 $this->mLinkHolders
['titles'][] = $nt;
1848 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1851 wfProfileOut( __METHOD__
);
1856 * Render a forced-blue link inline; protect against double expansion of
1857 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1858 * Since this little disaster has to split off the trail text to avoid
1859 * breaking URLs in the following text without breaking trails on the
1860 * wiki links, it's been made into a horrible function.
1863 * @param string $text
1864 * @param string $query
1865 * @param string $trail
1866 * @param string $prefix
1867 * @return string HTML-wikitext mix oh yuck
1869 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1870 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1871 $sk = $this->mOptions
->getSkin();
1872 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1873 return $this->armorLinks( $link ) . $trail;
1877 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1878 * going to go through further parsing steps before inline URL expansion.
1880 * In particular this is important when using action=render, which causes
1881 * full URLs to be included.
1883 * Oh man I hate our multi-layer parser!
1885 * @param string more-or-less HTML
1886 * @return string less-or-more HTML with NOPARSE bits
1888 function armorLinks( $text ) {
1889 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1890 "{$this->mUniqPrefix}NOPARSE$1", $text );
1894 * Return true if subpage links should be expanded on this page.
1897 function areSubpagesAllowed() {
1898 # Some namespaces don't allow subpages
1899 global $wgNamespacesWithSubpages;
1900 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1904 * Handle link to subpage if necessary
1905 * @param string $target the source of the link
1906 * @param string &$text the link text, modified as necessary
1907 * @return string the full name of the link
1910 function maybeDoSubpageLink($target, &$text) {
1913 # :Foobar -- override special treatment of prefix (images, language links)
1914 # /Foobar -- convert to CurrentPage/Foobar
1915 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1916 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1917 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1919 $fname = 'Parser::maybeDoSubpageLink';
1920 wfProfileIn( $fname );
1921 $ret = $target; # default return value is no change
1924 $target = trim( $target );
1926 # Some namespaces don't allow subpages,
1927 # so only perform processing if subpages are allowed
1928 if( $this->areSubpagesAllowed() ) {
1929 # Look at the first character
1930 if( $target != '' && $target{0} == '/' ) {
1931 # / at end means we don't want the slash to be shown
1932 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1933 if( $trailingSlashes ) {
1934 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1936 $noslash = substr( $target, 1 );
1939 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1940 if( '' === $text ) {
1942 } # this might be changed for ugliness reasons
1944 # check for .. subpage backlinks
1946 $nodotdot = $target;
1947 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1949 $nodotdot = substr( $nodotdot, 3 );
1951 if($dotdotcount > 0) {
1952 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1953 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1954 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1955 # / at the end means don't show full path
1956 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1957 $nodotdot = substr( $nodotdot, 0, -1 );
1958 if( '' === $text ) {
1962 $nodotdot = trim( $nodotdot );
1963 if( $nodotdot != '' ) {
1964 $ret .= '/' . $nodotdot;
1971 wfProfileOut( $fname );
1976 * Used by doBlockLevels()
1979 /* private */ function closeParagraph() {
1981 if ( '' != $this->mLastSection
) {
1982 $result = '</' . $this->mLastSection
. ">\n";
1984 $this->mInPre
= false;
1985 $this->mLastSection
= '';
1988 # getCommon() returns the length of the longest common substring
1989 # of both arguments, starting at the beginning of both.
1991 /* private */ function getCommon( $st1, $st2 ) {
1992 $fl = strlen( $st1 );
1993 $shorter = strlen( $st2 );
1994 if ( $fl < $shorter ) { $shorter = $fl; }
1996 for ( $i = 0; $i < $shorter; ++
$i ) {
1997 if ( $st1{$i} != $st2{$i} ) { break; }
2001 # These next three functions open, continue, and close the list
2002 # element appropriate to the prefix character passed into them.
2004 /* private */ function openList( $char ) {
2005 $result = $this->closeParagraph();
2007 if ( '*' == $char ) { $result .= '<ul><li>'; }
2008 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2009 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2010 else if ( ';' == $char ) {
2011 $result .= '<dl><dt>';
2012 $this->mDTopen
= true;
2014 else { $result = '<!-- ERR 1 -->'; }
2019 /* private */ function nextItem( $char ) {
2020 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2021 else if ( ':' == $char ||
';' == $char ) {
2023 if ( $this->mDTopen
) { $close = '</dt>'; }
2024 if ( ';' == $char ) {
2025 $this->mDTopen
= true;
2026 return $close . '<dt>';
2028 $this->mDTopen
= false;
2029 return $close . '<dd>';
2032 return '<!-- ERR 2 -->';
2035 /* private */ function closeList( $char ) {
2036 if ( '*' == $char ) { $text = '</li></ul>'; }
2037 else if ( '#' == $char ) { $text = '</li></ol>'; }
2038 else if ( ':' == $char ) {
2039 if ( $this->mDTopen
) {
2040 $this->mDTopen
= false;
2041 $text = '</dt></dl>';
2043 $text = '</dd></dl>';
2046 else { return '<!-- ERR 3 -->'; }
2052 * Make lists from lines starting with ':', '*', '#', etc.
2055 * @return string the lists rendered as HTML
2057 function doBlockLevels( $text, $linestart ) {
2058 $fname = 'Parser::doBlockLevels';
2059 wfProfileIn( $fname );
2061 # Parsing through the text line by line. The main thing
2062 # happening here is handling of block-level elements p, pre,
2063 # and making lists from lines starting with * # : etc.
2065 $textLines = explode( "\n", $text );
2067 $lastPrefix = $output = '';
2068 $this->mDTopen
= $inBlockElem = false;
2070 $paragraphStack = false;
2072 if ( !$linestart ) {
2073 $output .= array_shift( $textLines );
2075 foreach ( $textLines as $oLine ) {
2076 $lastPrefixLength = strlen( $lastPrefix );
2077 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2078 $preOpenMatch = preg_match('/<pre/i', $oLine );
2079 if ( !$this->mInPre
) {
2080 # Multiple prefixes may abut each other for nested lists.
2081 $prefixLength = strspn( $oLine, '*#:;' );
2082 $pref = substr( $oLine, 0, $prefixLength );
2085 $pref2 = str_replace( ';', ':', $pref );
2086 $t = substr( $oLine, $prefixLength );
2087 $this->mInPre
= !empty($preOpenMatch);
2089 # Don't interpret any other prefixes in preformatted text
2091 $pref = $pref2 = '';
2096 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2097 # Same as the last item, so no need to deal with nesting or opening stuff
2098 $output .= $this->nextItem( substr( $pref, -1 ) );
2099 $paragraphStack = false;
2101 if ( substr( $pref, -1 ) == ';') {
2102 # The one nasty exception: definition lists work like this:
2103 # ; title : definition text
2104 # So we check for : in the remainder text to split up the
2105 # title and definition, without b0rking links.
2107 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2109 $output .= $term . $this->nextItem( ':' );
2112 } elseif( $prefixLength ||
$lastPrefixLength ) {
2113 # Either open or close a level...
2114 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2115 $paragraphStack = false;
2117 while( $commonPrefixLength < $lastPrefixLength ) {
2118 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2119 --$lastPrefixLength;
2121 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2122 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2124 while ( $prefixLength > $commonPrefixLength ) {
2125 $char = substr( $pref, $commonPrefixLength, 1 );
2126 $output .= $this->openList( $char );
2128 if ( ';' == $char ) {
2129 # FIXME: This is dupe of code above
2130 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2132 $output .= $term . $this->nextItem( ':' );
2135 ++
$commonPrefixLength;
2137 $lastPrefix = $pref2;
2139 if( 0 == $prefixLength ) {
2140 wfProfileIn( "$fname-paragraph" );
2141 # No prefix (not in list)--go to paragraph mode
2142 // XXX: use a stack for nestable elements like span, table and div
2143 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2144 $closematch = preg_match(
2145 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2146 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2147 if ( $openmatch or $closematch ) {
2148 $paragraphStack = false;
2149 #Â TODO bug 5718: paragraph closed
2150 $output .= $this->closeParagraph();
2151 if ( $preOpenMatch and !$preCloseMatch ) {
2152 $this->mInPre
= true;
2154 if ( $closematch ) {
2155 $inBlockElem = false;
2157 $inBlockElem = true;
2159 } else if ( !$inBlockElem && !$this->mInPre
) {
2160 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2162 if ($this->mLastSection
!= 'pre') {
2163 $paragraphStack = false;
2164 $output .= $this->closeParagraph().'<pre>';
2165 $this->mLastSection
= 'pre';
2167 $t = substr( $t, 1 );
2170 if ( '' == trim($t) ) {
2171 if ( $paragraphStack ) {
2172 $output .= $paragraphStack.'<br />';
2173 $paragraphStack = false;
2174 $this->mLastSection
= 'p';
2176 if ($this->mLastSection
!= 'p' ) {
2177 $output .= $this->closeParagraph();
2178 $this->mLastSection
= '';
2179 $paragraphStack = '<p>';
2181 $paragraphStack = '</p><p>';
2185 if ( $paragraphStack ) {
2186 $output .= $paragraphStack;
2187 $paragraphStack = false;
2188 $this->mLastSection
= 'p';
2189 } else if ($this->mLastSection
!= 'p') {
2190 $output .= $this->closeParagraph().'<p>';
2191 $this->mLastSection
= 'p';
2196 wfProfileOut( "$fname-paragraph" );
2198 // somewhere above we forget to get out of pre block (bug 785)
2199 if($preCloseMatch && $this->mInPre
) {
2200 $this->mInPre
= false;
2202 if ($paragraphStack === false) {
2206 while ( $prefixLength ) {
2207 $output .= $this->closeList( $pref2{$prefixLength-1} );
2210 if ( '' != $this->mLastSection
) {
2211 $output .= '</' . $this->mLastSection
. '>';
2212 $this->mLastSection
= '';
2215 wfProfileOut( $fname );
2220 * Split up a string on ':', ignoring any occurences inside tags
2221 * to prevent illegal overlapping.
2222 * @param string $str the string to split
2223 * @param string &$before set to everything before the ':'
2224 * @param string &$after set to everything after the ':'
2225 * return string the position of the ':', or false if none found
2227 function findColonNoLinks($str, &$before, &$after) {
2228 $fname = 'Parser::findColonNoLinks';
2229 wfProfileIn( $fname );
2231 $pos = strpos( $str, ':' );
2232 if( $pos === false ) {
2234 wfProfileOut( $fname );
2238 $lt = strpos( $str, '<' );
2239 if( $lt === false ||
$lt > $pos ) {
2240 // Easy; no tag nesting to worry about
2241 $before = substr( $str, 0, $pos );
2242 $after = substr( $str, $pos+
1 );
2243 wfProfileOut( $fname );
2247 // Ugly state machine to walk through avoiding tags.
2248 $state = MW_COLON_STATE_TEXT
;
2250 $len = strlen( $str );
2251 for( $i = 0; $i < $len; $i++
) {
2255 // (Using the number is a performance hack for common cases)
2256 case 0: // MW_COLON_STATE_TEXT:
2259 // Could be either a <start> tag or an </end> tag
2260 $state = MW_COLON_STATE_TAGSTART
;
2265 $before = substr( $str, 0, $i );
2266 $after = substr( $str, $i +
1 );
2267 wfProfileOut( $fname );
2270 // Embedded in a tag; don't break it.
2273 // Skip ahead looking for something interesting
2274 $colon = strpos( $str, ':', $i );
2275 if( $colon === false ) {
2276 // Nothing else interesting
2277 wfProfileOut( $fname );
2280 $lt = strpos( $str, '<', $i );
2281 if( $stack === 0 ) {
2282 if( $lt === false ||
$colon < $lt ) {
2284 $before = substr( $str, 0, $colon );
2285 $after = substr( $str, $colon +
1 );
2286 wfProfileOut( $fname );
2290 if( $lt === false ) {
2291 // Nothing else interesting to find; abort!
2292 // We're nested, but there's no close tags left. Abort!
2295 // Skip ahead to next tag start
2297 $state = MW_COLON_STATE_TAGSTART
;
2300 case 1: // MW_COLON_STATE_TAG:
2305 $state = MW_COLON_STATE_TEXT
;
2308 // Slash may be followed by >?
2309 $state = MW_COLON_STATE_TAGSLASH
;
2315 case 2: // MW_COLON_STATE_TAGSTART:
2318 $state = MW_COLON_STATE_CLOSETAG
;
2321 $state = MW_COLON_STATE_COMMENT
;
2324 // Illegal early close? This shouldn't happen D:
2325 $state = MW_COLON_STATE_TEXT
;
2328 $state = MW_COLON_STATE_TAG
;
2331 case 3: // MW_COLON_STATE_CLOSETAG:
2336 wfDebug( "Invalid input in $fname; too many close tags\n" );
2337 wfProfileOut( $fname );
2340 $state = MW_COLON_STATE_TEXT
;
2343 case MW_COLON_STATE_TAGSLASH
:
2345 // Yes, a self-closed tag <blah/>
2346 $state = MW_COLON_STATE_TEXT
;
2348 // Probably we're jumping the gun, and this is an attribute
2349 $state = MW_COLON_STATE_TAG
;
2352 case 5: // MW_COLON_STATE_COMMENT:
2354 $state = MW_COLON_STATE_COMMENTDASH
;
2357 case MW_COLON_STATE_COMMENTDASH
:
2359 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2361 $state = MW_COLON_STATE_COMMENT
;
2364 case MW_COLON_STATE_COMMENTDASHDASH
:
2366 $state = MW_COLON_STATE_TEXT
;
2368 $state = MW_COLON_STATE_COMMENT
;
2372 throw new MWException( "State machine error in $fname" );
2376 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2379 wfProfileOut( $fname );
2384 * Return value of a magic variable (like PAGENAME)
2388 function getVariableValue( $index ) {
2389 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2392 * Some of these require message or data lookups and can be
2393 * expensive to check many times.
2395 static $varCache = array();
2396 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2397 if ( isset( $varCache[$index] ) ) {
2398 return $varCache[$index];
2403 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2406 global $wgLocaltimezone;
2407 if ( isset( $wgLocaltimezone ) ) {
2408 $oldtz = getenv( 'TZ' );
2409 putenv( 'TZ='.$wgLocaltimezone );
2411 $localTimestamp = date( 'YmdHis', $ts );
2412 $localMonth = date( 'm', $ts );
2413 $localMonthName = date( 'n', $ts );
2414 $localDay = date( 'j', $ts );
2415 $localDay2 = date( 'd', $ts );
2416 $localDayOfWeek = date( 'w', $ts );
2417 $localWeek = date( 'W', $ts );
2418 $localYear = date( 'Y', $ts );
2419 $localHour = date( 'H', $ts );
2420 if ( isset( $wgLocaltimezone ) ) {
2421 putenv( 'TZ='.$oldtz );
2425 case 'currentmonth':
2426 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2427 case 'currentmonthname':
2428 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2429 case 'currentmonthnamegen':
2430 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2431 case 'currentmonthabbrev':
2432 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2434 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2436 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2438 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2439 case 'localmonthname':
2440 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2441 case 'localmonthnamegen':
2442 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2443 case 'localmonthabbrev':
2444 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2446 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2448 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2450 return $this->mTitle
->getText();
2452 return $this->mTitle
->getPartialURL();
2453 case 'fullpagename':
2454 return $this->mTitle
->getPrefixedText();
2455 case 'fullpagenamee':
2456 return $this->mTitle
->getPrefixedURL();
2458 return $this->mTitle
->getSubpageText();
2459 case 'subpagenamee':
2460 return $this->mTitle
->getSubpageUrlForm();
2461 case 'basepagename':
2462 return $this->mTitle
->getBaseText();
2463 case 'basepagenamee':
2464 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2465 case 'talkpagename':
2466 if( $this->mTitle
->canTalk() ) {
2467 $talkPage = $this->mTitle
->getTalkPage();
2468 return $talkPage->getPrefixedText();
2472 case 'talkpagenamee':
2473 if( $this->mTitle
->canTalk() ) {
2474 $talkPage = $this->mTitle
->getTalkPage();
2475 return $talkPage->getPrefixedUrl();
2479 case 'subjectpagename':
2480 $subjPage = $this->mTitle
->getSubjectPage();
2481 return $subjPage->getPrefixedText();
2482 case 'subjectpagenamee':
2483 $subjPage = $this->mTitle
->getSubjectPage();
2484 return $subjPage->getPrefixedUrl();
2486 return $this->mRevisionId
;
2488 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2489 case 'revisionday2':
2490 return substr( $this->getRevisionTimestamp(), 6, 2 );
2491 case 'revisionmonth':
2492 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2493 case 'revisionyear':
2494 return substr( $this->getRevisionTimestamp(), 0, 4 );
2495 case 'revisiontimestamp':
2496 return $this->getRevisionTimestamp();
2498 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2500 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2502 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2504 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2505 case 'subjectspace':
2506 return $this->mTitle
->getSubjectNsText();
2507 case 'subjectspacee':
2508 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2509 case 'currentdayname':
2510 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2512 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2514 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2516 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2518 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2519 // int to remove the padding
2520 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2522 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2523 case 'localdayname':
2524 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2526 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2528 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2530 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2532 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2533 // int to remove the padding
2534 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2536 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2537 case 'numberofarticles':
2538 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2539 case 'numberoffiles':
2540 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2541 case 'numberofusers':
2542 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2543 case 'numberofpages':
2544 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2545 case 'numberofadmins':
2546 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2547 case 'numberofedits':
2548 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2549 case 'currenttimestamp':
2550 return $varCache[$index] = wfTimestampNow();
2551 case 'localtimestamp':
2552 return $varCache[$index] = $localTimestamp;
2553 case 'currentversion':
2554 return $varCache[$index] = SpecialVersion
::getVersion();
2560 return $wgServerName;
2562 return $wgScriptPath;
2563 case 'directionmark':
2564 return $wgContLang->getDirMark();
2565 case 'contentlanguage':
2566 global $wgContLanguageCode;
2567 return $wgContLanguageCode;
2570 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2578 * initialise the magic variables (like CURRENTMONTHNAME)
2582 function initialiseVariables() {
2583 $fname = 'Parser::initialiseVariables';
2584 wfProfileIn( $fname );
2585 $variableIDs = MagicWord
::getVariableIDs();
2587 $this->mVariables
= array();
2588 foreach ( $variableIDs as $id ) {
2589 $mw =& MagicWord
::get( $id );
2590 $mw->addToArray( $this->mVariables
, $id );
2592 wfProfileOut( $fname );
2596 * parse any parentheses in format ((title|part|part))
2597 * and call callbacks to get a replacement text for any found piece
2599 * @param string $text The text to parse
2600 * @param array $callbacks rules in form:
2601 * '{' => array( # opening parentheses
2602 * 'end' => '}', # closing parentheses
2603 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2604 * 3 => callback # replacement callback to call if {{{..}}} is found
2607 * 'min' => 2, # Minimum parenthesis count in cb
2608 * 'max' => 3, # Maximum parenthesis count in cb
2611 function replace_callback ($text, $callbacks) {
2612 wfProfileIn( __METHOD__
);
2613 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2614 $lastOpeningBrace = -1; # last not closed parentheses
2616 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2619 while ( $i < strlen( $text ) ) {
2620 # Find next opening brace, closing brace or pipe
2621 if ( $lastOpeningBrace == -1 ) {
2622 $currentClosing = '';
2623 $search = $validOpeningBraces;
2625 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2626 $search = $validOpeningBraces . '|' . $currentClosing;
2629 $i +
= strcspn( $text, $search, $i );
2630 if ( $i < strlen( $text ) ) {
2631 if ( $text[$i] == '|' ) {
2633 } elseif ( $text[$i] == $currentClosing ) {
2635 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2637 $rule = $callbacks[$text[$i]];
2639 # Some versions of PHP have a strcspn which stops on null characters
2640 # Ignore and continue
2649 if ( $found == 'open' ) {
2650 # found opening brace, let's add it to parentheses stack
2651 $piece = array('brace' => $text[$i],
2652 'braceEnd' => $rule['end'],
2656 # count opening brace characters
2657 $piece['count'] = strspn( $text, $piece['brace'], $i );
2658 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2659 $i +
= $piece['count'];
2661 # we need to add to stack only if opening brace count is enough for one of the rules
2662 if ( $piece['count'] >= $rule['min'] ) {
2663 $lastOpeningBrace ++
;
2664 $openingBraceStack[$lastOpeningBrace] = $piece;
2666 } elseif ( $found == 'close' ) {
2667 # lets check if it is enough characters for closing brace
2668 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2669 $count = strspn( $text, $text[$i], $i, $maxCount );
2671 # check for maximum matching characters (if there are 5 closing
2672 # characters, we will probably need only 3 - depending on the rules)
2674 $matchingCallback = null;
2675 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2676 if ( $count > $cbType['max'] ) {
2677 # The specified maximum exists in the callback array, unless the caller
2679 $matchingCount = $cbType['max'];
2681 # Count is less than the maximum
2682 # Skip any gaps in the callback array to find the true largest match
2683 # Need to use array_key_exists not isset because the callback can be null
2684 $matchingCount = $count;
2685 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2690 if ($matchingCount <= 0) {
2694 $matchingCallback = $cbType['cb'][$matchingCount];
2696 # let's set a title or last part (if '|' was found)
2697 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2698 $openingBraceStack[$lastOpeningBrace]['title'] =
2699 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2700 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2702 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2703 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2704 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2707 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2708 $pieceEnd = $i +
$matchingCount;
2710 if( is_callable( $matchingCallback ) ) {
2712 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2713 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2714 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2715 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2717 # finally we can call a user callback and replace piece of text
2718 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2719 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2720 $i = $pieceStart +
strlen($replaceWith);
2722 # null value for callback means that parentheses should be parsed, but not replaced
2723 $i +
= $matchingCount;
2726 # reset last opening parentheses, but keep it in case there are unused characters
2727 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2728 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2729 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2732 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2733 $openingBraceStack[$lastOpeningBrace--] = null;
2735 if ($matchingCount < $piece['count']) {
2736 $piece['count'] -= $matchingCount;
2737 $piece['startAt'] -= $matchingCount;
2738 $piece['partStart'] = $piece['startAt'];
2739 # do we still qualify for any callback with remaining count?
2740 $currentCbList = $callbacks[$piece['brace']]['cb'];
2741 while ( $piece['count'] ) {
2742 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2743 $lastOpeningBrace++
;
2744 $openingBraceStack[$lastOpeningBrace] = $piece;
2750 } elseif ( $found == 'pipe' ) {
2751 # lets set a title if it is a first separator, or next part otherwise
2752 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2753 $openingBraceStack[$lastOpeningBrace]['title'] =
2754 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2755 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2756 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2758 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2759 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2760 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2762 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2766 wfProfileOut( __METHOD__
);
2771 * Replace magic variables, templates, and template arguments
2772 * with the appropriate text. Templates are substituted recursively,
2773 * taking care to avoid infinite loops.
2775 * Note that the substitution depends on value of $mOutputType:
2776 * OT_WIKI: only {{subst:}} templates
2777 * OT_MSG: only magic variables
2778 * OT_HTML: all templates and magic variables
2780 * @param string $tex The text to transform
2781 * @param array $args Key-value pairs representing template parameters to substitute
2782 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2785 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2786 # Prevent too big inclusions
2787 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2791 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2792 wfProfileIn( $fname );
2794 # This function is called recursively. To keep track of arguments we need a stack:
2795 array_push( $this->mArgStack
, $args );
2797 $braceCallbacks = array();
2799 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2801 if ( $this->mOutputType
!= OT_MSG
) {
2802 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2804 if ( $braceCallbacks ) {
2808 'cb' => $braceCallbacks,
2809 'min' => $argsOnly ?
3 : 2,
2810 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2814 'cb' => array(2=>null),
2819 $text = $this->replace_callback ($text, $callbacks);
2821 array_pop( $this->mArgStack
);
2823 wfProfileOut( $fname );
2828 * Replace magic variables
2831 function variableSubstitution( $matches ) {
2833 $fname = 'Parser::variableSubstitution';
2834 $varname = $wgContLang->lc($matches[1]);
2835 wfProfileIn( $fname );
2837 if ( $this->mOutputType
== OT_WIKI
) {
2838 # Do only magic variables prefixed by SUBST
2839 $mwSubst =& MagicWord
::get( 'subst' );
2840 if (!$mwSubst->matchStartAndRemove( $varname ))
2842 # Note that if we don't substitute the variable below,
2843 # we don't remove the {{subst:}} magic word, in case
2844 # it is a template rather than a magic variable.
2846 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2847 $id = $this->mVariables
[$varname];
2848 # Now check if we did really match, case sensitive or not
2849 $mw =& MagicWord
::get( $id );
2850 if ($mw->match($matches[1])) {
2851 $text = $this->getVariableValue( $id );
2852 $this->mOutput
->mContainsOldMagic
= true;
2854 $text = $matches[0];
2857 $text = $matches[0];
2859 wfProfileOut( $fname );
2864 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2865 static function createAssocArgs( $args ) {
2866 $assocArgs = array();
2868 foreach( $args as $arg ) {
2869 $eqpos = strpos( $arg, '=' );
2870 if ( $eqpos === false ) {
2871 $assocArgs[$index++
] = $arg;
2873 $name = trim( substr( $arg, 0, $eqpos ) );
2874 $value = trim( substr( $arg, $eqpos+
1 ) );
2875 if ( $value === false ) {
2878 if ( $name !== false ) {
2879 $assocArgs[$name] = $value;
2888 * Return the text of a template, after recursively
2889 * replacing any variables or templates within the template.
2891 * @param array $piece The parts of the template
2892 * $piece['text']: matched text
2893 * $piece['title']: the title, i.e. the part before the |
2894 * $piece['parts']: the parameter array
2895 * @return string the text of the template
2898 function braceSubstitution( $piece ) {
2899 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2900 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2901 wfProfileIn( $fname );
2902 wfProfileIn( __METHOD__
.'-setup' );
2905 $found = false; # $text has been filled
2906 $nowiki = false; # wiki markup in $text should be escaped
2907 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2908 $noargs = false; # Don't replace triple-brace arguments in $text
2909 $replaceHeadings = false; # Make the edit section links go to the template not the article
2910 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2911 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2912 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2914 # Title object, where $text came from
2920 # $part1 is the bit before the first |, and must contain only title characters
2921 # $args is a list of arguments, starting from index 0, not including $part1
2923 $titleText = $part1 = $piece['title'];
2924 # If the third subpattern matched anything, it will start with |
2926 if (null == $piece['parts']) {
2927 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2928 if ($replaceWith != $piece['text']) {
2929 $text = $replaceWith;
2936 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2937 wfProfileOut( __METHOD__
.'-setup' );
2940 wfProfileIn( __METHOD__
.'-modifiers' );
2942 $mwSubst =& MagicWord
::get( 'subst' );
2943 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2944 # One of two possibilities is true:
2945 # 1) Found SUBST but not in the PST phase
2946 # 2) Didn't find SUBST and in the PST phase
2947 # In either case, return without further processing
2948 $text = $piece['text'];
2955 # MSG, MSGNW and RAW
2958 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2959 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2962 # Remove obsolete MSG:
2963 $mwMsg =& MagicWord
::get( 'msg' );
2964 $mwMsg->matchStartAndRemove( $part1 );
2968 $mwRaw =& MagicWord
::get( 'raw' );
2969 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2970 $forceRawInterwiki = true;
2973 wfProfileOut( __METHOD__
.'-modifiers' );
2975 //save path level before recursing into functions & templates.
2976 $lastPathLevel = $this->mTemplatePath
;
2980 wfProfileIn( __METHOD__
. '-pfunc' );
2982 $colonPos = strpos( $part1, ':' );
2983 if ( $colonPos !== false ) {
2984 # Case sensitive functions
2985 $function = substr( $part1, 0, $colonPos );
2986 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2987 $function = $this->mFunctionSynonyms
[1][$function];
2989 # Case insensitive functions
2990 $function = strtolower( $function );
2991 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2992 $function = $this->mFunctionSynonyms
[0][$function];
2998 $funcArgs = array_map( 'trim', $args );
2999 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
3000 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
3003 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3007 if ( is_array( $result ) ) {
3008 if ( isset( $result[0] ) ) {
3009 $text = $linestart . $result[0];
3010 unset( $result[0] );
3013 // Extract flags into the local scope
3014 // This allows callers to set flags such as nowiki, noparse, found, etc.
3017 $text = $linestart . $result;
3021 wfProfileOut( __METHOD__
. '-pfunc' );
3024 # Template table test
3026 # Did we encounter this template already? If yes, it is in the cache
3027 # and we need to check for loops.
3028 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3031 # Infinite loop test
3032 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3036 $text = $linestart .
3037 "[[$part1]]<!-- WARNING: template loop detected -->";
3038 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3040 # set $text to cached message.
3041 $text = $linestart . $this->mTemplates
[$piece['title']];
3042 #treat title for cached page the same as others
3045 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3046 if ($subpage !== '') {
3047 $ns = $this->mTitle
->getNamespace();
3049 $title = Title
::newFromText( $part1, $ns );
3050 //used by include size checking
3051 $titleText = $title->getPrefixedText();
3052 //used by edit section links
3053 $replaceHeadings = true;
3058 # Load from database
3060 wfProfileIn( __METHOD__
. '-loadtpl' );
3062 # declaring $subpage directly in the function call
3063 # does not work correctly with references and breaks
3064 # {{/subpage}}-style inclusions
3066 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3067 if ($subpage !== '') {
3068 $ns = $this->mTitle
->getNamespace();
3070 $title = Title
::newFromText( $part1, $ns );
3073 if ( !is_null( $title ) ) {
3074 $titleText = $title->getPrefixedText();
3075 # Check for language variants if the template is not found
3076 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3077 $wgContLang->findVariantLink($part1, $title);
3080 if ( !$title->isExternal() ) {
3081 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3082 $text = SpecialPage
::capturePath( $title );
3083 if ( is_string( $text ) ) {
3088 $this->disableCache();
3090 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3091 $found = false; //access denied
3092 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3094 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3095 if ( $articleContent !== false ) {
3097 $text = $articleContent;
3098 $replaceHeadings = true;
3102 # If the title is valid but undisplayable, make a link to it
3103 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3104 $text = "[[:$titleText]]";
3107 } elseif ( $title->isTrans() ) {
3108 // Interwiki transclusion
3109 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3110 $text = $this->interwikiTransclude( $title, 'render' );
3114 $text = $this->interwikiTransclude( $title, 'raw' );
3115 $replaceHeadings = true;
3120 # Template cache array insertion
3121 # Use the original $piece['title'] not the mangled $part1, so that
3122 # modifiers such as RAW: produce separate cache entries
3125 // A special page; don't store it in the template cache.
3127 $this->mTemplates
[$piece['title']] = $text;
3129 $text = $linestart . $text;
3132 wfProfileOut( __METHOD__
. '-loadtpl' );
3135 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3136 # Error, oversize inclusion
3137 $text = $linestart .
3138 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3143 # Recursive parsing, escaping and link table handling
3144 # Only for HTML output
3145 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3146 $text = wfEscapeWikiText( $text );
3147 } elseif ( !$this->ot
['msg'] && $found ) {
3149 $assocArgs = array();
3151 # Clean up argument array
3152 $assocArgs = self
::createAssocArgs($args);
3153 # Add a new element to the templace recursion path
3154 $this->mTemplatePath
[$part1] = 1;
3158 # If there are any <onlyinclude> tags, only include them
3159 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3160 $replacer = new OnlyIncludeReplacer
;
3161 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3162 array( &$replacer, 'replace' ), $text );
3163 $text = $replacer->output
;
3165 # Remove <noinclude> sections and <includeonly> tags
3166 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3167 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3169 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3170 # Strip <nowiki>, <pre>, etc.
3171 $text = $this->strip( $text, $this->mStripState
);
3172 if ( $this->ot
['html'] ) {
3173 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3174 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3175 $text = Sanitizer
::removeHTMLcomments( $text );
3178 $text = $this->replaceVariables( $text, $assocArgs );
3180 # If the template begins with a table or block-level
3181 # element, it should be treated as beginning a new line.
3182 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3183 $text = "\n" . $text;
3185 } elseif ( !$noargs ) {
3186 # $noparse and !$noargs
3187 # Just replace the arguments, not any double-brace items
3188 # This is used for rendered interwiki transclusion
3189 $text = $this->replaceVariables( $text, $assocArgs, true );
3192 # Prune lower levels off the recursion check path
3193 $this->mTemplatePath
= $lastPathLevel;
3195 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3196 # Error, oversize inclusion
3197 $text = $linestart .
3198 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3204 wfProfileOut( $fname );
3205 return $piece['text'];
3207 wfProfileIn( __METHOD__
. '-placeholders' );
3209 # Replace raw HTML by a placeholder
3210 # Add a blank line preceding, to prevent it from mucking up
3211 # immediately preceding headings
3212 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3214 # replace ==section headers==
3215 # XXX this needs to go away once we have a better parser.
3216 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3217 if( !is_null( $title ) )
3218 $encodedname = base64_encode($title->getPrefixedDBkey());
3220 $encodedname = base64_encode("");
3221 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3222 PREG_SPLIT_DELIM_CAPTURE
);
3224 $nsec = $headingOffset;
3226 for( $i = 0; $i < count($m); $i +
= 2 ) {
3228 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3230 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3235 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3236 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3237 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3243 wfProfileOut( __METHOD__
. '-placeholders' );
3246 # Prune lower levels off the recursion check path
3247 $this->mTemplatePath
= $lastPathLevel;
3250 wfProfileOut( $fname );
3251 return $piece['text'];
3253 wfProfileOut( $fname );
3259 * Fetch the unparsed text of a template and register a reference to it.
3261 function fetchTemplateAndtitle( $title ) {
3263 $finalTitle = $title;
3264 // Loop to fetch the article, with up to 1 redirect
3265 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3266 $rev = Revision
::newFromTitle( $title );
3267 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3269 $text = $rev->getText();
3270 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3272 $message = $wgLang->lcfirst( $title->getText() );
3273 $text = wfMsgForContentNoTrans( $message );
3274 if( wfEmptyMsg( $message, $text ) ) {
3281 if ( $text === false ) {
3285 $finalTitle = $title;
3286 $title = Title
::newFromRedirect( $text );
3288 return array($text,$finalTitle);
3291 function fetchTemplate( $title ) {
3292 $rv = $this->fetchTemplateAndtitle($title);
3297 * Transclude an interwiki link.
3299 function interwikiTransclude( $title, $action ) {
3300 global $wgEnableScaryTranscluding;
3302 if (!$wgEnableScaryTranscluding)
3303 return wfMsg('scarytranscludedisabled');
3305 $url = $title->getFullUrl( "action=$action" );
3307 if (strlen($url) > 255)
3308 return wfMsg('scarytranscludetoolong');
3309 return $this->fetchScaryTemplateMaybeFromCache($url);
3312 function fetchScaryTemplateMaybeFromCache($url) {
3313 global $wgTranscludeCacheExpiry;
3314 $dbr = wfGetDB(DB_SLAVE
);
3315 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3316 array('tc_url' => $url));
3318 $time = $obj->tc_time
;
3319 $text = $obj->tc_contents
;
3320 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3325 $text = Http
::get($url);
3327 return wfMsg('scarytranscludefailed', $url);
3329 $dbw = wfGetDB(DB_MASTER
);
3330 $dbw->replace('transcache', array('tc_url'), array(
3332 'tc_time' => time(),
3333 'tc_contents' => $text));
3339 * Triple brace replacement -- used for template arguments
3342 function argSubstitution( $matches ) {
3343 $arg = trim( $matches['title'] );
3344 $text = $matches['text'];
3345 $inputArgs = end( $this->mArgStack
);
3347 if ( array_key_exists( $arg, $inputArgs ) ) {
3348 $text = $inputArgs[$arg];
3349 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3350 null != $matches['parts'] && count($matches['parts']) > 0) {
3351 $text = $matches['parts'][0];
3353 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3354 $text = $matches['text'] .
3355 '<!-- WARNING: argument omitted, expansion size too large -->';
3362 * Increment an include size counter
3364 * @param string $type The type of expansion
3365 * @param integer $size The size of the text
3366 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3368 function incrementIncludeSize( $type, $size ) {
3369 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3372 $this->mIncludeSizes
[$type] +
= $size;
3378 * Detect __NOGALLERY__ magic word and set a placeholder
3380 function stripNoGallery( &$text ) {
3381 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3383 $mw = MagicWord
::get( 'nogallery' );
3384 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3388 * Detect __TOC__ magic word and set a placeholder
3390 function stripToc( $text ) {
3391 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3393 $mw = MagicWord
::get( 'notoc' );
3394 if( $mw->matchAndRemove( $text ) ) {
3395 $this->mShowToc
= false;
3398 $mw = MagicWord
::get( 'toc' );
3399 if( $mw->match( $text ) ) {
3400 $this->mShowToc
= true;
3401 $this->mForceTocPosition
= true;
3403 // Set a placeholder. At the end we'll fill it in with the TOC.
3404 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3406 // Only keep the first one.
3407 $text = $mw->replace( '', $text );
3413 * This function accomplishes several tasks:
3414 * 1) Auto-number headings if that option is enabled
3415 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3416 * 3) Add a Table of contents on the top for users who have enabled the option
3417 * 4) Auto-anchor headings
3419 * It loops through all headlines, collects the necessary data, then splits up the
3420 * string and re-inserts the newly formatted headlines.
3422 * @param string $text
3423 * @param boolean $isMain
3426 function formatHeadings( $text, $isMain=true ) {
3427 global $wgMaxTocLevel, $wgContLang;
3429 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3430 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3433 $showEditLink = $this->mOptions
->getEditSection();
3436 # Inhibit editsection links if requested in the page
3437 $esw =& MagicWord
::get( 'noeditsection' );
3438 if( $esw->matchAndRemove( $text ) ) {
3442 # Get all headlines for numbering them and adding funky stuff like [edit]
3443 # links - this is for later, but we need the number of headlines right now
3445 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3447 # if there are fewer than 4 headlines in the article, do not show TOC
3448 # unless it's been explicitly enabled.
3449 $enoughToc = $this->mShowToc
&&
3450 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3452 # Allow user to stipulate that a page should have a "new section"
3453 # link added via __NEWSECTIONLINK__
3454 $mw =& MagicWord
::get( 'newsectionlink' );
3455 if( $mw->matchAndRemove( $text ) )
3456 $this->mOutput
->setNewSection( true );
3458 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3459 # override above conditions and always show TOC above first header
3460 $mw =& MagicWord
::get( 'forcetoc' );
3461 if ($mw->matchAndRemove( $text ) ) {
3462 $this->mShowToc
= true;
3466 # We need this to perform operations on the HTML
3467 $sk = $this->mOptions
->getSkin();
3471 $sectionCount = 0; # headlineCount excluding template sections
3474 # Ugh .. the TOC should have neat indentation levels which can be
3475 # passed to the skin functions. These are determined here
3479 $sublevelCount = array();
3480 $levelCount = array();
3487 foreach( $matches[3] as $headline ) {
3489 $templatetitle = '';
3490 $templatesection = 0;
3493 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3495 $templatetitle = base64_decode($mat[1]);
3496 $templatesection = 1 +
(int)base64_decode($mat[2]);
3497 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3501 $prevlevel = $level;
3502 $prevtoclevel = $toclevel;
3504 $level = $matches[1][$headlineCount];
3506 if( $doNumberHeadings ||
$enoughToc ) {
3508 if ( $level > $prevlevel ) {
3509 # Increase TOC level
3511 $sublevelCount[$toclevel] = 0;
3512 if( $toclevel<$wgMaxTocLevel ) {
3513 $prevtoclevel = $toclevel;
3514 $toc .= $sk->tocIndent();
3518 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3519 # Decrease TOC level, find level to jump to
3521 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3522 # Can only go down to level 1
3525 for ($i = $toclevel; $i > 0; $i--) {
3526 if ( $levelCount[$i] == $level ) {
3527 # Found last matching level
3531 elseif ( $levelCount[$i] < $level ) {
3532 # Found first matching level below current level
3538 if( $toclevel<$wgMaxTocLevel ) {
3539 if($prevtoclevel < $wgMaxTocLevel) {
3540 # Unindent only if the previous toc level was shown :p
3541 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3543 $toc .= $sk->tocLineEnd();
3548 # No change in level, end TOC line
3549 if( $toclevel<$wgMaxTocLevel ) {
3550 $toc .= $sk->tocLineEnd();
3554 $levelCount[$toclevel] = $level;
3556 # count number of headlines for each level
3557 @$sublevelCount[$toclevel]++
;
3559 for( $i = 1; $i <= $toclevel; $i++
) {
3560 if( !empty( $sublevelCount[$i] ) ) {
3564 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3570 # The canonized header is a version of the header text safe to use for links
3571 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3572 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3574 # Remove link placeholders by the link text.
3575 # <!--LINK number-->
3577 # link text with suffix
3578 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3579 "\$this->mLinkHolders['texts'][\$1]",
3580 $canonized_headline );
3581 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3582 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3583 $canonized_headline );
3586 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3587 $tocline = trim( $canonized_headline );
3588 # Save headline for section edit hint before it's escaped
3589 $headline_hint = trim( $canonized_headline );
3590 $canonized_headline = Sanitizer
::escapeId( $tocline );
3591 $refers[$headlineCount] = $canonized_headline;
3593 # count how many in assoc. array so we can track dupes in anchors
3594 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3595 $refcount[$headlineCount]=$refers[$canonized_headline];
3597 # Don't number the heading if it is the only one (looks silly)
3598 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3599 # the two are different if the line contains a link
3600 $headline=$numbering . ' ' . $headline;
3603 # Create the anchor for linking from the TOC to the section
3604 $anchor = $canonized_headline;
3605 if($refcount[$headlineCount] > 1 ) {
3606 $anchor .= '_' . $refcount[$headlineCount];
3608 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3609 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3611 # give headline the correct <h#> tag
3612 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3614 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3616 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3620 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3627 # Never ever show TOC if no headers
3628 if( $numVisible < 1 ) {
3633 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3634 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3636 $toc = $sk->tocList( $toc );
3639 # split up and insert constructed headlines
3641 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3644 foreach( $blocks as $block ) {
3645 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3646 # This is the [edit] link that appears for the top block of text when
3647 # section editing is enabled
3649 # Disabled because it broke block formatting
3650 # For example, a bullet point in the top line
3651 # $full .= $sk->editSectionLink(0);
3654 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3655 # Top anchor now in skin
3659 if( !empty( $head[$i] ) ) {
3664 if( $this->mForceTocPosition
) {
3665 return str_replace( '<!--MWTOC-->', $toc, $full );
3672 * Transform wiki markup when saving a page by doing \r\n -> \n
3673 * conversion, substitting signatures, {{subst:}} templates, etc.
3675 * @param string $text the text to transform
3676 * @param Title &$title the Title object for the current article
3677 * @param User &$user the User object describing the current user
3678 * @param ParserOptions $options parsing options
3679 * @param bool $clearState whether to clear the parser state first
3680 * @return string the altered wiki markup
3683 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3684 $this->mOptions
= $options;
3685 $this->mTitle
=& $title;
3686 $this->setOutputType( OT_WIKI
);
3688 if ( $clearState ) {
3689 $this->clearState();
3692 $stripState = new StripState
;
3696 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3697 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3698 $text = $this->pstPass2( $text, $stripState, $user );
3699 $text = $stripState->unstripBoth( $text );
3704 * Pre-save transform helper function
3707 function pstPass2( $text, &$stripState, $user ) {
3708 global $wgContLang, $wgLocaltimezone;
3710 /* Note: This is the timestamp saved as hardcoded wikitext to
3711 * the database, we use $wgContLang here in order to give
3712 * everyone the same signature and use the default one rather
3713 * than the one selected in each user's preferences.
3715 if ( isset( $wgLocaltimezone ) ) {
3716 $oldtz = getenv( 'TZ' );
3717 putenv( 'TZ='.$wgLocaltimezone );
3719 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3720 ' (' . date( 'T' ) . ')';
3721 if ( isset( $wgLocaltimezone ) ) {
3722 putenv( 'TZ='.$oldtz );
3725 # Variable replacement
3726 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3727 $text = $this->replaceVariables( $text );
3729 # Strip out <nowiki> etc. added via replaceVariables
3730 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3733 $sigText = $this->getUserSig( $user );
3734 $text = strtr( $text, array(
3736 '~~~~' => "$sigText $d",
3740 # Context links: [[|name]] and [[name (context)|]]
3742 global $wgLegalTitleChars;
3743 $tc = "[$wgLegalTitleChars]";
3744 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3746 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3747 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3748 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3750 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3751 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3752 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3754 $t = $this->mTitle
->getText();
3756 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3757 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3758 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3759 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3761 # if there's no context, don't bother duplicating the title
3762 $text = preg_replace( $p2, '[[\\1]]', $text );
3765 # Trim trailing whitespace
3766 $text = rtrim( $text );
3772 * Fetch the user's signature text, if any, and normalize to
3773 * validated, ready-to-insert wikitext.
3779 function getUserSig( &$user ) {
3780 $username = $user->getName();
3781 $nickname = $user->getOption( 'nickname' );
3782 $nickname = $nickname === '' ?
$username : $nickname;
3784 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3785 # Sig. might contain markup; validate this
3786 if( $this->validateSig( $nickname ) !== false ) {
3787 # Validated; clean up (if needed) and return it
3788 return $this->cleanSig( $nickname, true );
3790 # Failed to validate; fall back to the default
3791 $nickname = $username;
3792 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3796 // Make sure nickname doesnt get a sig in a sig
3797 $nickname = $this->cleanSigInSig( $nickname );
3799 # If we're still here, make it a link to the user page
3800 $userpage = $user->getUserPage();
3801 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3805 * Check that the user's signature contains no bad XML
3807 * @param string $text
3808 * @return mixed An expanded string, or false if invalid.
3810 function validateSig( $text ) {
3811 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3815 * Clean up signature text
3817 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3818 * 2) Substitute all transclusions
3820 * @param string $text
3821 * @param $parsing Whether we're cleaning (preferences save) or parsing
3822 * @return string Signature text
3824 function cleanSig( $text, $parsing = false ) {
3826 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3828 $substWord = MagicWord
::get( 'subst' );
3829 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3830 $substText = '{{' . $substWord->getSynonym( 0 );
3832 $text = preg_replace( $substRegex, $substText, $text );
3833 $text = $this->cleanSigInSig( $text );
3834 $text = $this->replaceVariables( $text );
3836 $this->clearState();
3841 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3842 * @param string $text
3843 * @return string Signature text with /~{3,5}/ removed
3845 function cleanSigInSig( $text ) {
3846 $text = preg_replace( '/~{3,5}/', '', $text );
3851 * Set up some variables which are usually set up in parse()
3852 * so that an external function can call some class members with confidence
3855 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3856 $this->mTitle
=& $title;
3857 $this->mOptions
= $options;
3858 $this->setOutputType( $outputType );
3859 if ( $clearState ) {
3860 $this->clearState();
3865 * Transform a MediaWiki message by replacing magic variables.
3867 * @param string $text the text to transform
3868 * @param ParserOptions $options options
3869 * @return string the text with variables substituted
3872 function transformMsg( $text, $options ) {
3874 static $executing = false;
3876 $fname = "Parser::transformMsg";
3878 # Guard against infinite recursion
3884 wfProfileIn($fname);
3886 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3887 $this->mTitle
= $wgTitle;
3889 $this->mTitle
= Title
::newFromText('msg');
3891 $this->mOptions
= $options;
3892 $this->setOutputType( OT_MSG
);
3893 $this->clearState();
3894 $text = $this->replaceVariables( $text );
3897 wfProfileOut($fname);
3902 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3903 * The callback should have the following form:
3904 * function myParserHook( $text, $params, &$parser ) { ... }
3906 * Transform and return $text. Use $parser for any required context, e.g. use
3907 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3911 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3912 * @param mixed $callback The callback function (and object) to use for the tag
3914 * @return The old value of the mTagHooks array associated with the hook
3916 function setHook( $tag, $callback ) {
3917 $tag = strtolower( $tag );
3918 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3919 $this->mTagHooks
[$tag] = $callback;
3925 * Create a function, e.g. {{sum:1|2|3}}
3926 * The callback function should have the form:
3927 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3929 * The callback may either return the text result of the function, or an array with the text
3930 * in element 0, and a number of flags in the other elements. The names of the flags are
3931 * specified in the keys. Valid flags are:
3932 * found The text returned is valid, stop processing the template. This
3934 * nowiki Wiki markup in the return value should be escaped
3935 * noparse Unsafe HTML tags should not be stripped, etc.
3936 * noargs Don't replace triple-brace arguments in the return value
3937 * isHTML The returned text is HTML, armour it against wikitext transformation
3941 * @param string $id The magic word ID
3942 * @param mixed $callback The callback function (and object) to use
3943 * @param integer $flags a combination of the following flags:
3944 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3946 * @return The old callback function for this name, if any
3948 function setFunctionHook( $id, $callback, $flags = 0 ) {
3949 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3950 $this->mFunctionHooks
[$id] = $callback;
3952 # Add to function cache
3953 $mw = MagicWord
::get( $id );
3955 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3957 $synonyms = $mw->getSynonyms();
3958 $sensitive = intval( $mw->isCaseSensitive() );
3960 foreach ( $synonyms as $syn ) {
3962 if ( !$sensitive ) {
3963 $syn = strtolower( $syn );
3966 if ( !( $flags & SFH_NO_HASH
) ) {
3969 # Remove trailing colon
3970 if ( substr( $syn, -1, 1 ) == ':' ) {
3971 $syn = substr( $syn, 0, -1 );
3973 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3979 * Get all registered function hook identifiers
3983 function getFunctionHooks() {
3984 return array_keys( $this->mFunctionHooks
);
3988 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3989 * Placeholders created in Skin::makeLinkObj()
3990 * Returns an array of links found, indexed by PDBK:
3994 * $options is a bit field, RLH_FOR_UPDATE to select for update
3996 function replaceLinkHolders( &$text, $options = 0 ) {
4000 $fname = 'Parser::replaceLinkHolders';
4001 wfProfileIn( $fname );
4005 $sk = $this->mOptions
->getSkin();
4006 $linkCache =& LinkCache
::singleton();
4008 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4009 wfProfileIn( $fname.'-check' );
4010 $dbr = wfGetDB( DB_SLAVE
);
4011 $page = $dbr->tableName( 'page' );
4012 $threshold = $wgUser->getOption('stubthreshold');
4015 asort( $this->mLinkHolders
['namespaces'] );
4020 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4022 $title = $this->mLinkHolders
['titles'][$key];
4024 # Skip invalid entries.
4025 # Result will be ugly, but prevents crash.
4026 if ( is_null( $title ) ) {
4029 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4031 # Check if it's a static known link, e.g. interwiki
4032 if ( $title->isAlwaysKnown() ) {
4033 $colours[$pdbk] = 1;
4034 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4035 $colours[$pdbk] = 1;
4036 $this->mOutput
->addLink( $title, $id );
4037 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4038 $colours[$pdbk] = 0;
4040 # Not in the link cache, add it to the query
4041 if ( !isset( $current ) ) {
4043 $query = "SELECT page_id, page_namespace, page_title";
4044 if ( $threshold > 0 ) {
4045 $query .= ', page_len, page_is_redirect';
4047 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4048 } elseif ( $current != $ns ) {
4050 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4055 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4060 if ( $options & RLH_FOR_UPDATE
) {
4061 $query .= ' FOR UPDATE';
4064 $res = $dbr->query( $query, $fname );
4066 # Fetch data and form into an associative array
4067 # non-existent = broken
4070 while ( $s = $dbr->fetchObject($res) ) {
4071 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4072 $pdbk = $title->getPrefixedDBkey();
4073 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4074 $this->mOutput
->addLink( $title, $s->page_id
);
4076 if ( $threshold > 0 ) {
4077 $size = $s->page_len
;
4078 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4079 $colours[$pdbk] = 1;
4081 $colours[$pdbk] = 2;
4084 $colours[$pdbk] = 1;
4088 wfProfileOut( $fname.'-check' );
4090 # Do a second query for different language variants of links and categories
4091 if($wgContLang->hasVariants()){
4092 $linkBatch = new LinkBatch();
4093 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4094 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4095 $varCategories = array(); // category replacements oldDBkey => newDBkey
4097 $categories = $this->mOutput
->getCategoryLinks();
4099 // Add variants of links to link batch
4100 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4101 $title = $this->mLinkHolders
['titles'][$key];
4102 if ( is_null( $title ) )
4105 $pdbk = $title->getPrefixedDBkey();
4106 $titleText = $title->getText();
4108 // generate all variants of the link title text
4109 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4111 // if link was not found (in first query), add all variants to query
4112 if ( !isset($colours[$pdbk]) ){
4113 foreach($allTextVariants as $textVariant){
4114 if($textVariant != $titleText){
4115 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4116 if(is_null($variantTitle)) continue;
4117 $linkBatch->addObj( $variantTitle );
4118 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4124 // process categories, check if a category exists in some variant
4125 foreach( $categories as $category){
4126 $variants = $wgContLang->convertLinkToAllVariants($category);
4127 foreach($variants as $variant){
4128 if($variant != $category){
4129 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4130 if(is_null($variantTitle)) continue;
4131 $linkBatch->addObj( $variantTitle );
4132 $categoryMap[$variant] = $category;
4138 if(!$linkBatch->isEmpty()){
4140 $titleClause = $linkBatch->constructSet('page', $dbr);
4142 $variantQuery = "SELECT page_id, page_namespace, page_title";
4143 if ( $threshold > 0 ) {
4144 $variantQuery .= ', page_len, page_is_redirect';
4147 $variantQuery .= " FROM $page WHERE $titleClause";
4148 if ( $options & RLH_FOR_UPDATE
) {
4149 $variantQuery .= ' FOR UPDATE';
4152 $varRes = $dbr->query( $variantQuery, $fname );
4154 // for each found variants, figure out link holders and replace
4155 while ( $s = $dbr->fetchObject($varRes) ) {
4157 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4158 $varPdbk = $variantTitle->getPrefixedDBkey();
4159 $vardbk = $variantTitle->getDBkey();
4161 $holderKeys = array();
4162 if(isset($variantMap[$varPdbk])){
4163 $holderKeys = $variantMap[$varPdbk];
4164 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4165 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4168 // loop over link holders
4169 foreach($holderKeys as $key){
4170 $title = $this->mLinkHolders
['titles'][$key];
4171 if ( is_null( $title ) ) continue;
4173 $pdbk = $title->getPrefixedDBkey();
4175 if(!isset($colours[$pdbk])){
4176 // found link in some of the variants, replace the link holder data
4177 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4178 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4180 // set pdbk and colour
4181 $pdbks[$key] = $varPdbk;
4182 if ( $threshold > 0 ) {
4183 $size = $s->page_len
;
4184 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4185 $colours[$varPdbk] = 1;
4187 $colours[$varPdbk] = 2;
4191 $colours[$varPdbk] = 1;
4196 // check if the object is a variant of a category
4197 if(isset($categoryMap[$vardbk])){
4198 $oldkey = $categoryMap[$vardbk];
4199 if($oldkey != $vardbk)
4200 $varCategories[$oldkey]=$vardbk;
4204 // rebuild the categories in original order (if there are replacements)
4205 if(count($varCategories)>0){
4207 $originalCats = $this->mOutput
->getCategories();
4208 foreach($originalCats as $cat => $sortkey){
4209 // make the replacement
4210 if( array_key_exists($cat,$varCategories) )
4211 $newCats[$varCategories[$cat]] = $sortkey;
4212 else $newCats[$cat] = $sortkey;
4214 $this->mOutput
->setCategoryLinks($newCats);
4219 # Construct search and replace arrays
4220 wfProfileIn( $fname.'-construct' );
4221 $replacePairs = array();
4222 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4223 $pdbk = $pdbks[$key];
4224 $searchkey = "<!--LINK $key-->";
4225 $title = $this->mLinkHolders
['titles'][$key];
4226 if ( empty( $colours[$pdbk] ) ) {
4227 $linkCache->addBadLinkObj( $title );
4228 $colours[$pdbk] = 0;
4229 $this->mOutput
->addLink( $title, 0 );
4230 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4231 $this->mLinkHolders
['texts'][$key],
4232 $this->mLinkHolders
['queries'][$key] );
4233 } elseif ( $colours[$pdbk] == 1 ) {
4234 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4235 $this->mLinkHolders
['texts'][$key],
4236 $this->mLinkHolders
['queries'][$key] );
4237 } elseif ( $colours[$pdbk] == 2 ) {
4238 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4239 $this->mLinkHolders
['texts'][$key],
4240 $this->mLinkHolders
['queries'][$key] );
4243 $replacer = new HashtableReplacer( $replacePairs, 1 );
4244 wfProfileOut( $fname.'-construct' );
4247 wfProfileIn( $fname.'-replace' );
4248 $text = preg_replace_callback(
4249 '/(<!--LINK .*?-->)/',
4253 wfProfileOut( $fname.'-replace' );
4256 # Now process interwiki link holders
4257 # This is quite a bit simpler than internal links
4258 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4259 wfProfileIn( $fname.'-interwiki' );
4260 # Make interwiki link HTML
4261 $replacePairs = array();
4262 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4263 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4264 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4266 $replacer = new HashtableReplacer( $replacePairs, 1 );
4268 $text = preg_replace_callback(
4269 '/<!--IWLINK (.*?)-->/',
4272 wfProfileOut( $fname.'-interwiki' );
4275 wfProfileOut( $fname );
4280 * Replace <!--LINK--> link placeholders with plain text of links
4281 * (not HTML-formatted).
4282 * @param string $text
4285 function replaceLinkHoldersText( $text ) {
4286 $fname = 'Parser::replaceLinkHoldersText';
4287 wfProfileIn( $fname );
4289 $text = preg_replace_callback(
4290 '/<!--(LINK|IWLINK) (.*?)-->/',
4291 array( &$this, 'replaceLinkHoldersTextCallback' ),
4294 wfProfileOut( $fname );
4299 * @param array $matches
4303 function replaceLinkHoldersTextCallback( $matches ) {
4304 $type = $matches[1];
4306 if( $type == 'LINK' ) {
4307 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4308 return $this->mLinkHolders
['texts'][$key];
4310 } elseif( $type == 'IWLINK' ) {
4311 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4312 return $this->mInterwikiLinkHolders
['texts'][$key];
4319 * Tag hook handler for 'pre'.
4321 function renderPreTag( $text, $attribs ) {
4322 // Backwards-compatibility hack
4323 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4325 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4326 return wfOpenElement( 'pre', $attribs ) .
4327 Xml
::escapeTagsOnly( $content ) .
4332 * Renders an image gallery from a text with one line per image.
4333 * text labels may be given by using |-style alternative text. E.g.
4334 * Image:one.jpg|The number "1"
4335 * Image:tree.jpg|A tree
4336 * given as text will return the HTML of a gallery with two images,
4337 * labeled 'The number "1"' and
4340 function renderImageGallery( $text, $params ) {
4341 $ig = new ImageGallery();
4342 $ig->setContextTitle( $this->mTitle
);
4343 $ig->setShowBytes( false );
4344 $ig->setShowFilename( false );
4346 $ig->useSkin( $this->mOptions
->getSkin() );
4348 if( isset( $params['caption'] ) ) {
4349 $caption = $params['caption'];
4350 $caption = htmlspecialchars( $caption );
4351 $caption = $this->replaceInternalLinks( $caption );
4352 $ig->setCaptionHtml( $caption );
4354 if( isset( $params['perrow'] ) ) {
4355 $ig->setPerRow( $params['perrow'] );
4357 if( isset( $params['widths'] ) ) {
4358 $ig->setWidths( $params['widths'] );
4360 if( isset( $params['heights'] ) ) {
4361 $ig->setHeights( $params['heights'] );
4364 $lines = explode( "\n", $text );
4365 foreach ( $lines as $line ) {
4366 # match lines like these:
4367 # Image:someimage.jpg|This is some image
4369 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4371 if ( count( $matches ) == 0 ) {
4374 $tp = Title
::newFromText( $matches[1] );
4376 if( is_null( $nt ) ) {
4377 # Bogus title. Ignore these so we don't bomb out later.
4380 if ( isset( $matches[3] ) ) {
4381 $label = $matches[3];
4386 $pout = $this->parse( $label,
4389 false, // Strip whitespace...?
4390 false // Don't clear state!
4392 $html = $pout->getText();
4394 $ig->add( new Image( $nt ), $html );
4396 # Only add real images (bug #5586)
4397 if ( $nt->getNamespace() == NS_IMAGE
) {
4398 $this->mOutput
->addImage( $nt->getDBkey() );
4401 return $ig->toHTML();
4405 * Parse image options text and use it to make an image
4407 function makeImage( $nt, $options ) {
4408 # @TODO: let the MediaHandler specify its transform parameters
4410 # Check if the options text is of the form "options|alt text"
4412 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4413 # * left no resizing, just left align. label is used for alt= only
4414 # * right same, but right aligned
4415 # * none same, but not aligned
4416 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4417 # * center center the image
4418 # * framed Keep original image size, no magnify-button.
4419 # vertical-align values (no % or length right now):
4430 $part = array_map( 'trim', explode( '|', $options) );
4433 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4434 foreach ( $alignments as $alignment ) {
4435 $mwAlign[$alignment] =& MagicWord
::get( 'img_'.$alignment );
4437 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4438 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4439 $mwWidth =& MagicWord
::get( 'img_width' );
4440 $mwFramed =& MagicWord
::get( 'img_framed' );
4441 $mwPage =& MagicWord
::get( 'img_page' );
4445 $framed = $thumb = false;
4446 $manual_thumb = '' ;
4447 $align = $valign = '';
4448 $sk = $this->mOptions
->getSkin();
4450 foreach( $part as $val ) {
4451 if ( !is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4453 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4454 # use manually specified thumbnail
4456 $manual_thumb = $match;
4458 foreach( $alignments as $alignment ) {
4459 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4460 switch ( $alignment ) {
4461 case 'left': case 'right': case 'center': case 'none':
4462 $align = $alignment; break;
4464 $valign = $alignment;
4469 if ( ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4470 # Select a page in a multipage document
4471 $params['page'] = $match;
4472 } elseif ( !isset( $params['width'] ) && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4473 wfDebug( "img_width match: $match\n" );
4474 # $match is the image width in pixels
4476 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4477 $params['width'] = intval( $m[1] );
4478 $params['height'] = intval( $m[2] );
4480 $params['width'] = intval($match);
4482 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4489 # Strip bad stuff out of the alt text
4490 $alt = $this->replaceLinkHoldersText( $caption );
4492 # make sure there are no placeholders in thumbnail attributes
4493 # that are later expanded to html- so expand them now and
4495 $alt = $this->mStripState
->unstripBoth( $alt );
4496 $alt = Sanitizer
::stripAllTags( $alt );
4498 # Linker does the rest
4499 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $params, $framed, $thumb, $manual_thumb, $valign );
4503 * Set a flag in the output object indicating that the content is dynamic and
4504 * shouldn't be cached.
4506 function disableCache() {
4507 wfDebug( "Parser output marked as uncacheable.\n" );
4508 $this->mOutput
->mCacheTime
= -1;
4512 * Callback from the Sanitizer for expanding items found in HTML attribute
4513 * values, so they can be safely tested and escaped.
4514 * @param string $text
4515 * @param array $args
4519 function attributeStripCallback( &$text, $args ) {
4520 $text = $this->replaceVariables( $text, $args );
4521 $text = $this->mStripState
->unstripBoth( $text );
4530 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4531 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4532 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4538 function getTags() { return array_keys( $this->mTagHooks
); }
4543 * Break wikitext input into sections, and either pull or replace
4544 * some particular section's text.
4546 * External callers should use the getSection and replaceSection methods.
4548 * @param $text Page wikitext
4549 * @param $section Numbered section. 0 pulls the text before the first
4550 * heading; other numbers will pull the given section
4551 * along with its lower-level subsections.
4552 * @param $mode One of "get" or "replace"
4553 * @param $newtext Replacement text for section data.
4554 * @return string for "get", the extracted section text.
4555 * for "replace", the whole page with the section replaced.
4557 private function extractSections( $text, $section, $mode, $newtext='' ) {
4558 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4559 # comments to be stripped as well)
4560 $stripState = new StripState
;
4562 $oldOutputType = $this->mOutputType
;
4563 $oldOptions = $this->mOptions
;
4564 $this->mOptions
= new ParserOptions();
4565 $this->setOutputType( OT_WIKI
);
4567 $striptext = $this->strip( $text, $stripState, true );
4569 $this->setOutputType( $oldOutputType );
4570 $this->mOptions
= $oldOptions;
4572 # now that we can be sure that no pseudo-sections are in the source,
4573 # split it up by section
4574 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4575 $comment = "(?:$uniq-!--.*?QINU)";
4580 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4581 (=+) # Should this be limited to 6?
4582 .+? # Section title...
4583 \\2 # Ending = count must match start
4584 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4593 PREG_SPLIT_DELIM_CAPTURE
);
4595 if( $mode == "get" ) {
4596 if( $section == 0 ) {
4597 // "Section 0" returns the content before any other section.
4600 //track missing section, will replace if found.
4603 } elseif( $mode == "replace" ) {
4604 if( $section == 0 ) {
4605 $rv = $newtext . "\n\n";
4614 for( $index = 1; $index < count( $secs ); ) {
4615 $headerLine = $secs[$index++
];
4616 if( $secs[$index] ) {
4618 $headerLevel = strlen( $secs[$index++
] );
4622 $headerLevel = intval( $secs[$index++
] );
4624 $content = $secs[$index++
];
4627 if( $mode == "get" ) {
4628 if( $count == $section ) {
4629 $rv = $headerLine . $content;
4630 $sectionLevel = $headerLevel;
4631 } elseif( $count > $section ) {
4632 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4633 $rv .= $headerLine . $content;
4635 // Broke out to a higher-level section
4639 } elseif( $mode == "replace" ) {
4640 if( $count < $section ) {
4641 $rv .= $headerLine . $content;
4642 } elseif( $count == $section ) {
4643 $rv .= $newtext . "\n\n";
4644 $sectionLevel = $headerLevel;
4645 } elseif( $count > $section ) {
4646 if( $headerLevel <= $sectionLevel ) {
4647 // Passed the section's sub-parts.
4651 $rv .= $headerLine . $content;
4657 # reinsert stripped tags
4658 $rv = trim( $stripState->unstripBoth( $rv ) );
4664 * This function returns the text of a section, specified by a number ($section).
4665 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4666 * the first section before any such heading (section 0).
4668 * If a section contains subsections, these are also returned.
4670 * @param $text String: text to look in
4671 * @param $section Integer: section number
4672 * @param $deftext: default to return if section is not found
4673 * @return string text of the requested section
4675 public function getSection( $text, $section, $deftext='' ) {
4676 return $this->extractSections( $text, $section, "get", $deftext );
4679 public function replaceSection( $oldtext, $section, $text ) {
4680 return $this->extractSections( $oldtext, $section, "replace", $text );
4684 * Get the timestamp associated with the current revision, adjusted for
4685 * the default server-local timestamp
4687 function getRevisionTimestamp() {
4688 if ( is_null( $this->mRevisionTimestamp
) ) {
4689 wfProfileIn( __METHOD__
);
4691 $dbr = wfGetDB( DB_SLAVE
);
4692 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4693 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4695 // Normalize timestamp to internal MW format for timezone processing.
4696 // This has the added side-effect of replacing a null value with
4697 // the current time, which gives us more sensible behavior for
4699 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4701 // The cryptic '' timezone parameter tells to use the site-default
4702 // timezone offset instead of the user settings.
4704 // Since this value will be saved into the parser cache, served
4705 // to other users, and potentially even used inside links and such,
4706 // it needs to be consistent for all visitors.
4707 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4709 wfProfileOut( __METHOD__
);
4711 return $this->mRevisionTimestamp
;
4715 * Mutator for $mDefaultSort
4717 * @param $sort New value
4719 public function setDefaultSort( $sort ) {
4720 $this->mDefaultSort
= $sort;
4724 * Accessor for $mDefaultSort
4725 * Will use the title/prefixed title if none is set
4729 public function getDefaultSort() {
4730 if( $this->mDefaultSort
!== false ) {
4731 return $this->mDefaultSort
;
4733 return $this->mTitle
->getNamespace() == NS_CATEGORY
4734 ?
$this->mTitle
->getText()
4735 : $this->mTitle
->getPrefixedText();
4742 * @todo document, briefly.
4743 * @addtogroup Parser
4745 class OnlyIncludeReplacer
{
4748 function replace( $matches ) {
4749 if ( substr( $matches[1], -1 ) == "\n" ) {
4750 $this->output
.= substr( $matches[1], 0, -1 );
4752 $this->output
.= $matches[1];
4758 * @todo document, briefly.
4759 * @addtogroup Parser
4762 var $general, $nowiki;
4764 function __construct() {
4765 $this->general
= new ReplacementArray
;
4766 $this->nowiki
= new ReplacementArray
;
4769 function unstripGeneral( $text ) {
4770 wfProfileIn( __METHOD__
);
4771 $text = $this->general
->replace( $text );
4772 wfProfileOut( __METHOD__
);
4776 function unstripNoWiki( $text ) {
4777 wfProfileIn( __METHOD__
);
4778 $text = $this->nowiki
->replace( $text );
4779 wfProfileOut( __METHOD__
);
4783 function unstripBoth( $text ) {
4784 wfProfileIn( __METHOD__
);
4785 $text = $this->general
->replace( $text );
4786 $text = $this->nowiki
->replace( $text );
4787 wfProfileOut( __METHOD__
);