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, $revid = null ) {
404 wfProfileIn( __METHOD__
);
406 $this->setOutputType( OT_PREPROCESS
);
407 $this->mOptions
= $options;
408 $this->mTitle
= $title;
409 if( $revid !== null ) {
410 $this->mRevisionId
= $revid;
412 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
413 $text = $this->strip( $text, $this->mStripState
);
414 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
415 if ( $this->mOptions
->getRemoveComments() ) {
416 $text = Sanitizer
::removeHTMLcomments( $text );
418 $text = $this->replaceVariables( $text );
419 $text = $this->mStripState
->unstripBoth( $text );
420 wfProfileOut( __METHOD__
);
425 * Get a random string
430 function getRandomString() {
431 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
434 function &getTitle() { return $this->mTitle
; }
435 function getOptions() { return $this->mOptions
; }
437 function getFunctionLang() {
438 global $wgLang, $wgContLang;
439 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
443 * Replaces all occurrences of HTML-style comments and the given tags
444 * in the text with a random marker and returns teh next text. The output
445 * parameter $matches will be an associative array filled with data in
447 * 'UNIQ-xxxxx' => array(
450 * array( 'param' => 'x' ),
451 * '<element param="x">tag content</element>' ) )
453 * @param $elements list of element names. Comments are always extracted.
454 * @param $text Source text string.
455 * @param $uniq_prefix
460 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
465 $taglist = implode( '|', $elements );
466 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
468 while ( '' != $text ) {
469 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
471 if( count( $p ) < 5 ) {
474 if( count( $p ) > 5 ) {
488 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
489 $stripped .= $marker;
491 if ( $close === '/>' ) {
492 // Empty element tag, <tag />
497 if( $element == '!--' ) {
500 $end = "/(<\\/$element\\s*>)/i";
502 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
504 if( count( $q ) < 3 ) {
505 # No end tag -- let it run out to the end of the text.
514 $matches[$marker] = array( $element,
516 Sanitizer
::decodeTagAttributes( $attributes ),
517 "<$element$attributes$close$content$tail" );
523 * Strips and renders nowiki, pre, math, hiero
524 * If $render is set, performs necessary rendering operations on plugins
525 * Returns the text, and fills an array with data needed in unstrip()
527 * @param StripState $state
529 * @param bool $stripcomments when set, HTML comments <!-- like this -->
530 * will be stripped in addition to other tags. This is important
531 * for section editing, where these comments cause confusion when
532 * counting the sections in the wikisource
534 * @param array dontstrip contains tags which should not be stripped;
535 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
539 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
541 wfProfileIn( __METHOD__
);
542 $render = ($this->mOutputType
== OT_HTML
);
544 $uniq_prefix = $this->mUniqPrefix
;
545 $commentState = new ReplacementArray
;
546 $nowikiItems = array();
547 $generalItems = array();
549 $elements = array_merge(
550 array( 'nowiki', 'gallery' ),
551 array_keys( $this->mTagHooks
) );
554 $elements[] = 'html';
556 if( $this->mOptions
->getUseTeX() ) {
557 $elements[] = 'math';
560 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
561 foreach ( $elements AS $k => $v ) {
562 if ( !in_array ( $v , $dontstrip ) ) continue;
563 unset ( $elements[$k] );
567 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
569 foreach( $matches as $marker => $data ) {
570 list( $element, $content, $params, $tag ) = $data;
572 $tagName = strtolower( $element );
573 wfProfileIn( __METHOD__
."-render-$tagName" );
577 if( substr( $tag, -3 ) == '-->' ) {
580 // Unclosed comment in input.
581 // Close it so later stripping can remove it
590 // Shouldn't happen otherwise. :)
592 $output = Xml
::escapeTagsOnly( $content );
595 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
598 $output = $this->renderImageGallery( $content, $params );
601 if( isset( $this->mTagHooks
[$tagName] ) ) {
602 $output = call_user_func_array( $this->mTagHooks
[$tagName],
603 array( $content, $params, $this ) );
605 throw new MWException( "Invalid call hook $element" );
608 wfProfileOut( __METHOD__
."-render-$tagName" );
610 // Just stripping tags; keep the source
614 // Unstrip the output, to support recursive strip() calls
615 $output = $state->unstripBoth( $output );
617 if( !$stripcomments && $element == '!--' ) {
618 $commentState->setPair( $marker, $output );
619 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
620 $nowikiItems[$marker] = $output;
622 $generalItems[$marker] = $output;
625 # Add the new items to the state
626 # We do this after the loop instead of during it to avoid slowing
627 # down the recursive unstrip
628 $state->nowiki
->mergeArray( $nowikiItems );
629 $state->general
->mergeArray( $generalItems );
631 # Unstrip comments unless explicitly told otherwise.
632 # (The comments are always stripped prior to this point, so as to
633 # not invoke any extension tags / parser hooks contained within
635 if ( !$stripcomments ) {
636 // Put them all back and forget them
637 $text = $commentState->replace( $text );
640 wfProfileOut( __METHOD__
);
645 * Restores pre, math, and other extensions removed by strip()
647 * always call unstripNoWiki() after this one
649 * @deprecated use $this->mStripState->unstrip()
651 function unstrip( $text, $state ) {
652 return $state->unstripGeneral( $text );
656 * Always call this after unstrip() to preserve the order
659 * @deprecated use $this->mStripState->unstrip()
661 function unstripNoWiki( $text, $state ) {
662 return $state->unstripNoWiki( $text );
666 * @deprecated use $this->mStripState->unstripBoth()
668 function unstripForHTML( $text ) {
669 return $this->mStripState
->unstripBoth( $text );
673 * Add an item to the strip state
674 * Returns the unique tag which must be inserted into the stripped text
675 * The tag will be replaced with the original text in unstrip()
679 function insertStripItem( $text, &$state ) {
680 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
681 $state->general
->setPair( $rnd, $text );
686 * Interface with html tidy, used if $wgUseTidy = true.
687 * If tidy isn't able to correct the markup, the original will be
688 * returned in all its glory with a warning comment appended.
690 * Either the external tidy program or the in-process tidy extension
691 * will be used depending on availability. Override the default
692 * $wgTidyInternal setting to disable the internal if it's not working.
694 * @param string $text Hideous HTML input
695 * @return string Corrected HTML output
699 function tidy( $text ) {
700 global $wgTidyInternal;
701 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
702 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
703 '<head><title>test</title></head><body>'.$text.'</body></html>';
704 if( $wgTidyInternal ) {
705 $correctedtext = Parser
::internalTidy( $wrappedtext );
707 $correctedtext = Parser
::externalTidy( $wrappedtext );
709 if( is_null( $correctedtext ) ) {
710 wfDebug( "Tidy error detected!\n" );
711 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
713 return $correctedtext;
717 * Spawn an external HTML tidy process and get corrected markup back from it.
722 function externalTidy( $text ) {
723 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
724 $fname = 'Parser::externalTidy';
725 wfProfileIn( $fname );
730 $descriptorspec = array(
731 0 => array('pipe', 'r'),
732 1 => array('pipe', 'w'),
733 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.
736 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
737 if (is_resource($process)) {
738 // Theoretically, this style of communication could cause a deadlock
739 // here. If the stdout buffer fills up, then writes to stdin could
740 // block. This doesn't appear to happen with tidy, because tidy only
741 // writes to stdout after it's finished reading from stdin. Search
742 // for tidyParseStdin and tidySaveStdout in console/tidy.c
743 fwrite($pipes[0], $text);
745 while (!feof($pipes[1])) {
746 $cleansource .= fgets($pipes[1], 1024);
749 proc_close($process);
752 wfProfileOut( $fname );
754 if( $cleansource == '' && $text != '') {
755 // Some kind of error happened, so we couldn't get the corrected text.
756 // Just give up; we'll use the source text and append a warning.
764 * Use the HTML tidy PECL extension to use the tidy library in-process,
765 * saving the overhead of spawning a new process. Currently written to
766 * the PHP 4.3.x version of the extension, may not work on PHP 5.
768 * 'pear install tidy' should be able to compile the extension module.
773 function internalTidy( $text ) {
775 $fname = 'Parser::internalTidy';
776 wfProfileIn( $fname );
778 tidy_load_config( $wgTidyConf );
779 tidy_set_encoding( 'utf8' );
780 tidy_parse_string( $text );
782 if( tidy_get_status() == 2 ) {
783 // 2 is magic number for fatal error
784 // http://www.php.net/manual/en/function.tidy-get-status.php
787 $cleansource = tidy_get_output();
789 wfProfileOut( $fname );
794 * parse the wiki syntax used to render tables
798 function doTableStuff ( $text ) {
799 $fname = 'Parser::doTableStuff';
800 wfProfileIn( $fname );
802 $lines = explode ( "\n" , $text );
803 $td_history = array (); // Is currently a td tag open?
804 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
805 $tr_history = array (); // Is currently a tr tag open?
806 $tr_attributes = array (); // history of tr attributes
807 $has_opened_tr = array(); // Did this table open a <tr> element?
808 $indent_level = 0; // indent level of the table
809 foreach ( $lines as $key => $line )
811 $line = trim ( $line );
813 if( $line == '' ) { // empty line, go to next line
816 $first_character = $line{0};
819 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
820 // First check if we are starting a new table
821 $indent_level = strlen( $matches[1] );
823 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
824 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
826 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
827 array_push ( $td_history , false );
828 array_push ( $last_tag_history , '' );
829 array_push ( $tr_history , false );
830 array_push ( $tr_attributes , '' );
831 array_push ( $has_opened_tr , false );
832 } else if ( count ( $td_history ) == 0 ) {
833 // Don't do any of the following
835 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
836 // We are ending a table
837 $line = '</table>' . substr ( $line , 2 );
838 $last_tag = array_pop ( $last_tag_history );
840 if ( !array_pop ( $has_opened_tr ) ) {
841 $line = "<tr><td></td></tr>{$line}";
844 if ( array_pop ( $tr_history ) ) {
845 $line = "</tr>{$line}";
848 if ( array_pop ( $td_history ) ) {
849 $line = "</{$last_tag}>{$line}";
851 array_pop ( $tr_attributes );
852 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
853 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
854 // Now we have a table row
855 $line = preg_replace( '#^\|-+#', '', $line );
857 // Whats after the tag is now only attributes
858 $attributes = $this->mStripState
->unstripBoth( $line );
859 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
860 array_pop ( $tr_attributes );
861 array_push ( $tr_attributes , $attributes );
864 $last_tag = array_pop ( $last_tag_history );
865 array_pop ( $has_opened_tr );
866 array_push ( $has_opened_tr , true );
868 if ( array_pop ( $tr_history ) ) {
872 if ( array_pop ( $td_history ) ) {
873 $line = "</{$last_tag}>{$line}";
876 $lines[$key] = $line;
877 array_push ( $tr_history , false );
878 array_push ( $td_history , false );
879 array_push ( $last_tag_history , '' );
881 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
882 // This might be cell elements, td, th or captions
883 if ( substr ( $line , 0 , 2 ) == '|+' ) {
884 $first_character = '+';
885 $line = substr ( $line , 1 );
888 $line = substr ( $line , 1 );
890 if ( $first_character == '!' ) {
891 $line = str_replace ( '!!' , '||' , $line );
894 // Split up multiple cells on the same line.
895 // FIXME : This can result in improper nesting of tags processed
896 // by earlier parser steps, but should avoid splitting up eg
897 // attribute values containing literal "||".
898 $cells = StringUtils
::explodeMarkup( '||' , $line );
902 // Loop through each table cell
903 foreach ( $cells as $cell )
906 if ( $first_character != '+' )
908 $tr_after = array_pop ( $tr_attributes );
909 if ( !array_pop ( $tr_history ) ) {
910 $previous = "<tr{$tr_after}>\n";
912 array_push ( $tr_history , true );
913 array_push ( $tr_attributes , '' );
914 array_pop ( $has_opened_tr );
915 array_push ( $has_opened_tr , true );
918 $last_tag = array_pop ( $last_tag_history );
920 if ( array_pop ( $td_history ) ) {
921 $previous = "</{$last_tag}>{$previous}";
924 if ( $first_character == '|' ) {
926 } else if ( $first_character == '!' ) {
928 } else if ( $first_character == '+' ) {
929 $last_tag = 'caption';
934 array_push ( $last_tag_history , $last_tag );
936 // A cell could contain both parameters and data
937 $cell_data = explode ( '|' , $cell , 2 );
939 // Bug 553: Note that a '|' inside an invalid link should not
940 // be mistaken as delimiting cell parameters
941 if ( strpos( $cell_data[0], '[[' ) !== false ) {
942 $cell = "{$previous}<{$last_tag}>{$cell}";
943 } else if ( count ( $cell_data ) == 1 )
944 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
946 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
947 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
948 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
951 $lines[$key] .= $cell;
952 array_push ( $td_history , true );
957 // Closing open td, tr && table
958 while ( count ( $td_history ) > 0 )
960 if ( array_pop ( $td_history ) ) {
963 if ( array_pop ( $tr_history ) ) {
966 if ( !array_pop ( $has_opened_tr ) ) {
967 $lines[] = "<tr><td></td></tr>" ;
970 $lines[] = '</table>' ;
973 $output = implode ( "\n" , $lines ) ;
975 // special case: don't return empty table
976 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
980 wfProfileOut( $fname );
986 * Helper function for parse() that transforms wiki markup into
987 * HTML. Only called for $mOutputType == OT_HTML.
991 function internalParse( $text ) {
994 $fname = 'Parser::internalParse';
995 wfProfileIn( $fname );
997 # Hook to suspend the parser in this state
998 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
999 wfProfileOut( $fname );
1003 # Remove <noinclude> tags and <includeonly> sections
1004 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
1005 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1006 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1008 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1010 $text = $this->replaceVariables( $text, $args );
1011 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1013 // Tables need to come after variable replacement for things to work
1014 // properly; putting them before other transformations should keep
1015 // exciting things like link expansions from showing up in surprising
1017 $text = $this->doTableStuff( $text );
1019 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1021 $text = $this->stripToc( $text );
1022 $this->stripNoGallery( $text );
1023 $text = $this->doHeadings( $text );
1024 if($this->mOptions
->getUseDynamicDates()) {
1025 $df =& DateFormatter
::getInstance();
1026 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1028 $text = $this->doAllQuotes( $text );
1029 $text = $this->replaceInternalLinks( $text );
1030 $text = $this->replaceExternalLinks( $text );
1032 # replaceInternalLinks may sometimes leave behind
1033 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1034 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1036 $text = $this->doMagicLinks( $text );
1037 $text = $this->formatHeadings( $text, $isMain );
1039 wfProfileOut( $fname );
1044 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1045 * magic external links.
1049 function &doMagicLinks( &$text ) {
1050 wfProfileIn( __METHOD__
);
1051 $text = preg_replace_callback(
1053 <a.*?</a> | # Skip link text
1054 <.*?> | # Skip stuff inside HTML elements
1055 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1056 ISBN\s+(\b # ISBN, capture number as m[2]
1057 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1058 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1059 [0-9Xx] # check digit
1061 )!x', array( &$this, 'magicLinkCallback' ), $text );
1062 wfProfileOut( __METHOD__
);
1066 function magicLinkCallback( $m ) {
1067 if ( substr( $m[0], 0, 1 ) == '<' ) {
1070 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1072 $num = strtr( $isbn, array(
1077 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1078 $text = '<a href="' .
1079 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1080 "\" class=\"internal\">ISBN $isbn</a>";
1082 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1086 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1088 $urlmsg = 'pubmedurl';
1091 throw new MWException( __METHOD__
.': unrecognised match type "' .
1092 substr($m[0], 0, 20 ) . '"' );
1095 $url = wfMsg( $urlmsg, $id);
1096 $sk = $this->mOptions
->getSkin();
1097 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1098 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1104 * Parse headers and return html
1108 function doHeadings( $text ) {
1109 $fname = 'Parser::doHeadings';
1110 wfProfileIn( $fname );
1111 for ( $i = 6; $i >= 1; --$i ) {
1112 $h = str_repeat( '=', $i );
1113 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1114 "<h{$i}>\\1</h{$i}>\\2", $text );
1116 wfProfileOut( $fname );
1121 * Replace single quotes with HTML markup
1123 * @return string the altered text
1125 function doAllQuotes( $text ) {
1126 $fname = 'Parser::doAllQuotes';
1127 wfProfileIn( $fname );
1129 $lines = explode( "\n", $text );
1130 foreach ( $lines as $line ) {
1131 $outtext .= $this->doQuotes ( $line ) . "\n";
1133 $outtext = substr($outtext, 0,-1);
1134 wfProfileOut( $fname );
1139 * Helper function for doAllQuotes()
1142 function doQuotes( $text ) {
1143 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1144 if ( count( $arr ) == 1 )
1148 # First, do some preliminary work. This may shift some apostrophes from
1149 # being mark-up to being text. It also counts the number of occurrences
1150 # of bold and italics mark-ups.
1154 foreach ( $arr as $r )
1156 if ( ( $i %
2 ) == 1 )
1158 # If there are ever four apostrophes, assume the first is supposed to
1159 # be text, and the remaining three constitute mark-up for bold text.
1160 if ( strlen( $arr[$i] ) == 4 )
1165 # If there are more than 5 apostrophes in a row, assume they're all
1166 # text except for the last 5.
1167 else if ( strlen( $arr[$i] ) > 5 )
1169 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1172 # Count the number of occurrences of bold and italics mark-ups.
1173 # We are not counting sequences of five apostrophes.
1174 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1175 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1176 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1181 # If there is an odd number of both bold and italics, it is likely
1182 # that one of the bold ones was meant to be an apostrophe followed
1183 # by italics. Which one we cannot know for certain, but it is more
1184 # likely to be one that has a single-letter word before it.
1185 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1188 $firstsingleletterword = -1;
1189 $firstmultiletterword = -1;
1191 foreach ( $arr as $r )
1193 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1195 $x1 = substr ($arr[$i-1], -1);
1196 $x2 = substr ($arr[$i-1], -2, 1);
1198 if ($firstspace == -1) $firstspace = $i;
1199 } else if ($x2 == ' ') {
1200 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1202 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1208 # If there is a single-letter word, use it!
1209 if ($firstsingleletterword > -1)
1211 $arr [ $firstsingleletterword ] = "''";
1212 $arr [ $firstsingleletterword-1 ] .= "'";
1214 # If not, but there's a multi-letter word, use that one.
1215 else if ($firstmultiletterword > -1)
1217 $arr [ $firstmultiletterword ] = "''";
1218 $arr [ $firstmultiletterword-1 ] .= "'";
1220 # ... otherwise use the first one that has neither.
1221 # (notice that it is possible for all three to be -1 if, for example,
1222 # there is only one pentuple-apostrophe in the line)
1223 else if ($firstspace > -1)
1225 $arr [ $firstspace ] = "''";
1226 $arr [ $firstspace-1 ] .= "'";
1230 # Now let's actually convert our apostrophic mush to HTML!
1235 foreach ($arr as $r)
1239 if ($state == 'both')
1246 if (strlen ($r) == 2)
1249 { $output .= '</i>'; $state = ''; }
1250 else if ($state == 'bi')
1251 { $output .= '</i>'; $state = 'b'; }
1252 else if ($state == 'ib')
1253 { $output .= '</b></i><b>'; $state = 'b'; }
1254 else if ($state == 'both')
1255 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1256 else # $state can be 'b' or ''
1257 { $output .= '<i>'; $state .= 'i'; }
1259 else if (strlen ($r) == 3)
1262 { $output .= '</b>'; $state = ''; }
1263 else if ($state == 'bi')
1264 { $output .= '</i></b><i>'; $state = 'i'; }
1265 else if ($state == 'ib')
1266 { $output .= '</b>'; $state = 'i'; }
1267 else if ($state == 'both')
1268 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1269 else # $state can be 'i' or ''
1270 { $output .= '<b>'; $state .= 'b'; }
1272 else if (strlen ($r) == 5)
1275 { $output .= '</b><i>'; $state = 'i'; }
1276 else if ($state == 'i')
1277 { $output .= '</i><b>'; $state = 'b'; }
1278 else if ($state == 'bi')
1279 { $output .= '</i></b>'; $state = ''; }
1280 else if ($state == 'ib')
1281 { $output .= '</b></i>'; $state = ''; }
1282 else if ($state == 'both')
1283 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1284 else # ($state == '')
1285 { $buffer = ''; $state = 'both'; }
1290 # Now close all remaining tags. Notice that the order is important.
1291 if ($state == 'b' ||
$state == 'ib')
1293 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1297 # There might be lonely ''''', so make sure we have a buffer
1298 if ($state == 'both' && $buffer)
1299 $output .= '<b><i>'.$buffer.'</i></b>';
1305 * Replace external links
1307 * Note: this is all very hackish and the order of execution matters a lot.
1308 * Make sure to run maintenance/parserTests.php if you change this code.
1312 function replaceExternalLinks( $text ) {
1314 $fname = 'Parser::replaceExternalLinks';
1315 wfProfileIn( $fname );
1317 $sk = $this->mOptions
->getSkin();
1319 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1321 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1324 while ( $i<count( $bits ) ) {
1326 $protocol = $bits[$i++
];
1327 $text = $bits[$i++
];
1328 $trail = $bits[$i++
];
1330 # The characters '<' and '>' (which were escaped by
1331 # removeHTMLtags()) should not be included in
1332 # URLs, per RFC 2396.
1334 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1335 $text = substr($url, $m2[0][1]) . ' ' . $text;
1336 $url = substr($url, 0, $m2[0][1]);
1339 # If the link text is an image URL, replace it with an <img> tag
1340 # This happened by accident in the original parser, but some people used it extensively
1341 $img = $this->maybeMakeExternalImage( $text );
1342 if ( $img !== false ) {
1348 # Set linktype for CSS - if URL==text, link is essentially free
1349 $linktype = ($text == $url) ?
'free' : 'text';
1351 # No link text, e.g. [http://domain.tld/some.link]
1352 if ( $text == '' ) {
1353 # Autonumber if allowed. See bug #5918
1354 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1355 $text = '[' . ++
$this->mAutonumber
. ']';
1356 $linktype = 'autonumber';
1358 # Otherwise just use the URL
1359 $text = htmlspecialchars( $url );
1363 # Have link text, e.g. [http://domain.tld/some.link text]s
1365 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1368 $text = $wgContLang->markNoConversion($text);
1370 $url = Sanitizer
::cleanUrl( $url );
1372 # Process the trail (i.e. everything after this link up until start of the next link),
1373 # replacing any non-bracketed links
1374 $trail = $this->replaceFreeExternalLinks( $trail );
1376 # Use the encoded URL
1377 # This means that users can paste URLs directly into the text
1378 # Funny characters like ö aren't valid in URLs anyway
1379 # This was changed in August 2004
1380 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1382 # Register link in the output object.
1383 # Replace unnecessary URL escape codes with the referenced character
1384 # This prevents spammers from hiding links from the filters
1385 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1386 $this->mOutput
->addExternalLink( $pasteurized );
1389 wfProfileOut( $fname );
1394 * Replace anything that looks like a URL with a link
1397 function replaceFreeExternalLinks( $text ) {
1399 $fname = 'Parser::replaceFreeExternalLinks';
1400 wfProfileIn( $fname );
1402 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1403 $s = array_shift( $bits );
1406 $sk = $this->mOptions
->getSkin();
1408 while ( $i < count( $bits ) ){
1409 $protocol = $bits[$i++
];
1410 $remainder = $bits[$i++
];
1413 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1414 # Found some characters after the protocol that look promising
1415 $url = $protocol . $m[1];
1418 # special case: handle urls as url args:
1419 # http://www.example.com/foo?=http://www.example.com/bar
1420 if(strlen($trail) == 0 &&
1422 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1423 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1426 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1431 # The characters '<' and '>' (which were escaped by
1432 # removeHTMLtags()) should not be included in
1433 # URLs, per RFC 2396.
1435 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1436 $trail = substr($url, $m2[0][1]) . $trail;
1437 $url = substr($url, 0, $m2[0][1]);
1440 # Move trailing punctuation to $trail
1442 # If there is no left bracket, then consider right brackets fair game too
1443 if ( strpos( $url, '(' ) === false ) {
1447 $numSepChars = strspn( strrev( $url ), $sep );
1448 if ( $numSepChars ) {
1449 $trail = substr( $url, -$numSepChars ) . $trail;
1450 $url = substr( $url, 0, -$numSepChars );
1453 $url = Sanitizer
::cleanUrl( $url );
1455 # Is this an external image?
1456 $text = $this->maybeMakeExternalImage( $url );
1457 if ( $text === false ) {
1458 # Not an image, make a link
1459 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1460 # Register it in the output object...
1461 # Replace unnecessary URL escape codes with their equivalent characters
1462 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1463 $this->mOutput
->addExternalLink( $pasteurized );
1465 $s .= $text . $trail;
1467 $s .= $protocol . $remainder;
1470 wfProfileOut( $fname );
1475 * Replace unusual URL escape codes with their equivalent characters
1479 * @todo This can merge genuinely required bits in the path or query string,
1480 * breaking legit URLs. A proper fix would treat the various parts of
1481 * the URL differently; as a workaround, just use the output for
1482 * statistical records, not for actual linking/output.
1484 static function replaceUnusualEscapes( $url ) {
1485 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1486 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1490 * Callback function used in replaceUnusualEscapes().
1491 * Replaces unusual URL escape codes with their equivalent character
1495 private static function replaceUnusualEscapesCallback( $matches ) {
1496 $char = urldecode( $matches[0] );
1497 $ord = ord( $char );
1498 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1499 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1500 // No, shouldn't be escaped
1503 // Yes, leave it escaped
1509 * make an image if it's allowed, either through the global
1510 * option or through the exception
1513 function maybeMakeExternalImage( $url ) {
1514 $sk = $this->mOptions
->getSkin();
1515 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1516 $imagesexception = !empty($imagesfrom);
1518 if ( $this->mOptions
->getAllowExternalImages()
1519 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1520 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1522 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1529 * Process [[ ]] wikilinks
1533 function replaceInternalLinks( $s ) {
1535 static $fname = 'Parser::replaceInternalLinks' ;
1537 wfProfileIn( $fname );
1539 wfProfileIn( $fname.'-setup' );
1541 # the % is needed to support urlencoded titles as well
1542 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1544 $sk = $this->mOptions
->getSkin();
1546 #split the entire text string on occurences of [[
1547 $a = explode( '[[', ' ' . $s );
1548 #get the first element (all text up to first [[), and remove the space we added
1549 $s = array_shift( $a );
1550 $s = substr( $s, 1 );
1552 # Match a link having the form [[namespace:link|alternate]]trail
1554 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1555 # Match cases where there is no "]]", which might still be images
1556 static $e1_img = FALSE;
1557 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1558 # Match the end of a line for a word that's not followed by whitespace,
1559 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1560 $e2 = wfMsgForContent( 'linkprefix' );
1562 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1563 if( is_null( $this->mTitle
) ) {
1564 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1566 $nottalk = !$this->mTitle
->isTalkPage();
1568 if ( $useLinkPrefixExtension ) {
1570 if ( preg_match( $e2, $s, $m ) ) {
1571 $first_prefix = $m[2];
1573 $first_prefix = false;
1579 if($wgContLang->hasVariants()) {
1580 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1582 $selflink = array($this->mTitle
->getPrefixedText());
1584 $useSubpages = $this->areSubpagesAllowed();
1585 wfProfileOut( $fname.'-setup' );
1587 # Loop for each link
1588 for ($k = 0; isset( $a[$k] ); $k++
) {
1590 if ( $useLinkPrefixExtension ) {
1591 wfProfileIn( $fname.'-prefixhandling' );
1592 if ( preg_match( $e2, $s, $m ) ) {
1600 $prefix = $first_prefix;
1601 $first_prefix = false;
1603 wfProfileOut( $fname.'-prefixhandling' );
1606 $might_be_img = false;
1608 wfProfileIn( "$fname-e1" );
1609 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1611 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1612 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1613 # the real problem is with the $e1 regex
1616 # Still some problems for cases where the ] is meant to be outside punctuation,
1617 # and no image is in sight. See bug 2095.
1620 substr( $m[3], 0, 1 ) === ']' &&
1621 strpos($text, '[') !== false
1624 $text .= ']'; # so that replaceExternalLinks($text) works later
1625 $m[3] = substr( $m[3], 1 );
1627 # fix up urlencoded title texts
1628 if( strpos( $m[1], '%' ) !== false ) {
1629 # Should anchors '#' also be rejected?
1630 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1633 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1634 $might_be_img = true;
1636 if ( strpos( $m[1], '%' ) !== false ) {
1637 $m[1] = urldecode($m[1]);
1640 } else { # Invalid form; output directly
1641 $s .= $prefix . '[[' . $line ;
1642 wfProfileOut( "$fname-e1" );
1645 wfProfileOut( "$fname-e1" );
1646 wfProfileIn( "$fname-misc" );
1648 # Don't allow internal links to pages containing
1649 # PROTO: where PROTO is a valid URL protocol; these
1650 # should be external links.
1651 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1652 $s .= $prefix . '[[' . $line ;
1656 # Make subpage if necessary
1657 if( $useSubpages ) {
1658 $link = $this->maybeDoSubpageLink( $m[1], $text );
1663 $noforce = (substr($m[1], 0, 1) != ':');
1665 # Strip off leading ':'
1666 $link = substr($link, 1);
1669 wfProfileOut( "$fname-misc" );
1670 wfProfileIn( "$fname-title" );
1671 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1673 $s .= $prefix . '[[' . $line;
1674 wfProfileOut( "$fname-title" );
1678 $ns = $nt->getNamespace();
1679 $iw = $nt->getInterWiki();
1680 wfProfileOut( "$fname-title" );
1682 if ($might_be_img) { # if this is actually an invalid link
1683 wfProfileIn( "$fname-might_be_img" );
1684 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1686 while (isset ($a[$k+
1]) ) {
1687 #look at the next 'line' to see if we can close it there
1688 $spliced = array_splice( $a, $k +
1, 1 );
1689 $next_line = array_shift( $spliced );
1690 $m = explode( ']]', $next_line, 3 );
1691 if ( count( $m ) == 3 ) {
1692 # the first ]] closes the inner link, the second the image
1694 $text .= "[[{$m[0]}]]{$m[1]}";
1697 } elseif ( count( $m ) == 2 ) {
1698 #if there's exactly one ]] that's fine, we'll keep looking
1699 $text .= "[[{$m[0]}]]{$m[1]}";
1701 #if $next_line is invalid too, we need look no further
1702 $text .= '[[' . $next_line;
1707 # we couldn't find the end of this imageLink, so output it raw
1708 #but don't ignore what might be perfectly normal links in the text we've examined
1709 $text = $this->replaceInternalLinks($text);
1710 $s .= "{$prefix}[[$link|$text";
1711 # note: no $trail, because without an end, there *is* no trail
1712 wfProfileOut( "$fname-might_be_img" );
1715 } else { #it's not an image, so output it raw
1716 $s .= "{$prefix}[[$link|$text";
1717 # note: no $trail, because without an end, there *is* no trail
1718 wfProfileOut( "$fname-might_be_img" );
1721 wfProfileOut( "$fname-might_be_img" );
1724 $wasblank = ( '' == $text );
1725 if( $wasblank ) $text = $link;
1727 # Link not escaped by : , create the various objects
1731 wfProfileIn( "$fname-interwiki" );
1732 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1733 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1734 $s = rtrim($s . $prefix);
1735 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1736 wfProfileOut( "$fname-interwiki" );
1739 wfProfileOut( "$fname-interwiki" );
1741 if ( $ns == NS_IMAGE
) {
1742 wfProfileIn( "$fname-image" );
1743 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1744 # recursively parse links inside the image caption
1745 # actually, this will parse them in any other parameters, too,
1746 # but it might be hard to fix that, and it doesn't matter ATM
1747 $text = $this->replaceExternalLinks($text);
1748 $text = $this->replaceInternalLinks($text);
1750 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1751 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1752 $this->mOutput
->addImage( $nt->getDBkey() );
1754 wfProfileOut( "$fname-image" );
1757 # We still need to record the image's presence on the page
1758 $this->mOutput
->addImage( $nt->getDBkey() );
1760 wfProfileOut( "$fname-image" );
1764 if ( $ns == NS_CATEGORY
) {
1765 wfProfileIn( "$fname-category" );
1766 $s = rtrim($s . "\n"); # bug 87
1769 $sortkey = $this->getDefaultSort();
1773 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1774 $sortkey = str_replace( "\n", '', $sortkey );
1775 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1776 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1779 * Strip the whitespace Category links produce, see bug 87
1780 * @todo We might want to use trim($tmp, "\n") here.
1782 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1784 wfProfileOut( "$fname-category" );
1789 # Self-link checking
1790 if( $nt->getFragment() === '' ) {
1791 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1792 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1797 # Special and Media are pseudo-namespaces; no pages actually exist in them
1798 if( $ns == NS_MEDIA
) {
1799 $link = $sk->makeMediaLinkObj( $nt, $text );
1800 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1801 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1802 $this->mOutput
->addImage( $nt->getDBkey() );
1804 } elseif( $ns == NS_SPECIAL
) {
1805 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1806 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1808 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1811 } elseif( $ns == NS_IMAGE
) {
1812 $img = wfFindFile( $nt );
1814 // Force a blue link if the file exists; may be a remote
1815 // upload on the shared repository, and we want to see its
1816 // auto-generated page.
1817 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1818 $this->mOutput
->addLink( $nt );
1822 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1824 wfProfileOut( $fname );
1829 * Make a link placeholder. The text returned can be later resolved to a real link with
1830 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1831 * parsing of interwiki links, and secondly to allow all existence checks and
1832 * article length checks (for stub links) to be bundled into a single query.
1835 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1836 wfProfileIn( __METHOD__
);
1837 if ( ! is_object($nt) ) {
1839 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1841 # Separate the link trail from the rest of the link
1842 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1844 if ( $nt->isExternal() ) {
1845 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1846 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1847 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1849 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1850 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1851 $this->mLinkHolders
['queries'][] = $query;
1852 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1853 $this->mLinkHolders
['titles'][] = $nt;
1855 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1858 wfProfileOut( __METHOD__
);
1863 * Render a forced-blue link inline; protect against double expansion of
1864 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1865 * Since this little disaster has to split off the trail text to avoid
1866 * breaking URLs in the following text without breaking trails on the
1867 * wiki links, it's been made into a horrible function.
1870 * @param string $text
1871 * @param string $query
1872 * @param string $trail
1873 * @param string $prefix
1874 * @return string HTML-wikitext mix oh yuck
1876 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1877 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1878 $sk = $this->mOptions
->getSkin();
1879 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1880 return $this->armorLinks( $link ) . $trail;
1884 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1885 * going to go through further parsing steps before inline URL expansion.
1887 * In particular this is important when using action=render, which causes
1888 * full URLs to be included.
1890 * Oh man I hate our multi-layer parser!
1892 * @param string more-or-less HTML
1893 * @return string less-or-more HTML with NOPARSE bits
1895 function armorLinks( $text ) {
1896 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1897 "{$this->mUniqPrefix}NOPARSE$1", $text );
1901 * Return true if subpage links should be expanded on this page.
1904 function areSubpagesAllowed() {
1905 # Some namespaces don't allow subpages
1906 global $wgNamespacesWithSubpages;
1907 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1911 * Handle link to subpage if necessary
1912 * @param string $target the source of the link
1913 * @param string &$text the link text, modified as necessary
1914 * @return string the full name of the link
1917 function maybeDoSubpageLink($target, &$text) {
1920 # :Foobar -- override special treatment of prefix (images, language links)
1921 # /Foobar -- convert to CurrentPage/Foobar
1922 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1923 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1924 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1926 $fname = 'Parser::maybeDoSubpageLink';
1927 wfProfileIn( $fname );
1928 $ret = $target; # default return value is no change
1931 $target = trim( $target );
1933 # Some namespaces don't allow subpages,
1934 # so only perform processing if subpages are allowed
1935 if( $this->areSubpagesAllowed() ) {
1936 # Look at the first character
1937 if( $target != '' && $target{0} == '/' ) {
1938 # / at end means we don't want the slash to be shown
1940 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1941 if( $trailingSlashes ) {
1942 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1944 $noslash = substr( $target, 1 );
1947 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1948 if( '' === $text ) {
1950 } # this might be changed for ugliness reasons
1952 # check for .. subpage backlinks
1954 $nodotdot = $target;
1955 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1957 $nodotdot = substr( $nodotdot, 3 );
1959 if($dotdotcount > 0) {
1960 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1961 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1962 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1963 # / at the end means don't show full path
1964 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1965 $nodotdot = substr( $nodotdot, 0, -1 );
1966 if( '' === $text ) {
1970 $nodotdot = trim( $nodotdot );
1971 if( $nodotdot != '' ) {
1972 $ret .= '/' . $nodotdot;
1979 wfProfileOut( $fname );
1984 * Used by doBlockLevels()
1987 /* private */ function closeParagraph() {
1989 if ( '' != $this->mLastSection
) {
1990 $result = '</' . $this->mLastSection
. ">\n";
1992 $this->mInPre
= false;
1993 $this->mLastSection
= '';
1996 # getCommon() returns the length of the longest common substring
1997 # of both arguments, starting at the beginning of both.
1999 /* private */ function getCommon( $st1, $st2 ) {
2000 $fl = strlen( $st1 );
2001 $shorter = strlen( $st2 );
2002 if ( $fl < $shorter ) { $shorter = $fl; }
2004 for ( $i = 0; $i < $shorter; ++
$i ) {
2005 if ( $st1{$i} != $st2{$i} ) { break; }
2009 # These next three functions open, continue, and close the list
2010 # element appropriate to the prefix character passed into them.
2012 /* private */ function openList( $char ) {
2013 $result = $this->closeParagraph();
2015 if ( '*' == $char ) { $result .= '<ul><li>'; }
2016 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2017 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2018 else if ( ';' == $char ) {
2019 $result .= '<dl><dt>';
2020 $this->mDTopen
= true;
2022 else { $result = '<!-- ERR 1 -->'; }
2027 /* private */ function nextItem( $char ) {
2028 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2029 else if ( ':' == $char ||
';' == $char ) {
2031 if ( $this->mDTopen
) { $close = '</dt>'; }
2032 if ( ';' == $char ) {
2033 $this->mDTopen
= true;
2034 return $close . '<dt>';
2036 $this->mDTopen
= false;
2037 return $close . '<dd>';
2040 return '<!-- ERR 2 -->';
2043 /* private */ function closeList( $char ) {
2044 if ( '*' == $char ) { $text = '</li></ul>'; }
2045 else if ( '#' == $char ) { $text = '</li></ol>'; }
2046 else if ( ':' == $char ) {
2047 if ( $this->mDTopen
) {
2048 $this->mDTopen
= false;
2049 $text = '</dt></dl>';
2051 $text = '</dd></dl>';
2054 else { return '<!-- ERR 3 -->'; }
2060 * Make lists from lines starting with ':', '*', '#', etc.
2063 * @return string the lists rendered as HTML
2065 function doBlockLevels( $text, $linestart ) {
2066 $fname = 'Parser::doBlockLevels';
2067 wfProfileIn( $fname );
2069 # Parsing through the text line by line. The main thing
2070 # happening here is handling of block-level elements p, pre,
2071 # and making lists from lines starting with * # : etc.
2073 $textLines = explode( "\n", $text );
2075 $lastPrefix = $output = '';
2076 $this->mDTopen
= $inBlockElem = false;
2078 $paragraphStack = false;
2080 if ( !$linestart ) {
2081 $output .= array_shift( $textLines );
2083 foreach ( $textLines as $oLine ) {
2084 $lastPrefixLength = strlen( $lastPrefix );
2085 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2086 $preOpenMatch = preg_match('/<pre/i', $oLine );
2087 if ( !$this->mInPre
) {
2088 # Multiple prefixes may abut each other for nested lists.
2089 $prefixLength = strspn( $oLine, '*#:;' );
2090 $pref = substr( $oLine, 0, $prefixLength );
2093 $pref2 = str_replace( ';', ':', $pref );
2094 $t = substr( $oLine, $prefixLength );
2095 $this->mInPre
= !empty($preOpenMatch);
2097 # Don't interpret any other prefixes in preformatted text
2099 $pref = $pref2 = '';
2104 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2105 # Same as the last item, so no need to deal with nesting or opening stuff
2106 $output .= $this->nextItem( substr( $pref, -1 ) );
2107 $paragraphStack = false;
2109 if ( substr( $pref, -1 ) == ';') {
2110 # The one nasty exception: definition lists work like this:
2111 # ; title : definition text
2112 # So we check for : in the remainder text to split up the
2113 # title and definition, without b0rking links.
2115 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2117 $output .= $term . $this->nextItem( ':' );
2120 } elseif( $prefixLength ||
$lastPrefixLength ) {
2121 # Either open or close a level...
2122 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2123 $paragraphStack = false;
2125 while( $commonPrefixLength < $lastPrefixLength ) {
2126 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2127 --$lastPrefixLength;
2129 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2130 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2132 while ( $prefixLength > $commonPrefixLength ) {
2133 $char = substr( $pref, $commonPrefixLength, 1 );
2134 $output .= $this->openList( $char );
2136 if ( ';' == $char ) {
2137 # FIXME: This is dupe of code above
2138 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2140 $output .= $term . $this->nextItem( ':' );
2143 ++
$commonPrefixLength;
2145 $lastPrefix = $pref2;
2147 if( 0 == $prefixLength ) {
2148 wfProfileIn( "$fname-paragraph" );
2149 # No prefix (not in list)--go to paragraph mode
2150 // XXX: use a stack for nestable elements like span, table and div
2151 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2152 $closematch = preg_match(
2153 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2154 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2155 if ( $openmatch or $closematch ) {
2156 $paragraphStack = false;
2157 #Â TODO bug 5718: paragraph closed
2158 $output .= $this->closeParagraph();
2159 if ( $preOpenMatch and !$preCloseMatch ) {
2160 $this->mInPre
= true;
2162 if ( $closematch ) {
2163 $inBlockElem = false;
2165 $inBlockElem = true;
2167 } else if ( !$inBlockElem && !$this->mInPre
) {
2168 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2170 if ($this->mLastSection
!= 'pre') {
2171 $paragraphStack = false;
2172 $output .= $this->closeParagraph().'<pre>';
2173 $this->mLastSection
= 'pre';
2175 $t = substr( $t, 1 );
2178 if ( '' == trim($t) ) {
2179 if ( $paragraphStack ) {
2180 $output .= $paragraphStack.'<br />';
2181 $paragraphStack = false;
2182 $this->mLastSection
= 'p';
2184 if ($this->mLastSection
!= 'p' ) {
2185 $output .= $this->closeParagraph();
2186 $this->mLastSection
= '';
2187 $paragraphStack = '<p>';
2189 $paragraphStack = '</p><p>';
2193 if ( $paragraphStack ) {
2194 $output .= $paragraphStack;
2195 $paragraphStack = false;
2196 $this->mLastSection
= 'p';
2197 } else if ($this->mLastSection
!= 'p') {
2198 $output .= $this->closeParagraph().'<p>';
2199 $this->mLastSection
= 'p';
2204 wfProfileOut( "$fname-paragraph" );
2206 // somewhere above we forget to get out of pre block (bug 785)
2207 if($preCloseMatch && $this->mInPre
) {
2208 $this->mInPre
= false;
2210 if ($paragraphStack === false) {
2214 while ( $prefixLength ) {
2215 $output .= $this->closeList( $pref2{$prefixLength-1} );
2218 if ( '' != $this->mLastSection
) {
2219 $output .= '</' . $this->mLastSection
. '>';
2220 $this->mLastSection
= '';
2223 wfProfileOut( $fname );
2228 * Split up a string on ':', ignoring any occurences inside tags
2229 * to prevent illegal overlapping.
2230 * @param string $str the string to split
2231 * @param string &$before set to everything before the ':'
2232 * @param string &$after set to everything after the ':'
2233 * return string the position of the ':', or false if none found
2235 function findColonNoLinks($str, &$before, &$after) {
2236 $fname = 'Parser::findColonNoLinks';
2237 wfProfileIn( $fname );
2239 $pos = strpos( $str, ':' );
2240 if( $pos === false ) {
2242 wfProfileOut( $fname );
2246 $lt = strpos( $str, '<' );
2247 if( $lt === false ||
$lt > $pos ) {
2248 // Easy; no tag nesting to worry about
2249 $before = substr( $str, 0, $pos );
2250 $after = substr( $str, $pos+
1 );
2251 wfProfileOut( $fname );
2255 // Ugly state machine to walk through avoiding tags.
2256 $state = MW_COLON_STATE_TEXT
;
2258 $len = strlen( $str );
2259 for( $i = 0; $i < $len; $i++
) {
2263 // (Using the number is a performance hack for common cases)
2264 case 0: // MW_COLON_STATE_TEXT:
2267 // Could be either a <start> tag or an </end> tag
2268 $state = MW_COLON_STATE_TAGSTART
;
2273 $before = substr( $str, 0, $i );
2274 $after = substr( $str, $i +
1 );
2275 wfProfileOut( $fname );
2278 // Embedded in a tag; don't break it.
2281 // Skip ahead looking for something interesting
2282 $colon = strpos( $str, ':', $i );
2283 if( $colon === false ) {
2284 // Nothing else interesting
2285 wfProfileOut( $fname );
2288 $lt = strpos( $str, '<', $i );
2289 if( $stack === 0 ) {
2290 if( $lt === false ||
$colon < $lt ) {
2292 $before = substr( $str, 0, $colon );
2293 $after = substr( $str, $colon +
1 );
2294 wfProfileOut( $fname );
2298 if( $lt === false ) {
2299 // Nothing else interesting to find; abort!
2300 // We're nested, but there's no close tags left. Abort!
2303 // Skip ahead to next tag start
2305 $state = MW_COLON_STATE_TAGSTART
;
2308 case 1: // MW_COLON_STATE_TAG:
2313 $state = MW_COLON_STATE_TEXT
;
2316 // Slash may be followed by >?
2317 $state = MW_COLON_STATE_TAGSLASH
;
2323 case 2: // MW_COLON_STATE_TAGSTART:
2326 $state = MW_COLON_STATE_CLOSETAG
;
2329 $state = MW_COLON_STATE_COMMENT
;
2332 // Illegal early close? This shouldn't happen D:
2333 $state = MW_COLON_STATE_TEXT
;
2336 $state = MW_COLON_STATE_TAG
;
2339 case 3: // MW_COLON_STATE_CLOSETAG:
2344 wfDebug( "Invalid input in $fname; too many close tags\n" );
2345 wfProfileOut( $fname );
2348 $state = MW_COLON_STATE_TEXT
;
2351 case MW_COLON_STATE_TAGSLASH
:
2353 // Yes, a self-closed tag <blah/>
2354 $state = MW_COLON_STATE_TEXT
;
2356 // Probably we're jumping the gun, and this is an attribute
2357 $state = MW_COLON_STATE_TAG
;
2360 case 5: // MW_COLON_STATE_COMMENT:
2362 $state = MW_COLON_STATE_COMMENTDASH
;
2365 case MW_COLON_STATE_COMMENTDASH
:
2367 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2369 $state = MW_COLON_STATE_COMMENT
;
2372 case MW_COLON_STATE_COMMENTDASHDASH
:
2374 $state = MW_COLON_STATE_TEXT
;
2376 $state = MW_COLON_STATE_COMMENT
;
2380 throw new MWException( "State machine error in $fname" );
2384 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2387 wfProfileOut( $fname );
2392 * Return value of a magic variable (like PAGENAME)
2396 function getVariableValue( $index ) {
2397 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2400 * Some of these require message or data lookups and can be
2401 * expensive to check many times.
2403 static $varCache = array();
2404 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2405 if ( isset( $varCache[$index] ) ) {
2406 return $varCache[$index];
2411 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2414 global $wgLocaltimezone;
2415 if ( isset( $wgLocaltimezone ) ) {
2416 $oldtz = getenv( 'TZ' );
2417 putenv( 'TZ='.$wgLocaltimezone );
2420 wfSuppressWarnings(); // E_STRICT system time bitching
2421 $localTimestamp = date( 'YmdHis', $ts );
2422 $localMonth = date( 'm', $ts );
2423 $localMonthName = date( 'n', $ts );
2424 $localDay = date( 'j', $ts );
2425 $localDay2 = date( 'd', $ts );
2426 $localDayOfWeek = date( 'w', $ts );
2427 $localWeek = date( 'W', $ts );
2428 $localYear = date( 'Y', $ts );
2429 $localHour = date( 'H', $ts );
2430 if ( isset( $wgLocaltimezone ) ) {
2431 putenv( 'TZ='.$oldtz );
2433 wfRestoreWarnings();
2436 case 'currentmonth':
2437 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2438 case 'currentmonthname':
2439 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2440 case 'currentmonthnamegen':
2441 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2442 case 'currentmonthabbrev':
2443 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2445 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2447 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2449 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2450 case 'localmonthname':
2451 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2452 case 'localmonthnamegen':
2453 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2454 case 'localmonthabbrev':
2455 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2457 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2459 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2461 return wfEscapeWikiText( $this->mTitle
->getText() );
2463 return $this->mTitle
->getPartialURL();
2464 case 'fullpagename':
2465 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2466 case 'fullpagenamee':
2467 return $this->mTitle
->getPrefixedURL();
2469 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2470 case 'subpagenamee':
2471 return $this->mTitle
->getSubpageUrlForm();
2472 case 'basepagename':
2473 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2474 case 'basepagenamee':
2475 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2476 case 'talkpagename':
2477 if( $this->mTitle
->canTalk() ) {
2478 $talkPage = $this->mTitle
->getTalkPage();
2479 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2483 case 'talkpagenamee':
2484 if( $this->mTitle
->canTalk() ) {
2485 $talkPage = $this->mTitle
->getTalkPage();
2486 return $talkPage->getPrefixedUrl();
2490 case 'subjectpagename':
2491 $subjPage = $this->mTitle
->getSubjectPage();
2492 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2493 case 'subjectpagenamee':
2494 $subjPage = $this->mTitle
->getSubjectPage();
2495 return $subjPage->getPrefixedUrl();
2497 return $this->mRevisionId
;
2499 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2500 case 'revisionday2':
2501 return substr( $this->getRevisionTimestamp(), 6, 2 );
2502 case 'revisionmonth':
2503 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2504 case 'revisionyear':
2505 return substr( $this->getRevisionTimestamp(), 0, 4 );
2506 case 'revisiontimestamp':
2507 return $this->getRevisionTimestamp();
2509 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2511 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2513 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2515 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2516 case 'subjectspace':
2517 return $this->mTitle
->getSubjectNsText();
2518 case 'subjectspacee':
2519 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2520 case 'currentdayname':
2521 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2523 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2525 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2527 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2529 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2530 // int to remove the padding
2531 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2533 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2534 case 'localdayname':
2535 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2537 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2539 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2541 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2543 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2544 // int to remove the padding
2545 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2547 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2548 case 'numberofarticles':
2549 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2550 case 'numberoffiles':
2551 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2552 case 'numberofusers':
2553 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2554 case 'numberofpages':
2555 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2556 case 'numberofadmins':
2557 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2558 case 'numberofedits':
2559 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2560 case 'currenttimestamp':
2561 return $varCache[$index] = wfTimestampNow();
2562 case 'localtimestamp':
2563 return $varCache[$index] = $localTimestamp;
2564 case 'currentversion':
2565 return $varCache[$index] = SpecialVersion
::getVersion();
2571 return $wgServerName;
2573 return $wgScriptPath;
2574 case 'directionmark':
2575 return $wgContLang->getDirMark();
2576 case 'contentlanguage':
2577 global $wgContLanguageCode;
2578 return $wgContLanguageCode;
2581 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2589 * initialise the magic variables (like CURRENTMONTHNAME)
2593 function initialiseVariables() {
2594 $fname = 'Parser::initialiseVariables';
2595 wfProfileIn( $fname );
2596 $variableIDs = MagicWord
::getVariableIDs();
2598 $this->mVariables
= array();
2599 foreach ( $variableIDs as $id ) {
2600 $mw =& MagicWord
::get( $id );
2601 $mw->addToArray( $this->mVariables
, $id );
2603 wfProfileOut( $fname );
2607 * parse any parentheses in format ((title|part|part))
2608 * and call callbacks to get a replacement text for any found piece
2610 * @param string $text The text to parse
2611 * @param array $callbacks rules in form:
2612 * '{' => array( # opening parentheses
2613 * 'end' => '}', # closing parentheses
2614 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2615 * 3 => callback # replacement callback to call if {{{..}}} is found
2618 * 'min' => 2, # Minimum parenthesis count in cb
2619 * 'max' => 3, # Maximum parenthesis count in cb
2622 function replace_callback ($text, $callbacks) {
2623 wfProfileIn( __METHOD__
);
2624 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2625 $lastOpeningBrace = -1; # last not closed parentheses
2627 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2630 while ( $i < strlen( $text ) ) {
2631 # Find next opening brace, closing brace or pipe
2632 if ( $lastOpeningBrace == -1 ) {
2633 $currentClosing = '';
2634 $search = $validOpeningBraces;
2636 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2637 $search = $validOpeningBraces . '|' . $currentClosing;
2640 $i +
= strcspn( $text, $search, $i );
2641 if ( $i < strlen( $text ) ) {
2642 if ( $text[$i] == '|' ) {
2644 } elseif ( $text[$i] == $currentClosing ) {
2646 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2648 $rule = $callbacks[$text[$i]];
2650 # Some versions of PHP have a strcspn which stops on null characters
2651 # Ignore and continue
2660 if ( $found == 'open' ) {
2661 # found opening brace, let's add it to parentheses stack
2662 $piece = array('brace' => $text[$i],
2663 'braceEnd' => $rule['end'],
2667 # count opening brace characters
2668 $piece['count'] = strspn( $text, $piece['brace'], $i );
2669 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2670 $i +
= $piece['count'];
2672 # we need to add to stack only if opening brace count is enough for one of the rules
2673 if ( $piece['count'] >= $rule['min'] ) {
2674 $lastOpeningBrace ++
;
2675 $openingBraceStack[$lastOpeningBrace] = $piece;
2677 } elseif ( $found == 'close' ) {
2678 # lets check if it is enough characters for closing brace
2679 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2680 $count = strspn( $text, $text[$i], $i, $maxCount );
2682 # check for maximum matching characters (if there are 5 closing
2683 # characters, we will probably need only 3 - depending on the rules)
2685 $matchingCallback = null;
2686 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2687 if ( $count > $cbType['max'] ) {
2688 # The specified maximum exists in the callback array, unless the caller
2690 $matchingCount = $cbType['max'];
2692 # Count is less than the maximum
2693 # Skip any gaps in the callback array to find the true largest match
2694 # Need to use array_key_exists not isset because the callback can be null
2695 $matchingCount = $count;
2696 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2701 if ($matchingCount <= 0) {
2705 $matchingCallback = $cbType['cb'][$matchingCount];
2707 # let's set a title or last part (if '|' was found)
2708 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2709 $openingBraceStack[$lastOpeningBrace]['title'] =
2710 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2711 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2713 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2714 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2715 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2718 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2719 $pieceEnd = $i +
$matchingCount;
2721 if( is_callable( $matchingCallback ) ) {
2723 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2724 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2725 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2726 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2728 # finally we can call a user callback and replace piece of text
2729 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2730 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2731 $i = $pieceStart +
strlen($replaceWith);
2733 # null value for callback means that parentheses should be parsed, but not replaced
2734 $i +
= $matchingCount;
2737 # reset last opening parentheses, but keep it in case there are unused characters
2738 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2739 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2740 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2743 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2744 $openingBraceStack[$lastOpeningBrace--] = null;
2746 if ($matchingCount < $piece['count']) {
2747 $piece['count'] -= $matchingCount;
2748 $piece['startAt'] -= $matchingCount;
2749 $piece['partStart'] = $piece['startAt'];
2750 # do we still qualify for any callback with remaining count?
2751 $currentCbList = $callbacks[$piece['brace']]['cb'];
2752 while ( $piece['count'] ) {
2753 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2754 $lastOpeningBrace++
;
2755 $openingBraceStack[$lastOpeningBrace] = $piece;
2761 } elseif ( $found == 'pipe' ) {
2762 # lets set a title if it is a first separator, or next part otherwise
2763 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2764 $openingBraceStack[$lastOpeningBrace]['title'] =
2765 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2766 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2767 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2769 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2770 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2771 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2773 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2777 wfProfileOut( __METHOD__
);
2782 * Replace magic variables, templates, and template arguments
2783 * with the appropriate text. Templates are substituted recursively,
2784 * taking care to avoid infinite loops.
2786 * Note that the substitution depends on value of $mOutputType:
2787 * OT_WIKI: only {{subst:}} templates
2788 * OT_MSG: only magic variables
2789 * OT_HTML: all templates and magic variables
2791 * @param string $tex The text to transform
2792 * @param array $args Key-value pairs representing template parameters to substitute
2793 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2796 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2797 # Prevent too big inclusions
2798 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2802 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2803 wfProfileIn( $fname );
2805 # This function is called recursively. To keep track of arguments we need a stack:
2806 array_push( $this->mArgStack
, $args );
2808 $braceCallbacks = array();
2810 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2812 if ( $this->mOutputType
!= OT_MSG
) {
2813 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2815 if ( $braceCallbacks ) {
2819 'cb' => $braceCallbacks,
2820 'min' => $argsOnly ?
3 : 2,
2821 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2825 'cb' => array(2=>null),
2830 $text = $this->replace_callback ($text, $callbacks);
2832 array_pop( $this->mArgStack
);
2834 wfProfileOut( $fname );
2839 * Replace magic variables
2842 function variableSubstitution( $matches ) {
2844 $fname = 'Parser::variableSubstitution';
2845 $varname = $wgContLang->lc($matches[1]);
2846 wfProfileIn( $fname );
2848 if ( $this->mOutputType
== OT_WIKI
) {
2849 # Do only magic variables prefixed by SUBST
2850 $mwSubst =& MagicWord
::get( 'subst' );
2851 if (!$mwSubst->matchStartAndRemove( $varname ))
2853 # Note that if we don't substitute the variable below,
2854 # we don't remove the {{subst:}} magic word, in case
2855 # it is a template rather than a magic variable.
2857 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2858 $id = $this->mVariables
[$varname];
2859 # Now check if we did really match, case sensitive or not
2860 $mw =& MagicWord
::get( $id );
2861 if ($mw->match($matches[1])) {
2862 $text = $this->getVariableValue( $id );
2863 $this->mOutput
->mContainsOldMagic
= true;
2865 $text = $matches[0];
2868 $text = $matches[0];
2870 wfProfileOut( $fname );
2875 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2876 static function createAssocArgs( $args ) {
2877 $assocArgs = array();
2879 foreach( $args as $arg ) {
2880 $eqpos = strpos( $arg, '=' );
2881 if ( $eqpos === false ) {
2882 $assocArgs[$index++
] = $arg;
2884 $name = trim( substr( $arg, 0, $eqpos ) );
2885 $value = trim( substr( $arg, $eqpos+
1 ) );
2886 if ( $value === false ) {
2889 if ( $name !== false ) {
2890 $assocArgs[$name] = $value;
2899 * Return the text of a template, after recursively
2900 * replacing any variables or templates within the template.
2902 * @param array $piece The parts of the template
2903 * $piece['text']: matched text
2904 * $piece['title']: the title, i.e. the part before the |
2905 * $piece['parts']: the parameter array
2906 * @return string the text of the template
2909 function braceSubstitution( $piece ) {
2910 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2911 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2912 wfProfileIn( $fname );
2913 wfProfileIn( __METHOD__
.'-setup' );
2916 $found = false; # $text has been filled
2917 $nowiki = false; # wiki markup in $text should be escaped
2918 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2919 $noargs = false; # Don't replace triple-brace arguments in $text
2920 $replaceHeadings = false; # Make the edit section links go to the template not the article
2921 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2922 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2923 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2925 # Title object, where $text came from
2931 # $part1 is the bit before the first |, and must contain only title characters
2932 # $args is a list of arguments, starting from index 0, not including $part1
2934 $titleText = $part1 = $piece['title'];
2935 # If the third subpattern matched anything, it will start with |
2937 if (null == $piece['parts']) {
2938 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2939 if ($replaceWith != $piece['text']) {
2940 $text = $replaceWith;
2947 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2948 wfProfileOut( __METHOD__
.'-setup' );
2951 wfProfileIn( __METHOD__
.'-modifiers' );
2953 $mwSubst =& MagicWord
::get( 'subst' );
2954 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2955 # One of two possibilities is true:
2956 # 1) Found SUBST but not in the PST phase
2957 # 2) Didn't find SUBST and in the PST phase
2958 # In either case, return without further processing
2959 $text = $piece['text'];
2966 # MSG, MSGNW and RAW
2969 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2970 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2973 # Remove obsolete MSG:
2974 $mwMsg =& MagicWord
::get( 'msg' );
2975 $mwMsg->matchStartAndRemove( $part1 );
2979 $mwRaw =& MagicWord
::get( 'raw' );
2980 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2981 $forceRawInterwiki = true;
2984 wfProfileOut( __METHOD__
.'-modifiers' );
2986 //save path level before recursing into functions & templates.
2987 $lastPathLevel = $this->mTemplatePath
;
2991 wfProfileIn( __METHOD__
. '-pfunc' );
2993 $colonPos = strpos( $part1, ':' );
2994 if ( $colonPos !== false ) {
2995 # Case sensitive functions
2996 $function = substr( $part1, 0, $colonPos );
2997 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2998 $function = $this->mFunctionSynonyms
[1][$function];
3000 # Case insensitive functions
3001 $function = strtolower( $function );
3002 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3003 $function = $this->mFunctionSynonyms
[0][$function];
3009 $funcArgs = array_map( 'trim', $args );
3010 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
3011 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
3014 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3018 if ( is_array( $result ) ) {
3019 if ( isset( $result[0] ) ) {
3020 $text = $linestart . $result[0];
3021 unset( $result[0] );
3024 // Extract flags into the local scope
3025 // This allows callers to set flags such as nowiki, noparse, found, etc.
3028 $text = $linestart . $result;
3032 wfProfileOut( __METHOD__
. '-pfunc' );
3035 # Template table test
3037 # Did we encounter this template already? If yes, it is in the cache
3038 # and we need to check for loops.
3039 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3042 # Infinite loop test
3043 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3047 $text = $linestart .
3048 "[[$part1]]<!-- WARNING: template loop detected -->";
3049 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3051 # set $text to cached message.
3052 $text = $linestart . $this->mTemplates
[$piece['title']];
3053 #treat title for cached page the same as others
3056 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3057 if ($subpage !== '') {
3058 $ns = $this->mTitle
->getNamespace();
3060 $title = Title
::newFromText( $part1, $ns );
3061 //used by include size checking
3062 $titleText = $title->getPrefixedText();
3063 //used by edit section links
3064 $replaceHeadings = true;
3069 # Load from database
3071 wfProfileIn( __METHOD__
. '-loadtpl' );
3073 # declaring $subpage directly in the function call
3074 # does not work correctly with references and breaks
3075 # {{/subpage}}-style inclusions
3077 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3078 if ($subpage !== '') {
3079 $ns = $this->mTitle
->getNamespace();
3081 $title = Title
::newFromText( $part1, $ns );
3084 if ( !is_null( $title ) ) {
3085 $titleText = $title->getPrefixedText();
3086 # Check for language variants if the template is not found
3087 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3088 $wgContLang->findVariantLink($part1, $title);
3091 if ( !$title->isExternal() ) {
3092 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3093 $text = SpecialPage
::capturePath( $title );
3094 if ( is_string( $text ) ) {
3099 $this->disableCache();
3101 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3102 $found = false; //access denied
3103 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3105 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3106 if ( $articleContent !== false ) {
3108 $text = $articleContent;
3109 $replaceHeadings = true;
3113 # If the title is valid but undisplayable, make a link to it
3114 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3115 $text = "[[:$titleText]]";
3118 } elseif ( $title->isTrans() ) {
3119 // Interwiki transclusion
3120 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3121 $text = $this->interwikiTransclude( $title, 'render' );
3125 $text = $this->interwikiTransclude( $title, 'raw' );
3126 $replaceHeadings = true;
3131 # Template cache array insertion
3132 # Use the original $piece['title'] not the mangled $part1, so that
3133 # modifiers such as RAW: produce separate cache entries
3136 // A special page; don't store it in the template cache.
3138 $this->mTemplates
[$piece['title']] = $text;
3140 $text = $linestart . $text;
3143 wfProfileOut( __METHOD__
. '-loadtpl' );
3146 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3147 # Error, oversize inclusion
3148 $text = $linestart .
3149 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3154 # Recursive parsing, escaping and link table handling
3155 # Only for HTML output
3156 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3157 $text = wfEscapeWikiText( $text );
3158 } elseif ( !$this->ot
['msg'] && $found ) {
3160 $assocArgs = array();
3162 # Clean up argument array
3163 $assocArgs = self
::createAssocArgs($args);
3164 # Add a new element to the templace recursion path
3165 $this->mTemplatePath
[$part1] = 1;
3169 # If there are any <onlyinclude> tags, only include them
3170 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3171 $replacer = new OnlyIncludeReplacer
;
3172 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3173 array( &$replacer, 'replace' ), $text );
3174 $text = $replacer->output
;
3176 # Remove <noinclude> sections and <includeonly> tags
3177 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3178 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3180 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3181 # Strip <nowiki>, <pre>, etc.
3182 $text = $this->strip( $text, $this->mStripState
);
3183 if ( $this->ot
['html'] ) {
3184 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3185 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3186 $text = Sanitizer
::removeHTMLcomments( $text );
3189 $text = $this->replaceVariables( $text, $assocArgs );
3191 # If the template begins with a table or block-level
3192 # element, it should be treated as beginning a new line.
3193 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3194 $text = "\n" . $text;
3196 } elseif ( !$noargs ) {
3197 # $noparse and !$noargs
3198 # Just replace the arguments, not any double-brace items
3199 # This is used for rendered interwiki transclusion
3200 $text = $this->replaceVariables( $text, $assocArgs, true );
3203 # Prune lower levels off the recursion check path
3204 $this->mTemplatePath
= $lastPathLevel;
3206 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3207 # Error, oversize inclusion
3208 $text = $linestart .
3209 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3215 wfProfileOut( $fname );
3216 return $piece['text'];
3218 wfProfileIn( __METHOD__
. '-placeholders' );
3220 # Replace raw HTML by a placeholder
3221 # Add a blank line preceding, to prevent it from mucking up
3222 # immediately preceding headings
3223 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3225 # replace ==section headers==
3226 # XXX this needs to go away once we have a better parser.
3227 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3228 if( !is_null( $title ) )
3229 $encodedname = base64_encode($title->getPrefixedDBkey());
3231 $encodedname = base64_encode("");
3232 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3233 PREG_SPLIT_DELIM_CAPTURE
);
3235 $nsec = $headingOffset;
3237 for( $i = 0; $i < count($m); $i +
= 2 ) {
3239 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3241 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3246 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3247 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3248 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3254 wfProfileOut( __METHOD__
. '-placeholders' );
3257 # Prune lower levels off the recursion check path
3258 $this->mTemplatePath
= $lastPathLevel;
3261 wfProfileOut( $fname );
3262 return $piece['text'];
3264 wfProfileOut( $fname );
3270 * Fetch the unparsed text of a template and register a reference to it.
3272 function fetchTemplateAndtitle( $title ) {
3273 $text = $skip = false;
3274 $finalTitle = $title;
3275 // Loop to fetch the article, with up to 1 redirect
3276 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3277 # Give extensions a chance to select the revision instead
3278 $id = false; // Assume current
3279 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( &$this, &$title, &$skip, &$id ) );
3283 $this->mOutput
->addTemplate( $title, $title->getArticleID(), null );
3286 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3287 $rev_id = $rev ?
$rev->getId() : 0;
3289 $this->mOutput
->addTemplate( $title, $title->getArticleID(), $rev_id );
3292 $text = $rev->getText();
3293 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3295 $message = $wgLang->lcfirst( $title->getText() );
3296 $text = wfMsgForContentNoTrans( $message );
3297 if( wfEmptyMsg( $message, $text ) ) {
3304 if ( $text === false ) {
3308 $finalTitle = $title;
3309 $title = Title
::newFromRedirect( $text );
3311 return array($text,$finalTitle);
3314 function fetchTemplate( $title ) {
3315 $rv = $this->fetchTemplateAndtitle($title);
3320 * Transclude an interwiki link.
3322 function interwikiTransclude( $title, $action ) {
3323 global $wgEnableScaryTranscluding;
3325 if (!$wgEnableScaryTranscluding)
3326 return wfMsg('scarytranscludedisabled');
3328 $url = $title->getFullUrl( "action=$action" );
3330 if (strlen($url) > 255)
3331 return wfMsg('scarytranscludetoolong');
3332 return $this->fetchScaryTemplateMaybeFromCache($url);
3335 function fetchScaryTemplateMaybeFromCache($url) {
3336 global $wgTranscludeCacheExpiry;
3337 $dbr = wfGetDB(DB_SLAVE
);
3338 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3339 array('tc_url' => $url));
3341 $time = $obj->tc_time
;
3342 $text = $obj->tc_contents
;
3343 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3348 $text = Http
::get($url);
3350 return wfMsg('scarytranscludefailed', $url);
3352 $dbw = wfGetDB(DB_MASTER
);
3353 $dbw->replace('transcache', array('tc_url'), array(
3355 'tc_time' => time(),
3356 'tc_contents' => $text));
3362 * Triple brace replacement -- used for template arguments
3365 function argSubstitution( $matches ) {
3366 $arg = trim( $matches['title'] );
3367 $text = $matches['text'];
3368 $inputArgs = end( $this->mArgStack
);
3370 if ( array_key_exists( $arg, $inputArgs ) ) {
3371 $text = $inputArgs[$arg];
3372 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3373 null != $matches['parts'] && count($matches['parts']) > 0) {
3374 $text = $matches['parts'][0];
3376 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3377 $text = $matches['text'] .
3378 '<!-- WARNING: argument omitted, expansion size too large -->';
3385 * Increment an include size counter
3387 * @param string $type The type of expansion
3388 * @param integer $size The size of the text
3389 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3391 function incrementIncludeSize( $type, $size ) {
3392 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3395 $this->mIncludeSizes
[$type] +
= $size;
3401 * Detect __NOGALLERY__ magic word and set a placeholder
3403 function stripNoGallery( &$text ) {
3404 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3406 $mw = MagicWord
::get( 'nogallery' );
3407 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3411 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3412 * placeholder that will then be replaced by the real TOC in
3413 * ->formatHeadings, this works because at this points real
3414 * comments will have already been discarded by the sanitizer.
3416 * Any additional __TOC__ magic words left over will be discarded
3417 * as there can only be one TOC on the page.
3419 function stripToc( $text ) {
3420 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3422 $mw = MagicWord
::get( 'notoc' );
3423 if( $mw->matchAndRemove( $text ) ) {
3424 $this->mShowToc
= false;
3427 $mw = MagicWord
::get( 'toc' );
3428 if( $mw->match( $text ) ) {
3429 $this->mShowToc
= true;
3430 $this->mForceTocPosition
= true;
3432 // Set a placeholder. At the end we'll fill it in with the TOC.
3433 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3435 // Only keep the first one.
3436 $text = $mw->replace( '', $text );
3442 * This function accomplishes several tasks:
3443 * 1) Auto-number headings if that option is enabled
3444 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3445 * 3) Add a Table of contents on the top for users who have enabled the option
3446 * 4) Auto-anchor headings
3448 * It loops through all headlines, collects the necessary data, then splits up the
3449 * string and re-inserts the newly formatted headlines.
3451 * @param string $text
3452 * @param boolean $isMain
3455 function formatHeadings( $text, $isMain=true ) {
3456 global $wgMaxTocLevel, $wgContLang;
3458 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3459 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3462 $showEditLink = $this->mOptions
->getEditSection();
3465 # Inhibit editsection links if requested in the page
3466 $esw =& MagicWord
::get( 'noeditsection' );
3467 if( $esw->matchAndRemove( $text ) ) {
3471 # Get all headlines for numbering them and adding funky stuff like [edit]
3472 # links - this is for later, but we need the number of headlines right now
3474 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3476 # if there are fewer than 4 headlines in the article, do not show TOC
3477 # unless it's been explicitly enabled.
3478 $enoughToc = $this->mShowToc
&&
3479 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3481 # Allow user to stipulate that a page should have a "new section"
3482 # link added via __NEWSECTIONLINK__
3483 $mw =& MagicWord
::get( 'newsectionlink' );
3484 if( $mw->matchAndRemove( $text ) )
3485 $this->mOutput
->setNewSection( true );
3487 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3488 # override above conditions and always show TOC above first header
3489 $mw =& MagicWord
::get( 'forcetoc' );
3490 if ($mw->matchAndRemove( $text ) ) {
3491 $this->mShowToc
= true;
3495 # We need this to perform operations on the HTML
3496 $sk = $this->mOptions
->getSkin();
3500 $sectionCount = 0; # headlineCount excluding template sections
3503 # Ugh .. the TOC should have neat indentation levels which can be
3504 # passed to the skin functions. These are determined here
3508 $sublevelCount = array();
3509 $levelCount = array();
3516 foreach( $matches[3] as $headline ) {
3518 $templatetitle = '';
3519 $templatesection = 0;
3522 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3524 $templatetitle = base64_decode($mat[1]);
3525 $templatesection = 1 +
(int)base64_decode($mat[2]);
3526 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3530 $prevlevel = $level;
3531 $prevtoclevel = $toclevel;
3533 $level = $matches[1][$headlineCount];
3535 if( $doNumberHeadings ||
$enoughToc ) {
3537 if ( $level > $prevlevel ) {
3538 # Increase TOC level
3540 $sublevelCount[$toclevel] = 0;
3541 if( $toclevel<$wgMaxTocLevel ) {
3542 $prevtoclevel = $toclevel;
3543 $toc .= $sk->tocIndent();
3547 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3548 # Decrease TOC level, find level to jump to
3550 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3551 # Can only go down to level 1
3554 for ($i = $toclevel; $i > 0; $i--) {
3555 if ( $levelCount[$i] == $level ) {
3556 # Found last matching level
3560 elseif ( $levelCount[$i] < $level ) {
3561 # Found first matching level below current level
3567 if( $toclevel<$wgMaxTocLevel ) {
3568 if($prevtoclevel < $wgMaxTocLevel) {
3569 # Unindent only if the previous toc level was shown :p
3570 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3572 $toc .= $sk->tocLineEnd();
3577 # No change in level, end TOC line
3578 if( $toclevel<$wgMaxTocLevel ) {
3579 $toc .= $sk->tocLineEnd();
3583 $levelCount[$toclevel] = $level;
3585 # count number of headlines for each level
3586 @$sublevelCount[$toclevel]++
;
3588 for( $i = 1; $i <= $toclevel; $i++
) {
3589 if( !empty( $sublevelCount[$i] ) ) {
3593 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3599 # The canonized header is a version of the header text safe to use for links
3600 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3601 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3603 # Remove link placeholders by the link text.
3604 # <!--LINK number-->
3606 # link text with suffix
3607 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3608 "\$this->mLinkHolders['texts'][\$1]",
3609 $canonized_headline );
3610 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3611 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3612 $canonized_headline );
3615 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3616 $tocline = trim( $canonized_headline );
3617 # Save headline for section edit hint before it's escaped
3618 $headline_hint = trim( $canonized_headline );
3619 $canonized_headline = Sanitizer
::escapeId( $tocline );
3620 $refers[$headlineCount] = $canonized_headline;
3622 # count how many in assoc. array so we can track dupes in anchors
3623 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3624 $refcount[$headlineCount]=$refers[$canonized_headline];
3626 # Don't number the heading if it is the only one (looks silly)
3627 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3628 # the two are different if the line contains a link
3629 $headline=$numbering . ' ' . $headline;
3632 # Create the anchor for linking from the TOC to the section
3633 $anchor = $canonized_headline;
3634 if($refcount[$headlineCount] > 1 ) {
3635 $anchor .= '_' . $refcount[$headlineCount];
3637 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3638 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3640 # give headline the correct <h#> tag
3641 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3643 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3645 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3649 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3656 # Never ever show TOC if no headers
3657 if( $numVisible < 1 ) {
3662 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3663 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3665 $toc = $sk->tocList( $toc );
3668 # split up and insert constructed headlines
3670 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3673 foreach( $blocks as $block ) {
3674 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3675 # This is the [edit] link that appears for the top block of text when
3676 # section editing is enabled
3678 # Disabled because it broke block formatting
3679 # For example, a bullet point in the top line
3680 # $full .= $sk->editSectionLink(0);
3683 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3684 # Top anchor now in skin
3688 if( !empty( $head[$i] ) ) {
3693 if( $this->mForceTocPosition
) {
3694 return str_replace( '<!--MWTOC-->', $toc, $full );
3701 * Transform wiki markup when saving a page by doing \r\n -> \n
3702 * conversion, substitting signatures, {{subst:}} templates, etc.
3704 * @param string $text the text to transform
3705 * @param Title &$title the Title object for the current article
3706 * @param User &$user the User object describing the current user
3707 * @param ParserOptions $options parsing options
3708 * @param bool $clearState whether to clear the parser state first
3709 * @return string the altered wiki markup
3712 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3713 $this->mOptions
= $options;
3714 $this->mTitle
=& $title;
3715 $this->setOutputType( OT_WIKI
);
3717 if ( $clearState ) {
3718 $this->clearState();
3721 $stripState = new StripState
;
3725 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3726 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3727 $text = $this->pstPass2( $text, $stripState, $user );
3728 $text = $stripState->unstripBoth( $text );
3733 * Pre-save transform helper function
3736 function pstPass2( $text, &$stripState, $user ) {
3737 global $wgContLang, $wgLocaltimezone;
3739 /* Note: This is the timestamp saved as hardcoded wikitext to
3740 * the database, we use $wgContLang here in order to give
3741 * everyone the same signature and use the default one rather
3742 * than the one selected in each user's preferences.
3744 if ( isset( $wgLocaltimezone ) ) {
3745 $oldtz = getenv( 'TZ' );
3746 putenv( 'TZ='.$wgLocaltimezone );
3748 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3749 ' (' . date( 'T' ) . ')';
3750 if ( isset( $wgLocaltimezone ) ) {
3751 putenv( 'TZ='.$oldtz );
3754 # Variable replacement
3755 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3756 $text = $this->replaceVariables( $text );
3758 # Strip out <nowiki> etc. added via replaceVariables
3759 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3762 $sigText = $this->getUserSig( $user );
3763 $text = strtr( $text, array(
3765 '~~~~' => "$sigText $d",
3769 # Context links: [[|name]] and [[name (context)|]]
3771 global $wgLegalTitleChars;
3772 $tc = "[$wgLegalTitleChars]";
3773 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3775 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3776 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3777 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3779 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3780 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3781 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3783 $t = $this->mTitle
->getText();
3785 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3786 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3787 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3788 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3790 # if there's no context, don't bother duplicating the title
3791 $text = preg_replace( $p2, '[[\\1]]', $text );
3794 # Trim trailing whitespace
3795 $text = rtrim( $text );
3801 * Fetch the user's signature text, if any, and normalize to
3802 * validated, ready-to-insert wikitext.
3808 function getUserSig( &$user ) {
3809 global $wgMaxSigChars;
3811 $username = $user->getName();
3812 $nickname = $user->getOption( 'nickname' );
3813 $nickname = $nickname === '' ?
$username : $nickname;
3815 if( strlen( $nickname ) > $wgMaxSigChars ) {
3816 $nickname = $username;
3817 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3818 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3819 # Sig. might contain markup; validate this
3820 if( $this->validateSig( $nickname ) !== false ) {
3821 # Validated; clean up (if needed) and return it
3822 return $this->cleanSig( $nickname, true );
3824 # Failed to validate; fall back to the default
3825 $nickname = $username;
3826 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3830 // Make sure nickname doesnt get a sig in a sig
3831 $nickname = $this->cleanSigInSig( $nickname );
3833 # If we're still here, make it a link to the user page
3834 $userpage = $user->getUserPage();
3835 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3839 * Check that the user's signature contains no bad XML
3841 * @param string $text
3842 * @return mixed An expanded string, or false if invalid.
3844 function validateSig( $text ) {
3845 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3849 * Clean up signature text
3851 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3852 * 2) Substitute all transclusions
3854 * @param string $text
3855 * @param $parsing Whether we're cleaning (preferences save) or parsing
3856 * @return string Signature text
3858 function cleanSig( $text, $parsing = false ) {
3860 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3862 $substWord = MagicWord
::get( 'subst' );
3863 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3864 $substText = '{{' . $substWord->getSynonym( 0 );
3866 $text = preg_replace( $substRegex, $substText, $text );
3867 $text = $this->cleanSigInSig( $text );
3868 $text = $this->replaceVariables( $text );
3870 $this->clearState();
3875 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3876 * @param string $text
3877 * @return string Signature text with /~{3,5}/ removed
3879 function cleanSigInSig( $text ) {
3880 $text = preg_replace( '/~{3,5}/', '', $text );
3885 * Set up some variables which are usually set up in parse()
3886 * so that an external function can call some class members with confidence
3889 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3890 $this->mTitle
=& $title;
3891 $this->mOptions
= $options;
3892 $this->setOutputType( $outputType );
3893 if ( $clearState ) {
3894 $this->clearState();
3899 * Transform a MediaWiki message by replacing magic variables.
3901 * @param string $text the text to transform
3902 * @param ParserOptions $options options
3903 * @return string the text with variables substituted
3906 function transformMsg( $text, $options ) {
3908 static $executing = false;
3910 $fname = "Parser::transformMsg";
3912 # Guard against infinite recursion
3918 wfProfileIn($fname);
3920 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3921 $this->mTitle
= $wgTitle;
3923 $this->mTitle
= Title
::newFromText('msg');
3925 $this->mOptions
= $options;
3926 $this->setOutputType( OT_MSG
);
3927 $this->clearState();
3928 $text = $this->replaceVariables( $text );
3931 wfProfileOut($fname);
3936 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3937 * The callback should have the following form:
3938 * function myParserHook( $text, $params, &$parser ) { ... }
3940 * Transform and return $text. Use $parser for any required context, e.g. use
3941 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3945 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3946 * @param mixed $callback The callback function (and object) to use for the tag
3948 * @return The old value of the mTagHooks array associated with the hook
3950 function setHook( $tag, $callback ) {
3951 $tag = strtolower( $tag );
3952 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3953 $this->mTagHooks
[$tag] = $callback;
3959 * Create a function, e.g. {{sum:1|2|3}}
3960 * The callback function should have the form:
3961 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3963 * The callback may either return the text result of the function, or an array with the text
3964 * in element 0, and a number of flags in the other elements. The names of the flags are
3965 * specified in the keys. Valid flags are:
3966 * found The text returned is valid, stop processing the template. This
3968 * nowiki Wiki markup in the return value should be escaped
3969 * noparse Unsafe HTML tags should not be stripped, etc.
3970 * noargs Don't replace triple-brace arguments in the return value
3971 * isHTML The returned text is HTML, armour it against wikitext transformation
3975 * @param string $id The magic word ID
3976 * @param mixed $callback The callback function (and object) to use
3977 * @param integer $flags a combination of the following flags:
3978 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3980 * @return The old callback function for this name, if any
3982 function setFunctionHook( $id, $callback, $flags = 0 ) {
3983 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3984 $this->mFunctionHooks
[$id] = $callback;
3986 # Add to function cache
3987 $mw = MagicWord
::get( $id );
3989 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3991 $synonyms = $mw->getSynonyms();
3992 $sensitive = intval( $mw->isCaseSensitive() );
3994 foreach ( $synonyms as $syn ) {
3996 if ( !$sensitive ) {
3997 $syn = strtolower( $syn );
4000 if ( !( $flags & SFH_NO_HASH
) ) {
4003 # Remove trailing colon
4004 if ( substr( $syn, -1, 1 ) == ':' ) {
4005 $syn = substr( $syn, 0, -1 );
4007 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4013 * Get all registered function hook identifiers
4017 function getFunctionHooks() {
4018 return array_keys( $this->mFunctionHooks
);
4022 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4023 * Placeholders created in Skin::makeLinkObj()
4024 * Returns an array of links found, indexed by PDBK:
4028 * $options is a bit field, RLH_FOR_UPDATE to select for update
4030 function replaceLinkHolders( &$text, $options = 0 ) {
4034 $fname = 'Parser::replaceLinkHolders';
4035 wfProfileIn( $fname );
4039 $sk = $this->mOptions
->getSkin();
4040 $linkCache =& LinkCache
::singleton();
4042 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4043 wfProfileIn( $fname.'-check' );
4044 $dbr = wfGetDB( DB_SLAVE
);
4045 $page = $dbr->tableName( 'page' );
4046 $threshold = $wgUser->getOption('stubthreshold');
4049 asort( $this->mLinkHolders
['namespaces'] );
4054 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4056 $title = $this->mLinkHolders
['titles'][$key];
4058 # Skip invalid entries.
4059 # Result will be ugly, but prevents crash.
4060 if ( is_null( $title ) ) {
4063 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4065 # Check if it's a static known link, e.g. interwiki
4066 if ( $title->isAlwaysKnown() ) {
4067 $colours[$pdbk] = 1;
4068 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4069 $colours[$pdbk] = 1;
4070 $this->mOutput
->addLink( $title, $id );
4071 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4072 $colours[$pdbk] = 0;
4073 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4074 $colours[$pdbk] = 0;
4076 # Not in the link cache, add it to the query
4077 if ( !isset( $current ) ) {
4079 $query = "SELECT page_id, page_namespace, page_title";
4080 if ( $threshold > 0 ) {
4081 $query .= ', page_len, page_is_redirect';
4083 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4084 } elseif ( $current != $ns ) {
4086 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4091 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4096 if ( $options & RLH_FOR_UPDATE
) {
4097 $query .= ' FOR UPDATE';
4100 $res = $dbr->query( $query, $fname );
4102 # Fetch data and form into an associative array
4103 # non-existent = broken
4106 while ( $s = $dbr->fetchObject($res) ) {
4107 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4108 $pdbk = $title->getPrefixedDBkey();
4109 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4110 $this->mOutput
->addLink( $title, $s->page_id
);
4112 $colours[$pdbk] = ( $threshold == 0 ||
(
4113 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4114 $s->page_is_redirect ||
4115 !Namespace::isContent( $s->page_namespace
) )
4119 wfProfileOut( $fname.'-check' );
4121 # Do a second query for different language variants of links and categories
4122 if($wgContLang->hasVariants()){
4123 $linkBatch = new LinkBatch();
4124 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4125 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4126 $varCategories = array(); // category replacements oldDBkey => newDBkey
4128 $categories = $this->mOutput
->getCategoryLinks();
4130 // Add variants of links to link batch
4131 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4132 $title = $this->mLinkHolders
['titles'][$key];
4133 if ( is_null( $title ) )
4136 $pdbk = $title->getPrefixedDBkey();
4137 $titleText = $title->getText();
4139 // generate all variants of the link title text
4140 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4142 // if link was not found (in first query), add all variants to query
4143 if ( !isset($colours[$pdbk]) ){
4144 foreach($allTextVariants as $textVariant){
4145 if($textVariant != $titleText){
4146 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4147 if(is_null($variantTitle)) continue;
4148 $linkBatch->addObj( $variantTitle );
4149 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4155 // process categories, check if a category exists in some variant
4156 foreach( $categories as $category ){
4157 $variants = $wgContLang->convertLinkToAllVariants($category);
4158 foreach($variants as $variant){
4159 if($variant != $category){
4160 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4161 if(is_null($variantTitle)) continue;
4162 $linkBatch->addObj( $variantTitle );
4163 $categoryMap[$variant] = $category;
4169 if(!$linkBatch->isEmpty()){
4171 $titleClause = $linkBatch->constructSet('page', $dbr);
4173 $variantQuery = "SELECT page_id, page_namespace, page_title";
4174 if ( $threshold > 0 ) {
4175 $variantQuery .= ', page_len, page_is_redirect';
4178 $variantQuery .= " FROM $page WHERE $titleClause";
4179 if ( $options & RLH_FOR_UPDATE
) {
4180 $variantQuery .= ' FOR UPDATE';
4183 $varRes = $dbr->query( $variantQuery, $fname );
4185 // for each found variants, figure out link holders and replace
4186 while ( $s = $dbr->fetchObject($varRes) ) {
4188 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4189 $varPdbk = $variantTitle->getPrefixedDBkey();
4190 $vardbk = $variantTitle->getDBkey();
4192 $holderKeys = array();
4193 if(isset($variantMap[$varPdbk])){
4194 $holderKeys = $variantMap[$varPdbk];
4195 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4196 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4199 // loop over link holders
4200 foreach($holderKeys as $key){
4201 $title = $this->mLinkHolders
['titles'][$key];
4202 if ( is_null( $title ) ) continue;
4204 $pdbk = $title->getPrefixedDBkey();
4206 if(!isset($colours[$pdbk])){
4207 // found link in some of the variants, replace the link holder data
4208 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4209 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4211 // set pdbk and colour
4212 $pdbks[$key] = $varPdbk;
4213 if ( $threshold > 0 ) {
4214 $size = $s->page_len
;
4215 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4216 $colours[$varPdbk] = 1;
4218 $colours[$varPdbk] = 2;
4222 $colours[$varPdbk] = 1;
4227 // check if the object is a variant of a category
4228 if(isset($categoryMap[$vardbk])){
4229 $oldkey = $categoryMap[$vardbk];
4230 if($oldkey != $vardbk)
4231 $varCategories[$oldkey]=$vardbk;
4235 // rebuild the categories in original order (if there are replacements)
4236 if(count($varCategories)>0){
4238 $originalCats = $this->mOutput
->getCategories();
4239 foreach($originalCats as $cat => $sortkey){
4240 // make the replacement
4241 if( array_key_exists($cat,$varCategories) )
4242 $newCats[$varCategories[$cat]] = $sortkey;
4243 else $newCats[$cat] = $sortkey;
4245 $this->mOutput
->setCategoryLinks($newCats);
4250 # Construct search and replace arrays
4251 wfProfileIn( $fname.'-construct' );
4252 $replacePairs = array();
4253 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4254 $pdbk = $pdbks[$key];
4255 $searchkey = "<!--LINK $key-->";
4256 $title = $this->mLinkHolders
['titles'][$key];
4257 if ( empty( $colours[$pdbk] ) ) {
4258 $linkCache->addBadLinkObj( $title );
4259 $colours[$pdbk] = 0;
4260 $this->mOutput
->addLink( $title, 0 );
4261 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4262 $this->mLinkHolders
['texts'][$key],
4263 $this->mLinkHolders
['queries'][$key] );
4264 } elseif ( $colours[$pdbk] == 1 ) {
4265 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4266 $this->mLinkHolders
['texts'][$key],
4267 $this->mLinkHolders
['queries'][$key] );
4268 } elseif ( $colours[$pdbk] == 2 ) {
4269 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4270 $this->mLinkHolders
['texts'][$key],
4271 $this->mLinkHolders
['queries'][$key] );
4274 $replacer = new HashtableReplacer( $replacePairs, 1 );
4275 wfProfileOut( $fname.'-construct' );
4278 wfProfileIn( $fname.'-replace' );
4279 $text = preg_replace_callback(
4280 '/(<!--LINK .*?-->)/',
4284 wfProfileOut( $fname.'-replace' );
4287 # Now process interwiki link holders
4288 # This is quite a bit simpler than internal links
4289 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4290 wfProfileIn( $fname.'-interwiki' );
4291 # Make interwiki link HTML
4292 $replacePairs = array();
4293 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4294 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4295 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4297 $replacer = new HashtableReplacer( $replacePairs, 1 );
4299 $text = preg_replace_callback(
4300 '/<!--IWLINK (.*?)-->/',
4303 wfProfileOut( $fname.'-interwiki' );
4306 wfProfileOut( $fname );
4311 * Replace <!--LINK--> link placeholders with plain text of links
4312 * (not HTML-formatted).
4313 * @param string $text
4316 function replaceLinkHoldersText( $text ) {
4317 $fname = 'Parser::replaceLinkHoldersText';
4318 wfProfileIn( $fname );
4320 $text = preg_replace_callback(
4321 '/<!--(LINK|IWLINK) (.*?)-->/',
4322 array( &$this, 'replaceLinkHoldersTextCallback' ),
4325 wfProfileOut( $fname );
4330 * @param array $matches
4334 function replaceLinkHoldersTextCallback( $matches ) {
4335 $type = $matches[1];
4337 if( $type == 'LINK' ) {
4338 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4339 return $this->mLinkHolders
['texts'][$key];
4341 } elseif( $type == 'IWLINK' ) {
4342 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4343 return $this->mInterwikiLinkHolders
['texts'][$key];
4350 * Tag hook handler for 'pre'.
4352 function renderPreTag( $text, $attribs ) {
4353 // Backwards-compatibility hack
4354 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4356 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4357 return wfOpenElement( 'pre', $attribs ) .
4358 Xml
::escapeTagsOnly( $content ) .
4363 * Renders an image gallery from a text with one line per image.
4364 * text labels may be given by using |-style alternative text. E.g.
4365 * Image:one.jpg|The number "1"
4366 * Image:tree.jpg|A tree
4367 * given as text will return the HTML of a gallery with two images,
4368 * labeled 'The number "1"' and
4371 function renderImageGallery( $text, $params ) {
4372 $ig = new ImageGallery();
4373 $ig->setContextTitle( $this->mTitle
);
4374 $ig->setShowBytes( false );
4375 $ig->setShowFilename( false );
4377 $ig->useSkin( $this->mOptions
->getSkin() );
4378 $ig->mRevisionId
= $this->mRevisionId
;
4380 if( isset( $params['caption'] ) ) {
4381 $caption = $params['caption'];
4382 $caption = htmlspecialchars( $caption );
4383 $caption = $this->replaceInternalLinks( $caption );
4384 $ig->setCaptionHtml( $caption );
4386 if( isset( $params['perrow'] ) ) {
4387 $ig->setPerRow( $params['perrow'] );
4389 if( isset( $params['widths'] ) ) {
4390 $ig->setWidths( $params['widths'] );
4392 if( isset( $params['heights'] ) ) {
4393 $ig->setHeights( $params['heights'] );
4396 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4398 $lines = explode( "\n", $text );
4399 foreach ( $lines as $line ) {
4400 # match lines like these:
4401 # Image:someimage.jpg|This is some image
4403 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4405 if ( count( $matches ) == 0 ) {
4408 $tp = Title
::newFromText( $matches[1] );
4410 if( is_null( $nt ) ) {
4411 # Bogus title. Ignore these so we don't bomb out later.
4414 if ( isset( $matches[3] ) ) {
4415 $label = $matches[3];
4420 $pout = $this->parse( $label,
4423 false, // Strip whitespace...?
4424 false // Don't clear state!
4426 $html = $pout->getText();
4428 $ig->add( $nt, $html );
4430 # Only add real images (bug #5586)
4431 if ( $nt->getNamespace() == NS_IMAGE
) {
4432 $this->mOutput
->addImage( $nt->getDBkey() );
4435 return $ig->toHTML();
4439 * Parse image options text and use it to make an image
4441 function makeImage( $nt, $options ) {
4442 # @TODO: let the MediaHandler specify its transform parameters
4444 # Check if the options text is of the form "options|alt text"
4446 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4447 # * left no resizing, just left align. label is used for alt= only
4448 # * right same, but right aligned
4449 # * none same, but not aligned
4450 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4451 # * center center the image
4452 # * framed Keep original image size, no magnify-button.
4453 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4454 # * upright reduce width for upright images, rounded to full __0 px
4455 # * border draw a 1px border around the image
4456 # vertical-align values (no % or length right now):
4467 $part = array_map( 'trim', explode( '|', $options) );
4470 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4471 foreach ( $alignments as $alignment ) {
4472 $mwAlign[$alignment] =& MagicWord
::get( 'img_'.$alignment );
4474 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4475 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4476 $mwWidth =& MagicWord
::get( 'img_width' );
4477 $mwFramed =& MagicWord
::get( 'img_framed' );
4478 $mwFrameless =& MagicWord
::get( 'img_frameless' );
4479 $mwUpright =& MagicWord
::get( 'img_upright' );
4480 $mwBorder =& MagicWord
::get( 'img_border' );
4481 $mwPage =& MagicWord
::get( 'img_page' );
4485 $framed = $thumb = false;
4486 $manual_thumb = '' ;
4487 $align = $valign = '';
4488 $sk = $this->mOptions
->getSkin();
4490 foreach( $part as $val ) {
4491 if ( !is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4493 } elseif ( !is_null( $match = $mwUpright->matchVariableStartToEnd( $val ) ) ) {
4494 $params['upright'] = true;
4495 $params['upright_factor'] = floatval( $match );
4496 } elseif ( !is_null( $match = $mwFrameless->matchVariableStartToEnd( $val ) ) ) {
4497 $params['frameless'] = true;
4498 } elseif ( !is_null( $mwBorder->matchVariableStartToEnd( $val ) ) ) {
4499 $params['border'] = true;
4500 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4501 # use manually specified thumbnail
4503 $manual_thumb = $match;
4505 foreach( $alignments as $alignment ) {
4506 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4507 switch ( $alignment ) {
4508 case 'left': case 'right': case 'center': case 'none':
4509 $align = $alignment; break;
4511 $valign = $alignment;
4516 if ( ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4517 # Select a page in a multipage document
4518 $params['page'] = $match;
4519 } elseif ( !isset( $params['width'] ) && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4520 wfDebug( "img_width match: $match\n" );
4521 # $match is the image width in pixels
4523 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4524 $params['width'] = intval( $m[1] );
4525 $params['height'] = intval( $m[2] );
4527 $params['width'] = intval($match);
4529 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4536 # Strip bad stuff out of the alt text
4537 $alt = $this->replaceLinkHoldersText( $caption );
4539 # make sure there are no placeholders in thumbnail attributes
4540 # that are later expanded to html- so expand them now and
4542 $alt = $this->mStripState
->unstripBoth( $alt );
4543 $alt = Sanitizer
::stripAllTags( $alt );
4545 # Give extensions a chance to select the file revision for us
4546 $skip = $time = false;
4547 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
4549 # Linker does the rest
4551 $link = $sk->makeLinkObj( $nt );
4553 $link = $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $params, $framed, $thumb, $manual_thumb, $valign, $time );
4560 * Set a flag in the output object indicating that the content is dynamic and
4561 * shouldn't be cached.
4563 function disableCache() {
4564 wfDebug( "Parser output marked as uncacheable.\n" );
4565 $this->mOutput
->mCacheTime
= -1;
4569 * Callback from the Sanitizer for expanding items found in HTML attribute
4570 * values, so they can be safely tested and escaped.
4571 * @param string $text
4572 * @param array $args
4576 function attributeStripCallback( &$text, $args ) {
4577 $text = $this->replaceVariables( $text, $args );
4578 $text = $this->mStripState
->unstripBoth( $text );
4587 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4588 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4589 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4595 function getTags() { return array_keys( $this->mTagHooks
); }
4600 * Break wikitext input into sections, and either pull or replace
4601 * some particular section's text.
4603 * External callers should use the getSection and replaceSection methods.
4605 * @param $text Page wikitext
4606 * @param $section Numbered section. 0 pulls the text before the first
4607 * heading; other numbers will pull the given section
4608 * along with its lower-level subsections.
4609 * @param $mode One of "get" or "replace"
4610 * @param $newtext Replacement text for section data.
4611 * @return string for "get", the extracted section text.
4612 * for "replace", the whole page with the section replaced.
4614 private function extractSections( $text, $section, $mode, $newtext='' ) {
4615 # I.... _hope_ this is right.
4616 # Otherwise, sometimes we don't have things initialized properly.
4617 $this->clearState();
4619 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4620 # comments to be stripped as well)
4621 $stripState = new StripState
;
4623 $oldOutputType = $this->mOutputType
;
4624 $oldOptions = $this->mOptions
;
4625 $this->mOptions
= new ParserOptions();
4626 $this->setOutputType( OT_WIKI
);
4628 $striptext = $this->strip( $text, $stripState, true );
4630 $this->setOutputType( $oldOutputType );
4631 $this->mOptions
= $oldOptions;
4633 # now that we can be sure that no pseudo-sections are in the source,
4634 # split it up by section
4635 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4636 $comment = "(?:$uniq-!--.*?QINU)";
4641 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4642 (=+) # Should this be limited to 6?
4643 .+? # Section title...
4644 \\2 # Ending = count must match start
4645 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4654 PREG_SPLIT_DELIM_CAPTURE
);
4656 if( $mode == "get" ) {
4657 if( $section == 0 ) {
4658 // "Section 0" returns the content before any other section.
4661 //track missing section, will replace if found.
4664 } elseif( $mode == "replace" ) {
4665 if( $section == 0 ) {
4666 $rv = $newtext . "\n\n";
4675 for( $index = 1; $index < count( $secs ); ) {
4676 $headerLine = $secs[$index++
];
4677 if( $secs[$index] ) {
4679 $headerLevel = strlen( $secs[$index++
] );
4683 $headerLevel = intval( $secs[$index++
] );
4685 $content = $secs[$index++
];
4688 if( $mode == "get" ) {
4689 if( $count == $section ) {
4690 $rv = $headerLine . $content;
4691 $sectionLevel = $headerLevel;
4692 } elseif( $count > $section ) {
4693 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4694 $rv .= $headerLine . $content;
4696 // Broke out to a higher-level section
4700 } elseif( $mode == "replace" ) {
4701 if( $count < $section ) {
4702 $rv .= $headerLine . $content;
4703 } elseif( $count == $section ) {
4704 $rv .= $newtext . "\n\n";
4705 $sectionLevel = $headerLevel;
4706 } elseif( $count > $section ) {
4707 if( $headerLevel <= $sectionLevel ) {
4708 // Passed the section's sub-parts.
4712 $rv .= $headerLine . $content;
4718 # reinsert stripped tags
4719 $rv = trim( $stripState->unstripBoth( $rv ) );
4725 * This function returns the text of a section, specified by a number ($section).
4726 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4727 * the first section before any such heading (section 0).
4729 * If a section contains subsections, these are also returned.
4731 * @param $text String: text to look in
4732 * @param $section Integer: section number
4733 * @param $deftext: default to return if section is not found
4734 * @return string text of the requested section
4736 public function getSection( $text, $section, $deftext='' ) {
4737 return $this->extractSections( $text, $section, "get", $deftext );
4740 public function replaceSection( $oldtext, $section, $text ) {
4741 return $this->extractSections( $oldtext, $section, "replace", $text );
4745 * Get the timestamp associated with the current revision, adjusted for
4746 * the default server-local timestamp
4748 function getRevisionTimestamp() {
4749 if ( is_null( $this->mRevisionTimestamp
) ) {
4750 wfProfileIn( __METHOD__
);
4752 $dbr = wfGetDB( DB_SLAVE
);
4753 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4754 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4756 // Normalize timestamp to internal MW format for timezone processing.
4757 // This has the added side-effect of replacing a null value with
4758 // the current time, which gives us more sensible behavior for
4760 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4762 // The cryptic '' timezone parameter tells to use the site-default
4763 // timezone offset instead of the user settings.
4765 // Since this value will be saved into the parser cache, served
4766 // to other users, and potentially even used inside links and such,
4767 // it needs to be consistent for all visitors.
4768 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4770 wfProfileOut( __METHOD__
);
4772 return $this->mRevisionTimestamp
;
4776 * Mutator for $mDefaultSort
4778 * @param $sort New value
4780 public function setDefaultSort( $sort ) {
4781 $this->mDefaultSort
= $sort;
4785 * Accessor for $mDefaultSort
4786 * Will use the title/prefixed title if none is set
4790 public function getDefaultSort() {
4791 if( $this->mDefaultSort
!== false ) {
4792 return $this->mDefaultSort
;
4794 return $this->mTitle
->getNamespace() == NS_CATEGORY
4795 ?
$this->mTitle
->getText()
4796 : $this->mTitle
->getPrefixedText();
4803 * @todo document, briefly.
4804 * @addtogroup Parser
4806 class OnlyIncludeReplacer
{
4809 function replace( $matches ) {
4810 if ( substr( $matches[1], -1 ) == "\n" ) {
4811 $this->output
.= substr( $matches[1], 0, -1 );
4813 $this->output
.= $matches[1];
4819 * @todo document, briefly.
4820 * @addtogroup Parser
4823 var $general, $nowiki;
4825 function __construct() {
4826 $this->general
= new ReplacementArray
;
4827 $this->nowiki
= new ReplacementArray
;
4830 function unstripGeneral( $text ) {
4831 wfProfileIn( __METHOD__
);
4832 $text = $this->general
->replace( $text );
4833 wfProfileOut( __METHOD__
);
4837 function unstripNoWiki( $text ) {
4838 wfProfileIn( __METHOD__
);
4839 $text = $this->nowiki
->replace( $text );
4840 wfProfileOut( __METHOD__
);
4844 function unstripBoth( $text ) {
4845 wfProfileIn( __METHOD__
);
4846 $text = $this->general
->replace( $text );
4847 $text = $this->nowiki
->replace( $text );
4848 wfProfileOut( __METHOD__
);