3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
16 define( 'RLH_FOR_UPDATE', 1 );
18 # Allowed values for $mOutputType
19 define( 'OT_HTML', 1 );
20 define( 'OT_WIKI', 2 );
21 define( 'OT_MSG' , 3 );
22 define( 'OT_PREPROCESS', 4 );
24 # Flags for setFunctionHook
25 define( 'SFH_NO_HASH', 1 );
27 # string parameter for extractTags which will cause it
28 # to strip HTML comments in addition to regular
29 # <XML>-style tags. This should not be anything we
30 # may want to use in wikisyntax
31 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
33 # Constants needed for external link processing
34 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
35 # Everything except bracket, space, or control characters
36 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
37 # Including space, but excluding newlines
38 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
39 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
40 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
41 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
42 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
43 define( 'EXT_IMAGE_REGEX',
44 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
45 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
46 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
49 // State constants for the definition list colon extraction
50 define( 'MW_COLON_STATE_TEXT', 0 );
51 define( 'MW_COLON_STATE_TAG', 1 );
52 define( 'MW_COLON_STATE_TAGSTART', 2 );
53 define( 'MW_COLON_STATE_CLOSETAG', 3 );
54 define( 'MW_COLON_STATE_TAGSLASH', 4 );
55 define( 'MW_COLON_STATE_COMMENT', 5 );
56 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
57 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
62 * Processes wiki markup
65 * There are four main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
73 * removes HTML comments and expands templates
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
86 * * only within ParserOptions
97 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
103 var $mIncludeSizes, $mDefaultSort;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId, // ID to display in {{REVISIONID}} tags
116 $mRevisionTimestamp, // The timestamp of the specified revision ID
117 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
127 $this->mTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mFirstCall
= true;
134 * Do various kinds of initialisation on the first call of the parser
136 function firstCallInit() {
137 if ( !$this->mFirstCall
) {
141 wfProfileIn( __METHOD__
);
142 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
144 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
146 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
170 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
172 if ( $wgAllowDisplayTitle ) {
173 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
175 if ( $wgAllowSlowParserFunctions ) {
176 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
179 $this->initialiseVariables();
180 $this->mFirstCall
= false;
181 wfProfileOut( __METHOD__
);
189 function clearState() {
190 wfProfileIn( __METHOD__
);
191 if ( $this->mFirstCall
) {
192 $this->firstCallInit();
194 $this->mOutput
= new ParserOutput
;
195 $this->mAutonumber
= 0;
196 $this->mLastSection
= '';
197 $this->mDTopen
= false;
198 $this->mIncludeCount
= array();
199 $this->mStripState
= new StripState
;
200 $this->mArgStack
= array();
201 $this->mInPre
= false;
202 $this->mInterwikiLinkHolders
= array(
206 $this->mLinkHolders
= array(
207 'namespaces' => array(),
209 'queries' => array(),
213 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
216 * Prefix for temporary replacement strings for the multipass parser.
217 * \x07 should never appear in input as it's disallowed in XML.
218 * Using it at the front also gives us a little extra robustness
219 * since it shouldn't match when butted up against identifier-like
222 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
224 # Clear these on every parse, bug 4549
225 $this->mTemplates
= array();
226 $this->mTemplatePath
= array();
228 $this->mShowToc
= true;
229 $this->mForceTocPosition
= false;
230 $this->mIncludeSizes
= array(
235 $this->mDefaultSort
= false;
237 wfRunHooks( 'ParserClearState', array( &$this ) );
238 wfProfileOut( __METHOD__
);
241 function setOutputType( $ot ) {
242 $this->mOutputType
= $ot;
245 'html' => $ot == OT_HTML
,
246 'wiki' => $ot == OT_WIKI
,
247 'msg' => $ot == OT_MSG
,
248 'pre' => $ot == OT_PREPROCESS
,
253 * Accessor for mUniqPrefix.
257 function uniqPrefix() {
258 return $this->mUniqPrefix
;
262 * Convert wikitext to HTML
263 * Do not call this function recursively.
265 * @param string $text Text we want to parse
266 * @param Title &$title A title object
267 * @param array $options
268 * @param boolean $linestart
269 * @param boolean $clearState
270 * @param int $revid number to pass in {{REVISIONID}}
271 * @return ParserOutput a ParserOutput
273 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
275 * First pass--just handle <nowiki> sections, pass the rest off
276 * to internalParse() which does all the real work.
279 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
280 $fname = 'Parser::parse-' . wfGetCaller();
281 wfProfileIn( __METHOD__
);
282 wfProfileIn( $fname );
288 $this->mOptions
= $options;
289 $this->mTitle
=& $title;
290 $oldRevisionId = $this->mRevisionId
;
291 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
292 if( $revid !== null ) {
293 $this->mRevisionId
= $revid;
294 $this->mRevisionTimestamp
= null;
296 $this->setOutputType( OT_HTML
);
297 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
298 $text = $this->strip( $text, $this->mStripState
);
299 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
300 $text = $this->internalParse( $text );
301 $text = $this->mStripState
->unstripGeneral( $text );
303 # Clean up special characters, only run once, next-to-last before doBlockLevels
305 # french spaces, last one Guillemet-left
306 # only if there is something before the space
307 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
308 # french spaces, Guillemet-right
309 '/(\\302\\253) /' => '\\1 ',
311 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
314 $text = $this->doBlockLevels( $text, $linestart );
316 $this->replaceLinkHolders( $text );
318 # the position of the parserConvert() call should not be changed. it
319 # assumes that the links are all replaced and the only thing left
320 # is the <nowiki> mark.
321 # Side-effects: this calls $this->mOutput->setTitleText()
322 $text = $wgContLang->parserConvert( $text, $this );
324 $text = $this->mStripState
->unstripNoWiki( $text );
326 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
328 $text = Sanitizer
::normalizeCharReferences( $text );
330 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
331 $text = Parser
::tidy($text);
333 # attempt to sanitize at least some nesting problems
334 # (bug #2702 and quite a few others)
336 # ''Something [http://www.cool.com cool''] -->
337 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
338 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
339 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
340 # fix up an anchor inside another anchor, only
341 # at least for a single single nested link (bug 3695)
342 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
343 '\\1\\2</a>\\3</a>\\1\\4</a>',
344 # fix div inside inline elements- doBlockLevels won't wrap a line which
345 # contains a div, so fix it up here; replace
346 # div with escaped text
347 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
348 '\\1\\3<div\\5>\\6</div>\\8\\9',
349 # remove empty italic or bold tag pairs, some
350 # introduced by rules above
351 '/<([bi])><\/\\1>/' => '',
354 $text = preg_replace(
355 array_keys( $tidyregs ),
356 array_values( $tidyregs ),
360 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
362 # Information on include size limits, for the benefit of users who try to skirt them
363 if ( max( $this->mIncludeSizes
) > 1000 ) {
364 $max = $this->mOptions
->getMaxIncludeSize();
366 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
367 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
368 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
369 "Maximum: $max bytes\n" .
372 $this->mOutput
->setText( $text );
373 $this->mRevisionId
= $oldRevisionId;
374 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
375 wfProfileOut( $fname );
376 wfProfileOut( __METHOD__
);
378 return $this->mOutput
;
382 * Recursive parser entry point that can be called from an extension tag
385 function recursiveTagParse( $text ) {
386 wfProfileIn( __METHOD__
);
387 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
388 $text = $this->strip( $text, $this->mStripState
);
389 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
390 $text = $this->internalParse( $text );
391 wfProfileOut( __METHOD__
);
396 * Expand templates and variables in the text, producing valid, static wikitext.
397 * Also removes comments.
399 function preprocess( $text, $title, $options ) {
400 wfProfileIn( __METHOD__
);
402 $this->setOutputType( OT_PREPROCESS
);
403 $this->mOptions
= $options;
404 $this->mTitle
= $title;
405 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
406 $text = $this->strip( $text, $this->mStripState
);
407 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
408 if ( $this->mOptions
->getRemoveComments() ) {
409 $text = Sanitizer
::removeHTMLcomments( $text );
411 $text = $this->replaceVariables( $text );
412 $text = $this->mStripState
->unstripBoth( $text );
413 wfProfileOut( __METHOD__
);
418 * Get a random string
423 function getRandomString() {
424 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
427 function &getTitle() { return $this->mTitle
; }
428 function getOptions() { return $this->mOptions
; }
430 function getFunctionLang() {
431 global $wgLang, $wgContLang;
432 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
436 * Replaces all occurrences of HTML-style comments and the given tags
437 * in the text with a random marker and returns teh next text. The output
438 * parameter $matches will be an associative array filled with data in
440 * 'UNIQ-xxxxx' => array(
443 * array( 'param' => 'x' ),
444 * '<element param="x">tag content</element>' ) )
446 * @param $elements list of element names. Comments are always extracted.
447 * @param $text Source text string.
448 * @param $uniq_prefix
453 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
458 $taglist = implode( '|', $elements );
459 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
461 while ( '' != $text ) {
462 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
464 if( count( $p ) < 5 ) {
467 if( count( $p ) > 5 ) {
481 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
482 $stripped .= $marker;
484 if ( $close === '/>' ) {
485 // Empty element tag, <tag />
490 if( $element == '!--' ) {
493 $end = "/(<\\/$element\\s*>)/i";
495 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
497 if( count( $q ) < 3 ) {
498 # No end tag -- let it run out to the end of the text.
507 $matches[$marker] = array( $element,
509 Sanitizer
::decodeTagAttributes( $attributes ),
510 "<$element$attributes$close$content$tail" );
516 * Strips and renders nowiki, pre, math, hiero
517 * If $render is set, performs necessary rendering operations on plugins
518 * Returns the text, and fills an array with data needed in unstrip()
520 * @param StripState $state
522 * @param bool $stripcomments when set, HTML comments <!-- like this -->
523 * will be stripped in addition to other tags. This is important
524 * for section editing, where these comments cause confusion when
525 * counting the sections in the wikisource
527 * @param array dontstrip contains tags which should not be stripped;
528 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
532 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
534 wfProfileIn( __METHOD__
);
535 $render = ($this->mOutputType
== OT_HTML
);
537 $uniq_prefix = $this->mUniqPrefix
;
538 $commentState = new ReplacementArray
;
539 $nowikiItems = array();
540 $generalItems = array();
542 $elements = array_merge(
543 array( 'nowiki', 'gallery' ),
544 array_keys( $this->mTagHooks
) );
547 $elements[] = 'html';
549 if( $this->mOptions
->getUseTeX() ) {
550 $elements[] = 'math';
553 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
554 foreach ( $elements AS $k => $v ) {
555 if ( !in_array ( $v , $dontstrip ) ) continue;
556 unset ( $elements[$k] );
560 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
562 foreach( $matches as $marker => $data ) {
563 list( $element, $content, $params, $tag ) = $data;
565 $tagName = strtolower( $element );
566 wfProfileIn( __METHOD__
."-render-$tagName" );
570 if( substr( $tag, -3 ) == '-->' ) {
573 // Unclosed comment in input.
574 // Close it so later stripping can remove it
583 // Shouldn't happen otherwise. :)
585 $output = Xml
::escapeTagsOnly( $content );
588 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
591 $output = $this->renderImageGallery( $content, $params );
594 if( isset( $this->mTagHooks
[$tagName] ) ) {
595 $output = call_user_func_array( $this->mTagHooks
[$tagName],
596 array( $content, $params, $this ) );
598 throw new MWException( "Invalid call hook $element" );
601 wfProfileOut( __METHOD__
."-render-$tagName" );
603 // Just stripping tags; keep the source
607 // Unstrip the output, to support recursive strip() calls
608 $output = $state->unstripBoth( $output );
610 if( !$stripcomments && $element == '!--' ) {
611 $commentState->setPair( $marker, $output );
612 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
613 $nowikiItems[$marker] = $output;
615 $generalItems[$marker] = $output;
618 # Add the new items to the state
619 # We do this after the loop instead of during it to avoid slowing
620 # down the recursive unstrip
621 $state->nowiki
->mergeArray( $nowikiItems );
622 $state->general
->mergeArray( $generalItems );
624 # Unstrip comments unless explicitly told otherwise.
625 # (The comments are always stripped prior to this point, so as to
626 # not invoke any extension tags / parser hooks contained within
628 if ( !$stripcomments ) {
629 // Put them all back and forget them
630 $text = $commentState->replace( $text );
633 wfProfileOut( __METHOD__
);
638 * Restores pre, math, and other extensions removed by strip()
640 * always call unstripNoWiki() after this one
642 * @deprecated use $this->mStripState->unstrip()
644 function unstrip( $text, $state ) {
645 return $state->unstripGeneral( $text );
649 * Always call this after unstrip() to preserve the order
652 * @deprecated use $this->mStripState->unstrip()
654 function unstripNoWiki( $text, $state ) {
655 return $state->unstripNoWiki( $text );
659 * @deprecated use $this->mStripState->unstripBoth()
661 function unstripForHTML( $text ) {
662 return $this->mStripState
->unstripBoth( $text );
666 * Add an item to the strip state
667 * Returns the unique tag which must be inserted into the stripped text
668 * The tag will be replaced with the original text in unstrip()
672 function insertStripItem( $text, &$state ) {
673 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
674 $state->general
->setPair( $rnd, $text );
679 * Interface with html tidy, used if $wgUseTidy = true.
680 * If tidy isn't able to correct the markup, the original will be
681 * returned in all its glory with a warning comment appended.
683 * Either the external tidy program or the in-process tidy extension
684 * will be used depending on availability. Override the default
685 * $wgTidyInternal setting to disable the internal if it's not working.
687 * @param string $text Hideous HTML input
688 * @return string Corrected HTML output
692 function tidy( $text ) {
693 global $wgTidyInternal;
694 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
695 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
696 '<head><title>test</title></head><body>'.$text.'</body></html>';
697 if( $wgTidyInternal ) {
698 $correctedtext = Parser
::internalTidy( $wrappedtext );
700 $correctedtext = Parser
::externalTidy( $wrappedtext );
702 if( is_null( $correctedtext ) ) {
703 wfDebug( "Tidy error detected!\n" );
704 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
706 return $correctedtext;
710 * Spawn an external HTML tidy process and get corrected markup back from it.
715 function externalTidy( $text ) {
716 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
717 $fname = 'Parser::externalTidy';
718 wfProfileIn( $fname );
723 $descriptorspec = array(
724 0 => array('pipe', 'r'),
725 1 => array('pipe', 'w'),
726 2 => array('file', '/dev/null', 'a')
729 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
730 if (is_resource($process)) {
731 // Theoretically, this style of communication could cause a deadlock
732 // here. If the stdout buffer fills up, then writes to stdin could
733 // block. This doesn't appear to happen with tidy, because tidy only
734 // writes to stdout after it's finished reading from stdin. Search
735 // for tidyParseStdin and tidySaveStdout in console/tidy.c
736 fwrite($pipes[0], $text);
738 while (!feof($pipes[1])) {
739 $cleansource .= fgets($pipes[1], 1024);
742 proc_close($process);
745 wfProfileOut( $fname );
747 if( $cleansource == '' && $text != '') {
748 // Some kind of error happened, so we couldn't get the corrected text.
749 // Just give up; we'll use the source text and append a warning.
757 * Use the HTML tidy PECL extension to use the tidy library in-process,
758 * saving the overhead of spawning a new process. Currently written to
759 * the PHP 4.3.x version of the extension, may not work on PHP 5.
761 * 'pear install tidy' should be able to compile the extension module.
766 function internalTidy( $text ) {
768 $fname = 'Parser::internalTidy';
769 wfProfileIn( $fname );
771 tidy_load_config( $wgTidyConf );
772 tidy_set_encoding( 'utf8' );
773 tidy_parse_string( $text );
775 if( tidy_get_status() == 2 ) {
776 // 2 is magic number for fatal error
777 // http://www.php.net/manual/en/function.tidy-get-status.php
780 $cleansource = tidy_get_output();
782 wfProfileOut( $fname );
787 * parse the wiki syntax used to render tables
791 function doTableStuff ( $text ) {
792 $fname = 'Parser::doTableStuff';
793 wfProfileIn( $fname );
795 $lines = explode ( "\n" , $text );
796 $td_history = array (); // Is currently a td tag open?
797 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
798 $tr_history = array (); // Is currently a tr tag open?
799 $tr_attributes = array (); // history of tr attributes
800 $has_opened_tr = array(); // Did this table open a <tr> element?
801 $indent_level = 0; // indent level of the table
802 foreach ( $lines as $key => $line )
804 $line = trim ( $line );
806 if( $line == '' ) { // empty line, go to next line
809 $first_character = $line{0};
812 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
813 // First check if we are starting a new table
814 $indent_level = strlen( $matches[1] );
816 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
817 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
819 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
820 array_push ( $td_history , false );
821 array_push ( $last_tag_history , '' );
822 array_push ( $tr_history , false );
823 array_push ( $tr_attributes , '' );
824 array_push ( $has_opened_tr , false );
825 } else if ( count ( $td_history ) == 0 ) {
826 // Don't do any of the following
828 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
829 // We are ending a table
830 $line = '</table>' . substr ( $line , 2 );
831 $last_tag = array_pop ( $last_tag_history );
833 if ( !array_pop ( $has_opened_tr ) ) {
834 $line = "<tr><td></td></tr>{$line}";
837 if ( array_pop ( $tr_history ) ) {
838 $line = "</tr>{$line}";
841 if ( array_pop ( $td_history ) ) {
842 $line = "</{$last_tag}>{$line}";
844 array_pop ( $tr_attributes );
845 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
846 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
847 // Now we have a table row
848 $line = preg_replace( '#^\|-+#', '', $line );
850 // Whats after the tag is now only attributes
851 $attributes = $this->mStripState
->unstripBoth( $line );
852 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
853 array_pop ( $tr_attributes );
854 array_push ( $tr_attributes , $attributes );
857 $last_tag = array_pop ( $last_tag_history );
858 array_pop ( $has_opened_tr );
859 array_push ( $has_opened_tr , true );
861 if ( array_pop ( $tr_history ) ) {
865 if ( array_pop ( $td_history ) ) {
866 $line = "</{$last_tag}>{$line}";
869 $lines[$key] = $line;
870 array_push ( $tr_history , false );
871 array_push ( $td_history , false );
872 array_push ( $last_tag_history , '' );
874 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
875 // This might be cell elements, td, th or captions
876 if ( substr ( $line , 0 , 2 ) == '|+' ) {
877 $first_character = '+';
878 $line = substr ( $line , 1 );
881 $line = substr ( $line , 1 );
883 if ( $first_character == '!' ) {
884 $line = str_replace ( '!!' , '||' , $line );
887 // Split up multiple cells on the same line.
888 // FIXME : This can result in improper nesting of tags processed
889 // by earlier parser steps, but should avoid splitting up eg
890 // attribute values containing literal "||".
891 $cells = StringUtils
::explodeMarkup( '||' , $line );
895 // Loop through each table cell
896 foreach ( $cells as $cell )
899 if ( $first_character != '+' )
901 $tr_after = array_pop ( $tr_attributes );
902 if ( !array_pop ( $tr_history ) ) {
903 $previous = "<tr{$tr_after}>\n";
905 array_push ( $tr_history , true );
906 array_push ( $tr_attributes , '' );
907 array_pop ( $has_opened_tr );
908 array_push ( $has_opened_tr , true );
911 $last_tag = array_pop ( $last_tag_history );
913 if ( array_pop ( $td_history ) ) {
914 $previous = "</{$last_tag}>{$previous}";
917 if ( $first_character == '|' ) {
919 } else if ( $first_character == '!' ) {
921 } else if ( $first_character == '+' ) {
922 $last_tag = 'caption';
927 array_push ( $last_tag_history , $last_tag );
929 // A cell could contain both parameters and data
930 $cell_data = explode ( '|' , $cell , 2 );
932 // Bug 553: Note that a '|' inside an invalid link should not
933 // be mistaken as delimiting cell parameters
934 if ( strpos( $cell_data[0], '[[' ) !== false ) {
935 $cell = "{$previous}<{$last_tag}>{$cell}";
936 } else if ( count ( $cell_data ) == 1 )
937 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
939 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
940 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
941 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
944 $lines[$key] .= $cell;
945 array_push ( $td_history , true );
950 // Closing open td, tr && table
951 while ( count ( $td_history ) > 0 )
953 if ( array_pop ( $td_history ) ) {
956 if ( array_pop ( $tr_history ) ) {
959 if ( !array_pop ( $has_opened_tr ) ) {
960 $lines[] = "<tr><td></td></tr>" ;
963 $lines[] = '</table>' ;
966 $output = implode ( "\n" , $lines ) ;
968 // special case: don't return empty table
969 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
973 wfProfileOut( $fname );
979 * Helper function for parse() that transforms wiki markup into
980 * HTML. Only called for $mOutputType == OT_HTML.
984 function internalParse( $text ) {
987 $fname = 'Parser::internalParse';
988 wfProfileIn( $fname );
990 # Hook to suspend the parser in this state
991 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
992 wfProfileOut( $fname );
996 # Remove <noinclude> tags and <includeonly> sections
997 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
998 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
999 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1001 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1003 $text = $this->replaceVariables( $text, $args );
1005 // Tables need to come after variable replacement for things to work
1006 // properly; putting them before other transformations should keep
1007 // exciting things like link expansions from showing up in surprising
1009 $text = $this->doTableStuff( $text );
1011 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1013 $text = $this->stripToc( $text );
1014 $this->stripNoGallery( $text );
1015 $text = $this->doHeadings( $text );
1016 if($this->mOptions
->getUseDynamicDates()) {
1017 $df =& DateFormatter
::getInstance();
1018 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1020 $text = $this->doAllQuotes( $text );
1021 $text = $this->replaceInternalLinks( $text );
1022 $text = $this->replaceExternalLinks( $text );
1024 # replaceInternalLinks may sometimes leave behind
1025 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1026 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1028 $text = $this->doMagicLinks( $text );
1029 $text = $this->formatHeadings( $text, $isMain );
1031 wfProfileOut( $fname );
1036 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1037 * magic external links.
1041 function &doMagicLinks( &$text ) {
1042 wfProfileIn( __METHOD__
);
1043 $text = preg_replace_callback(
1045 <a.*?</a> | # Skip link text
1046 <.*?> | # Skip stuff inside HTML elements
1047 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1048 ISBN\s+(\b # ISBN, capture number as m[2]
1049 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1050 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1051 [0-9Xx] # check digit
1053 )!x', array( &$this, 'magicLinkCallback' ), $text );
1054 wfProfileOut( __METHOD__
);
1058 function magicLinkCallback( $m ) {
1059 if ( substr( $m[0], 0, 1 ) == '<' ) {
1062 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1064 $num = strtr( $isbn, array(
1069 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1070 $text = '<a href="' .
1071 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1072 "\" class=\"internal\">ISBN $isbn</a>";
1074 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1078 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1080 $urlmsg = 'pubmedurl';
1083 throw new MWException( __METHOD__
.': unrecognised match type "' .
1084 substr($m[0], 0, 20 ) . '"' );
1087 $url = wfMsg( $urlmsg, $id);
1088 $sk =& $this->mOptions
->getSkin();
1089 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1090 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1096 * Parse headers and return html
1100 function doHeadings( $text ) {
1101 $fname = 'Parser::doHeadings';
1102 wfProfileIn( $fname );
1103 for ( $i = 6; $i >= 1; --$i ) {
1104 $h = str_repeat( '=', $i );
1105 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1106 "<h{$i}>\\1</h{$i}>\\2", $text );
1108 wfProfileOut( $fname );
1113 * Replace single quotes with HTML markup
1115 * @return string the altered text
1117 function doAllQuotes( $text ) {
1118 $fname = 'Parser::doAllQuotes';
1119 wfProfileIn( $fname );
1121 $lines = explode( "\n", $text );
1122 foreach ( $lines as $line ) {
1123 $outtext .= $this->doQuotes ( $line ) . "\n";
1125 $outtext = substr($outtext, 0,-1);
1126 wfProfileOut( $fname );
1131 * Helper function for doAllQuotes()
1134 function doQuotes( $text ) {
1135 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1136 if ( count( $arr ) == 1 )
1140 # First, do some preliminary work. This may shift some apostrophes from
1141 # being mark-up to being text. It also counts the number of occurrences
1142 # of bold and italics mark-ups.
1146 foreach ( $arr as $r )
1148 if ( ( $i %
2 ) == 1 )
1150 # If there are ever four apostrophes, assume the first is supposed to
1151 # be text, and the remaining three constitute mark-up for bold text.
1152 if ( strlen( $arr[$i] ) == 4 )
1157 # If there are more than 5 apostrophes in a row, assume they're all
1158 # text except for the last 5.
1159 else if ( strlen( $arr[$i] ) > 5 )
1161 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1164 # Count the number of occurrences of bold and italics mark-ups.
1165 # We are not counting sequences of five apostrophes.
1166 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1167 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1168 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1173 # If there is an odd number of both bold and italics, it is likely
1174 # that one of the bold ones was meant to be an apostrophe followed
1175 # by italics. Which one we cannot know for certain, but it is more
1176 # likely to be one that has a single-letter word before it.
1177 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1180 $firstsingleletterword = -1;
1181 $firstmultiletterword = -1;
1183 foreach ( $arr as $r )
1185 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1187 $x1 = substr ($arr[$i-1], -1);
1188 $x2 = substr ($arr[$i-1], -2, 1);
1190 if ($firstspace == -1) $firstspace = $i;
1191 } else if ($x2 == ' ') {
1192 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1194 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1200 # If there is a single-letter word, use it!
1201 if ($firstsingleletterword > -1)
1203 $arr [ $firstsingleletterword ] = "''";
1204 $arr [ $firstsingleletterword-1 ] .= "'";
1206 # If not, but there's a multi-letter word, use that one.
1207 else if ($firstmultiletterword > -1)
1209 $arr [ $firstmultiletterword ] = "''";
1210 $arr [ $firstmultiletterword-1 ] .= "'";
1212 # ... otherwise use the first one that has neither.
1213 # (notice that it is possible for all three to be -1 if, for example,
1214 # there is only one pentuple-apostrophe in the line)
1215 else if ($firstspace > -1)
1217 $arr [ $firstspace ] = "''";
1218 $arr [ $firstspace-1 ] .= "'";
1222 # Now let's actually convert our apostrophic mush to HTML!
1227 foreach ($arr as $r)
1231 if ($state == 'both')
1238 if (strlen ($r) == 2)
1241 { $output .= '</i>'; $state = ''; }
1242 else if ($state == 'bi')
1243 { $output .= '</i>'; $state = 'b'; }
1244 else if ($state == 'ib')
1245 { $output .= '</b></i><b>'; $state = 'b'; }
1246 else if ($state == 'both')
1247 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1248 else # $state can be 'b' or ''
1249 { $output .= '<i>'; $state .= 'i'; }
1251 else if (strlen ($r) == 3)
1254 { $output .= '</b>'; $state = ''; }
1255 else if ($state == 'bi')
1256 { $output .= '</i></b><i>'; $state = 'i'; }
1257 else if ($state == 'ib')
1258 { $output .= '</b>'; $state = 'i'; }
1259 else if ($state == 'both')
1260 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1261 else # $state can be 'i' or ''
1262 { $output .= '<b>'; $state .= 'b'; }
1264 else if (strlen ($r) == 5)
1267 { $output .= '</b><i>'; $state = 'i'; }
1268 else if ($state == 'i')
1269 { $output .= '</i><b>'; $state = 'b'; }
1270 else if ($state == 'bi')
1271 { $output .= '</i></b>'; $state = ''; }
1272 else if ($state == 'ib')
1273 { $output .= '</b></i>'; $state = ''; }
1274 else if ($state == 'both')
1275 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1276 else # ($state == '')
1277 { $buffer = ''; $state = 'both'; }
1282 # Now close all remaining tags. Notice that the order is important.
1283 if ($state == 'b' ||
$state == 'ib')
1285 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1289 if ($state == 'both')
1290 $output .= '<b><i>'.$buffer.'</i></b>';
1296 * Replace external links
1298 * Note: this is all very hackish and the order of execution matters a lot.
1299 * Make sure to run maintenance/parserTests.php if you change this code.
1303 function replaceExternalLinks( $text ) {
1305 $fname = 'Parser::replaceExternalLinks';
1306 wfProfileIn( $fname );
1308 $sk =& $this->mOptions
->getSkin();
1310 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1312 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1315 while ( $i<count( $bits ) ) {
1317 $protocol = $bits[$i++
];
1318 $text = $bits[$i++
];
1319 $trail = $bits[$i++
];
1321 # The characters '<' and '>' (which were escaped by
1322 # removeHTMLtags()) should not be included in
1323 # URLs, per RFC 2396.
1325 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1326 $text = substr($url, $m2[0][1]) . ' ' . $text;
1327 $url = substr($url, 0, $m2[0][1]);
1330 # If the link text is an image URL, replace it with an <img> tag
1331 # This happened by accident in the original parser, but some people used it extensively
1332 $img = $this->maybeMakeExternalImage( $text );
1333 if ( $img !== false ) {
1339 # Set linktype for CSS - if URL==text, link is essentially free
1340 $linktype = ($text == $url) ?
'free' : 'text';
1342 # No link text, e.g. [http://domain.tld/some.link]
1343 if ( $text == '' ) {
1344 # Autonumber if allowed. See bug #5918
1345 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1346 $text = '[' . ++
$this->mAutonumber
. ']';
1347 $linktype = 'autonumber';
1349 # Otherwise just use the URL
1350 $text = htmlspecialchars( $url );
1354 # Have link text, e.g. [http://domain.tld/some.link text]s
1356 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1359 $text = $wgContLang->markNoConversion($text);
1361 $url = Sanitizer
::cleanUrl( $url );
1363 # Process the trail (i.e. everything after this link up until start of the next link),
1364 # replacing any non-bracketed links
1365 $trail = $this->replaceFreeExternalLinks( $trail );
1367 # Use the encoded URL
1368 # This means that users can paste URLs directly into the text
1369 # Funny characters like ö aren't valid in URLs anyway
1370 # This was changed in August 2004
1371 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1373 # Register link in the output object.
1374 # Replace unnecessary URL escape codes with the referenced character
1375 # This prevents spammers from hiding links from the filters
1376 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1377 $this->mOutput
->addExternalLink( $pasteurized );
1380 wfProfileOut( $fname );
1385 * Replace anything that looks like a URL with a link
1388 function replaceFreeExternalLinks( $text ) {
1390 $fname = 'Parser::replaceFreeExternalLinks';
1391 wfProfileIn( $fname );
1393 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1394 $s = array_shift( $bits );
1397 $sk =& $this->mOptions
->getSkin();
1399 while ( $i < count( $bits ) ){
1400 $protocol = $bits[$i++
];
1401 $remainder = $bits[$i++
];
1404 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1405 # Found some characters after the protocol that look promising
1406 $url = $protocol . $m[1];
1409 # special case: handle urls as url args:
1410 # http://www.example.com/foo?=http://www.example.com/bar
1411 if(strlen($trail) == 0 &&
1413 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1414 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1417 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1422 # The characters '<' and '>' (which were escaped by
1423 # removeHTMLtags()) should not be included in
1424 # URLs, per RFC 2396.
1426 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1427 $trail = substr($url, $m2[0][1]) . $trail;
1428 $url = substr($url, 0, $m2[0][1]);
1431 # Move trailing punctuation to $trail
1433 # If there is no left bracket, then consider right brackets fair game too
1434 if ( strpos( $url, '(' ) === false ) {
1438 $numSepChars = strspn( strrev( $url ), $sep );
1439 if ( $numSepChars ) {
1440 $trail = substr( $url, -$numSepChars ) . $trail;
1441 $url = substr( $url, 0, -$numSepChars );
1444 $url = Sanitizer
::cleanUrl( $url );
1446 # Is this an external image?
1447 $text = $this->maybeMakeExternalImage( $url );
1448 if ( $text === false ) {
1449 # Not an image, make a link
1450 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1451 # Register it in the output object...
1452 # Replace unnecessary URL escape codes with their equivalent characters
1453 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1454 $this->mOutput
->addExternalLink( $pasteurized );
1456 $s .= $text . $trail;
1458 $s .= $protocol . $remainder;
1461 wfProfileOut( $fname );
1466 * Replace unusual URL escape codes with their equivalent characters
1470 * @fixme This can merge genuinely required bits in the path or query string,
1471 * breaking legit URLs. A proper fix would treat the various parts of
1472 * the URL differently; as a workaround, just use the output for
1473 * statistical records, not for actual linking/output.
1475 static function replaceUnusualEscapes( $url ) {
1476 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1477 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1481 * Callback function used in replaceUnusualEscapes().
1482 * Replaces unusual URL escape codes with their equivalent character
1486 private static function replaceUnusualEscapesCallback( $matches ) {
1487 $char = urldecode( $matches[0] );
1488 $ord = ord( $char );
1489 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1490 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1491 // No, shouldn't be escaped
1494 // Yes, leave it escaped
1500 * make an image if it's allowed, either through the global
1501 * option or through the exception
1504 function maybeMakeExternalImage( $url ) {
1505 $sk =& $this->mOptions
->getSkin();
1506 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1507 $imagesexception = !empty($imagesfrom);
1509 if ( $this->mOptions
->getAllowExternalImages()
1510 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1511 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1513 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1520 * Process [[ ]] wikilinks
1524 function replaceInternalLinks( $s ) {
1526 static $fname = 'Parser::replaceInternalLinks' ;
1528 wfProfileIn( $fname );
1530 wfProfileIn( $fname.'-setup' );
1532 # the % is needed to support urlencoded titles as well
1533 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1535 $sk =& $this->mOptions
->getSkin();
1537 #split the entire text string on occurences of [[
1538 $a = explode( '[[', ' ' . $s );
1539 #get the first element (all text up to first [[), and remove the space we added
1540 $s = array_shift( $a );
1541 $s = substr( $s, 1 );
1543 # Match a link having the form [[namespace:link|alternate]]trail
1545 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1546 # Match cases where there is no "]]", which might still be images
1547 static $e1_img = FALSE;
1548 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1549 # Match the end of a line for a word that's not followed by whitespace,
1550 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1551 $e2 = wfMsgForContent( 'linkprefix' );
1553 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1554 if( is_null( $this->mTitle
) ) {
1555 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1557 $nottalk = !$this->mTitle
->isTalkPage();
1559 if ( $useLinkPrefixExtension ) {
1561 if ( preg_match( $e2, $s, $m ) ) {
1562 $first_prefix = $m[2];
1564 $first_prefix = false;
1570 if($wgContLang->hasVariants()) {
1571 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1573 $selflink = array($this->mTitle
->getPrefixedText());
1575 $useSubpages = $this->areSubpagesAllowed();
1576 wfProfileOut( $fname.'-setup' );
1578 # Loop for each link
1579 for ($k = 0; isset( $a[$k] ); $k++
) {
1581 if ( $useLinkPrefixExtension ) {
1582 wfProfileIn( $fname.'-prefixhandling' );
1583 if ( preg_match( $e2, $s, $m ) ) {
1591 $prefix = $first_prefix;
1592 $first_prefix = false;
1594 wfProfileOut( $fname.'-prefixhandling' );
1597 $might_be_img = false;
1599 wfProfileIn( "$fname-e1" );
1600 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1602 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1603 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1604 # the real problem is with the $e1 regex
1607 # Still some problems for cases where the ] is meant to be outside punctuation,
1608 # and no image is in sight. See bug 2095.
1611 substr( $m[3], 0, 1 ) === ']' &&
1612 strpos($text, '[') !== false
1615 $text .= ']'; # so that replaceExternalLinks($text) works later
1616 $m[3] = substr( $m[3], 1 );
1618 # fix up urlencoded title texts
1619 if( strpos( $m[1], '%' ) !== false ) {
1620 # Should anchors '#' also be rejected?
1621 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1624 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1625 $might_be_img = true;
1627 if ( strpos( $m[1], '%' ) !== false ) {
1628 $m[1] = urldecode($m[1]);
1631 } else { # Invalid form; output directly
1632 $s .= $prefix . '[[' . $line ;
1633 wfProfileOut( "$fname-e1" );
1636 wfProfileOut( "$fname-e1" );
1637 wfProfileIn( "$fname-misc" );
1639 # Don't allow internal links to pages containing
1640 # PROTO: where PROTO is a valid URL protocol; these
1641 # should be external links.
1642 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1643 $s .= $prefix . '[[' . $line ;
1647 # Make subpage if necessary
1648 if( $useSubpages ) {
1649 $link = $this->maybeDoSubpageLink( $m[1], $text );
1654 $noforce = (substr($m[1], 0, 1) != ':');
1656 # Strip off leading ':'
1657 $link = substr($link, 1);
1660 wfProfileOut( "$fname-misc" );
1661 wfProfileIn( "$fname-title" );
1662 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1664 $s .= $prefix . '[[' . $line;
1665 wfProfileOut( "$fname-title" );
1669 $ns = $nt->getNamespace();
1670 $iw = $nt->getInterWiki();
1671 wfProfileOut( "$fname-title" );
1673 if ($might_be_img) { # if this is actually an invalid link
1674 wfProfileIn( "$fname-might_be_img" );
1675 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1677 while (isset ($a[$k+
1]) ) {
1678 #look at the next 'line' to see if we can close it there
1679 $spliced = array_splice( $a, $k +
1, 1 );
1680 $next_line = array_shift( $spliced );
1681 $m = explode( ']]', $next_line, 3 );
1682 if ( count( $m ) == 3 ) {
1683 # the first ]] closes the inner link, the second the image
1685 $text .= "[[{$m[0]}]]{$m[1]}";
1688 } elseif ( count( $m ) == 2 ) {
1689 #if there's exactly one ]] that's fine, we'll keep looking
1690 $text .= "[[{$m[0]}]]{$m[1]}";
1692 #if $next_line is invalid too, we need look no further
1693 $text .= '[[' . $next_line;
1698 # we couldn't find the end of this imageLink, so output it raw
1699 #but don't ignore what might be perfectly normal links in the text we've examined
1700 $text = $this->replaceInternalLinks($text);
1701 $s .= "{$prefix}[[$link|$text";
1702 # note: no $trail, because without an end, there *is* no trail
1703 wfProfileOut( "$fname-might_be_img" );
1706 } else { #it's not an image, so output it raw
1707 $s .= "{$prefix}[[$link|$text";
1708 # note: no $trail, because without an end, there *is* no trail
1709 wfProfileOut( "$fname-might_be_img" );
1712 wfProfileOut( "$fname-might_be_img" );
1715 $wasblank = ( '' == $text );
1716 if( $wasblank ) $text = $link;
1718 # Link not escaped by : , create the various objects
1722 wfProfileIn( "$fname-interwiki" );
1723 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1724 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1725 $s = rtrim($s . "\n");
1726 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1727 wfProfileOut( "$fname-interwiki" );
1730 wfProfileOut( "$fname-interwiki" );
1732 if ( $ns == NS_IMAGE
) {
1733 wfProfileIn( "$fname-image" );
1734 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1735 # recursively parse links inside the image caption
1736 # actually, this will parse them in any other parameters, too,
1737 # but it might be hard to fix that, and it doesn't matter ATM
1738 $text = $this->replaceExternalLinks($text);
1739 $text = $this->replaceInternalLinks($text);
1741 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1742 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1743 $this->mOutput
->addImage( $nt->getDBkey() );
1745 wfProfileOut( "$fname-image" );
1748 # We still need to record the image's presence on the page
1749 $this->mOutput
->addImage( $nt->getDBkey() );
1751 wfProfileOut( "$fname-image" );
1755 if ( $ns == NS_CATEGORY
) {
1756 wfProfileIn( "$fname-category" );
1757 $s = rtrim($s . "\n"); # bug 87
1760 $sortkey = $this->getDefaultSort();
1764 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1765 $sortkey = str_replace( "\n", '', $sortkey );
1766 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1767 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1770 * Strip the whitespace Category links produce, see bug 87
1771 * @todo We might want to use trim($tmp, "\n") here.
1773 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1775 wfProfileOut( "$fname-category" );
1780 if( ( in_array( $nt->getPrefixedText(), $selflink ) ) &&
1781 ( $nt->getFragment() === '' ) ) {
1782 # Self-links are handled specially; generally de-link and change to bold.
1783 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1787 # Special and Media are pseudo-namespaces; no pages actually exist in them
1788 if( $ns == NS_MEDIA
) {
1789 $link = $sk->makeMediaLinkObj( $nt, $text );
1790 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1791 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1792 $this->mOutput
->addImage( $nt->getDBkey() );
1794 } elseif( $ns == NS_SPECIAL
) {
1795 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1797 } elseif( $ns == NS_IMAGE
) {
1798 $img = new Image( $nt );
1799 if( $img->exists() ) {
1800 // Force a blue link if the file exists; may be a remote
1801 // upload on the shared repository, and we want to see its
1802 // auto-generated page.
1803 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1804 $this->mOutput
->addLink( $nt );
1808 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1810 wfProfileOut( $fname );
1815 * Make a link placeholder. The text returned can be later resolved to a real link with
1816 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1817 * parsing of interwiki links, and secondly to allow all existence checks and
1818 * article length checks (for stub links) to be bundled into a single query.
1821 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1822 wfProfileIn( __METHOD__
);
1823 if ( ! is_object($nt) ) {
1825 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1827 # Separate the link trail from the rest of the link
1828 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1830 if ( $nt->isExternal() ) {
1831 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1832 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1833 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1835 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1836 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1837 $this->mLinkHolders
['queries'][] = $query;
1838 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1839 $this->mLinkHolders
['titles'][] = $nt;
1841 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1844 wfProfileOut( __METHOD__
);
1849 * Render a forced-blue link inline; protect against double expansion of
1850 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1851 * Since this little disaster has to split off the trail text to avoid
1852 * breaking URLs in the following text without breaking trails on the
1853 * wiki links, it's been made into a horrible function.
1856 * @param string $text
1857 * @param string $query
1858 * @param string $trail
1859 * @param string $prefix
1860 * @return string HTML-wikitext mix oh yuck
1862 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1863 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1864 $sk =& $this->mOptions
->getSkin();
1865 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1866 return $this->armorLinks( $link ) . $trail;
1870 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1871 * going to go through further parsing steps before inline URL expansion.
1873 * In particular this is important when using action=render, which causes
1874 * full URLs to be included.
1876 * Oh man I hate our multi-layer parser!
1878 * @param string more-or-less HTML
1879 * @return string less-or-more HTML with NOPARSE bits
1881 function armorLinks( $text ) {
1882 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1883 "{$this->mUniqPrefix}NOPARSE$1", $text );
1887 * Return true if subpage links should be expanded on this page.
1890 function areSubpagesAllowed() {
1891 # Some namespaces don't allow subpages
1892 global $wgNamespacesWithSubpages;
1893 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1897 * Handle link to subpage if necessary
1898 * @param string $target the source of the link
1899 * @param string &$text the link text, modified as necessary
1900 * @return string the full name of the link
1903 function maybeDoSubpageLink($target, &$text) {
1906 # :Foobar -- override special treatment of prefix (images, language links)
1907 # /Foobar -- convert to CurrentPage/Foobar
1908 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1909 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1910 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1912 $fname = 'Parser::maybeDoSubpageLink';
1913 wfProfileIn( $fname );
1914 $ret = $target; # default return value is no change
1917 $target = trim( $target );
1919 # Some namespaces don't allow subpages,
1920 # so only perform processing if subpages are allowed
1921 if( $this->areSubpagesAllowed() ) {
1922 # Look at the first character
1923 if( $target != '' && $target{0} == '/' ) {
1924 # / at end means we don't want the slash to be shown
1925 if( substr( $target, -1, 1 ) == '/' ) {
1926 $target = substr( $target, 1, -1 );
1929 $noslash = substr( $target, 1 );
1932 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1933 if( '' === $text ) {
1935 } # this might be changed for ugliness reasons
1937 # check for .. subpage backlinks
1939 $nodotdot = $target;
1940 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1942 $nodotdot = substr( $nodotdot, 3 );
1944 if($dotdotcount > 0) {
1945 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1946 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1947 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1948 # / at the end means don't show full path
1949 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1950 $nodotdot = substr( $nodotdot, 0, -1 );
1951 if( '' === $text ) {
1955 $nodotdot = trim( $nodotdot );
1956 if( $nodotdot != '' ) {
1957 $ret .= '/' . $nodotdot;
1964 wfProfileOut( $fname );
1969 * Used by doBlockLevels()
1972 /* private */ function closeParagraph() {
1974 if ( '' != $this->mLastSection
) {
1975 $result = '</' . $this->mLastSection
. ">\n";
1977 $this->mInPre
= false;
1978 $this->mLastSection
= '';
1981 # getCommon() returns the length of the longest common substring
1982 # of both arguments, starting at the beginning of both.
1984 /* private */ function getCommon( $st1, $st2 ) {
1985 $fl = strlen( $st1 );
1986 $shorter = strlen( $st2 );
1987 if ( $fl < $shorter ) { $shorter = $fl; }
1989 for ( $i = 0; $i < $shorter; ++
$i ) {
1990 if ( $st1{$i} != $st2{$i} ) { break; }
1994 # These next three functions open, continue, and close the list
1995 # element appropriate to the prefix character passed into them.
1997 /* private */ function openList( $char ) {
1998 $result = $this->closeParagraph();
2000 if ( '*' == $char ) { $result .= '<ul><li>'; }
2001 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2002 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2003 else if ( ';' == $char ) {
2004 $result .= '<dl><dt>';
2005 $this->mDTopen
= true;
2007 else { $result = '<!-- ERR 1 -->'; }
2012 /* private */ function nextItem( $char ) {
2013 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2014 else if ( ':' == $char ||
';' == $char ) {
2016 if ( $this->mDTopen
) { $close = '</dt>'; }
2017 if ( ';' == $char ) {
2018 $this->mDTopen
= true;
2019 return $close . '<dt>';
2021 $this->mDTopen
= false;
2022 return $close . '<dd>';
2025 return '<!-- ERR 2 -->';
2028 /* private */ function closeList( $char ) {
2029 if ( '*' == $char ) { $text = '</li></ul>'; }
2030 else if ( '#' == $char ) { $text = '</li></ol>'; }
2031 else if ( ':' == $char ) {
2032 if ( $this->mDTopen
) {
2033 $this->mDTopen
= false;
2034 $text = '</dt></dl>';
2036 $text = '</dd></dl>';
2039 else { return '<!-- ERR 3 -->'; }
2045 * Make lists from lines starting with ':', '*', '#', etc.
2048 * @return string the lists rendered as HTML
2050 function doBlockLevels( $text, $linestart ) {
2051 $fname = 'Parser::doBlockLevels';
2052 wfProfileIn( $fname );
2054 # Parsing through the text line by line. The main thing
2055 # happening here is handling of block-level elements p, pre,
2056 # and making lists from lines starting with * # : etc.
2058 $textLines = explode( "\n", $text );
2060 $lastPrefix = $output = '';
2061 $this->mDTopen
= $inBlockElem = false;
2063 $paragraphStack = false;
2065 if ( !$linestart ) {
2066 $output .= array_shift( $textLines );
2068 foreach ( $textLines as $oLine ) {
2069 $lastPrefixLength = strlen( $lastPrefix );
2070 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2071 $preOpenMatch = preg_match('/<pre/i', $oLine );
2072 if ( !$this->mInPre
) {
2073 # Multiple prefixes may abut each other for nested lists.
2074 $prefixLength = strspn( $oLine, '*#:;' );
2075 $pref = substr( $oLine, 0, $prefixLength );
2078 $pref2 = str_replace( ';', ':', $pref );
2079 $t = substr( $oLine, $prefixLength );
2080 $this->mInPre
= !empty($preOpenMatch);
2082 # Don't interpret any other prefixes in preformatted text
2084 $pref = $pref2 = '';
2089 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2090 # Same as the last item, so no need to deal with nesting or opening stuff
2091 $output .= $this->nextItem( substr( $pref, -1 ) );
2092 $paragraphStack = false;
2094 if ( substr( $pref, -1 ) == ';') {
2095 # The one nasty exception: definition lists work like this:
2096 # ; title : definition text
2097 # So we check for : in the remainder text to split up the
2098 # title and definition, without b0rking links.
2100 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2102 $output .= $term . $this->nextItem( ':' );
2105 } elseif( $prefixLength ||
$lastPrefixLength ) {
2106 # Either open or close a level...
2107 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2108 $paragraphStack = false;
2110 while( $commonPrefixLength < $lastPrefixLength ) {
2111 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2112 --$lastPrefixLength;
2114 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2115 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2117 while ( $prefixLength > $commonPrefixLength ) {
2118 $char = substr( $pref, $commonPrefixLength, 1 );
2119 $output .= $this->openList( $char );
2121 if ( ';' == $char ) {
2122 # FIXME: This is dupe of code above
2123 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2125 $output .= $term . $this->nextItem( ':' );
2128 ++
$commonPrefixLength;
2130 $lastPrefix = $pref2;
2132 if( 0 == $prefixLength ) {
2133 wfProfileIn( "$fname-paragraph" );
2134 # No prefix (not in list)--go to paragraph mode
2135 // XXX: use a stack for nestable elements like span, table and div
2136 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2137 $closematch = preg_match(
2138 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2139 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2140 if ( $openmatch or $closematch ) {
2141 $paragraphStack = false;
2142 #Â TODO bug 5718: paragraph closed
2143 $output .= $this->closeParagraph();
2144 if ( $preOpenMatch and !$preCloseMatch ) {
2145 $this->mInPre
= true;
2147 if ( $closematch ) {
2148 $inBlockElem = false;
2150 $inBlockElem = true;
2152 } else if ( !$inBlockElem && !$this->mInPre
) {
2153 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2155 if ($this->mLastSection
!= 'pre') {
2156 $paragraphStack = false;
2157 $output .= $this->closeParagraph().'<pre>';
2158 $this->mLastSection
= 'pre';
2160 $t = substr( $t, 1 );
2163 if ( '' == trim($t) ) {
2164 if ( $paragraphStack ) {
2165 $output .= $paragraphStack.'<br />';
2166 $paragraphStack = false;
2167 $this->mLastSection
= 'p';
2169 if ($this->mLastSection
!= 'p' ) {
2170 $output .= $this->closeParagraph();
2171 $this->mLastSection
= '';
2172 $paragraphStack = '<p>';
2174 $paragraphStack = '</p><p>';
2178 if ( $paragraphStack ) {
2179 $output .= $paragraphStack;
2180 $paragraphStack = false;
2181 $this->mLastSection
= 'p';
2182 } else if ($this->mLastSection
!= 'p') {
2183 $output .= $this->closeParagraph().'<p>';
2184 $this->mLastSection
= 'p';
2189 wfProfileOut( "$fname-paragraph" );
2191 // somewhere above we forget to get out of pre block (bug 785)
2192 if($preCloseMatch && $this->mInPre
) {
2193 $this->mInPre
= false;
2195 if ($paragraphStack === false) {
2199 while ( $prefixLength ) {
2200 $output .= $this->closeList( $pref2{$prefixLength-1} );
2203 if ( '' != $this->mLastSection
) {
2204 $output .= '</' . $this->mLastSection
. '>';
2205 $this->mLastSection
= '';
2208 wfProfileOut( $fname );
2213 * Split up a string on ':', ignoring any occurences inside tags
2214 * to prevent illegal overlapping.
2215 * @param string $str the string to split
2216 * @param string &$before set to everything before the ':'
2217 * @param string &$after set to everything after the ':'
2218 * return string the position of the ':', or false if none found
2220 function findColonNoLinks($str, &$before, &$after) {
2221 $fname = 'Parser::findColonNoLinks';
2222 wfProfileIn( $fname );
2224 $pos = strpos( $str, ':' );
2225 if( $pos === false ) {
2227 wfProfileOut( $fname );
2231 $lt = strpos( $str, '<' );
2232 if( $lt === false ||
$lt > $pos ) {
2233 // Easy; no tag nesting to worry about
2234 $before = substr( $str, 0, $pos );
2235 $after = substr( $str, $pos+
1 );
2236 wfProfileOut( $fname );
2240 // Ugly state machine to walk through avoiding tags.
2241 $state = MW_COLON_STATE_TEXT
;
2243 $len = strlen( $str );
2244 for( $i = 0; $i < $len; $i++
) {
2248 // (Using the number is a performance hack for common cases)
2249 case 0: // MW_COLON_STATE_TEXT:
2252 // Could be either a <start> tag or an </end> tag
2253 $state = MW_COLON_STATE_TAGSTART
;
2258 $before = substr( $str, 0, $i );
2259 $after = substr( $str, $i +
1 );
2260 wfProfileOut( $fname );
2263 // Embedded in a tag; don't break it.
2266 // Skip ahead looking for something interesting
2267 $colon = strpos( $str, ':', $i );
2268 if( $colon === false ) {
2269 // Nothing else interesting
2270 wfProfileOut( $fname );
2273 $lt = strpos( $str, '<', $i );
2274 if( $stack === 0 ) {
2275 if( $lt === false ||
$colon < $lt ) {
2277 $before = substr( $str, 0, $colon );
2278 $after = substr( $str, $colon +
1 );
2279 wfProfileOut( $fname );
2283 if( $lt === false ) {
2284 // Nothing else interesting to find; abort!
2285 // We're nested, but there's no close tags left. Abort!
2288 // Skip ahead to next tag start
2290 $state = MW_COLON_STATE_TAGSTART
;
2293 case 1: // MW_COLON_STATE_TAG:
2298 $state = MW_COLON_STATE_TEXT
;
2301 // Slash may be followed by >?
2302 $state = MW_COLON_STATE_TAGSLASH
;
2308 case 2: // MW_COLON_STATE_TAGSTART:
2311 $state = MW_COLON_STATE_CLOSETAG
;
2314 $state = MW_COLON_STATE_COMMENT
;
2317 // Illegal early close? This shouldn't happen D:
2318 $state = MW_COLON_STATE_TEXT
;
2321 $state = MW_COLON_STATE_TAG
;
2324 case 3: // MW_COLON_STATE_CLOSETAG:
2329 wfDebug( "Invalid input in $fname; too many close tags\n" );
2330 wfProfileOut( $fname );
2333 $state = MW_COLON_STATE_TEXT
;
2336 case MW_COLON_STATE_TAGSLASH
:
2338 // Yes, a self-closed tag <blah/>
2339 $state = MW_COLON_STATE_TEXT
;
2341 // Probably we're jumping the gun, and this is an attribute
2342 $state = MW_COLON_STATE_TAG
;
2345 case 5: // MW_COLON_STATE_COMMENT:
2347 $state = MW_COLON_STATE_COMMENTDASH
;
2350 case MW_COLON_STATE_COMMENTDASH
:
2352 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2354 $state = MW_COLON_STATE_COMMENT
;
2357 case MW_COLON_STATE_COMMENTDASHDASH
:
2359 $state = MW_COLON_STATE_TEXT
;
2361 $state = MW_COLON_STATE_COMMENT
;
2365 throw new MWException( "State machine error in $fname" );
2369 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2372 wfProfileOut( $fname );
2377 * Return value of a magic variable (like PAGENAME)
2381 function getVariableValue( $index ) {
2382 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2385 * Some of these require message or data lookups and can be
2386 * expensive to check many times.
2388 static $varCache = array();
2389 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2390 if ( isset( $varCache[$index] ) ) {
2391 return $varCache[$index];
2396 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2399 global $wgLocaltimezone;
2400 if ( isset( $wgLocaltimezone ) ) {
2401 $oldtz = getenv( 'TZ' );
2402 putenv( 'TZ='.$wgLocaltimezone );
2404 $localTimestamp = date( 'YmdHis', $ts );
2405 $localMonth = date( 'm', $ts );
2406 $localMonthName = date( 'n', $ts );
2407 $localDay = date( 'j', $ts );
2408 $localDay2 = date( 'd', $ts );
2409 $localDayOfWeek = date( 'w', $ts );
2410 $localWeek = date( 'W', $ts );
2411 $localYear = date( 'Y', $ts );
2412 $localHour = date( 'H', $ts );
2413 if ( isset( $wgLocaltimezone ) ) {
2414 putenv( 'TZ='.$oldtz );
2418 case 'currentmonth':
2419 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2420 case 'currentmonthname':
2421 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2422 case 'currentmonthnamegen':
2423 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2424 case 'currentmonthabbrev':
2425 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2427 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2429 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2431 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2432 case 'localmonthname':
2433 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2434 case 'localmonthnamegen':
2435 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2436 case 'localmonthabbrev':
2437 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2439 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2441 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2443 return $this->mTitle
->getText();
2445 return $this->mTitle
->getPartialURL();
2446 case 'fullpagename':
2447 return $this->mTitle
->getPrefixedText();
2448 case 'fullpagenamee':
2449 return $this->mTitle
->getPrefixedURL();
2451 return $this->mTitle
->getSubpageText();
2452 case 'subpagenamee':
2453 return $this->mTitle
->getSubpageUrlForm();
2454 case 'basepagename':
2455 return $this->mTitle
->getBaseText();
2456 case 'basepagenamee':
2457 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2458 case 'talkpagename':
2459 if( $this->mTitle
->canTalk() ) {
2460 $talkPage = $this->mTitle
->getTalkPage();
2461 return $talkPage->getPrefixedText();
2465 case 'talkpagenamee':
2466 if( $this->mTitle
->canTalk() ) {
2467 $talkPage = $this->mTitle
->getTalkPage();
2468 return $talkPage->getPrefixedUrl();
2472 case 'subjectpagename':
2473 $subjPage = $this->mTitle
->getSubjectPage();
2474 return $subjPage->getPrefixedText();
2475 case 'subjectpagenamee':
2476 $subjPage = $this->mTitle
->getSubjectPage();
2477 return $subjPage->getPrefixedUrl();
2479 return $this->mRevisionId
;
2481 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2482 case 'revisionday2':
2483 return substr( $this->getRevisionTimestamp(), 6, 2 );
2484 case 'revisionmonth':
2485 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2486 case 'revisionyear':
2487 return substr( $this->getRevisionTimestamp(), 0, 4 );
2488 case 'revisiontimestamp':
2489 return $this->getRevisionTimestamp();
2491 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2493 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2495 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2497 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2498 case 'subjectspace':
2499 return $this->mTitle
->getSubjectNsText();
2500 case 'subjectspacee':
2501 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2502 case 'currentdayname':
2503 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2505 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2507 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2509 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2511 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2512 // int to remove the padding
2513 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2515 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2516 case 'localdayname':
2517 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2519 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2521 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2523 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2525 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2526 // int to remove the padding
2527 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2529 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2530 case 'numberofarticles':
2531 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2532 case 'numberoffiles':
2533 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2534 case 'numberofusers':
2535 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2536 case 'numberofpages':
2537 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2538 case 'numberofadmins':
2539 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2540 case 'currenttimestamp':
2541 return $varCache[$index] = wfTimestampNow();
2542 case 'localtimestamp':
2543 return $varCache[$index] = $localTimestamp;
2544 case 'currentversion':
2545 return $varCache[$index] = SpecialVersion
::getVersion();
2551 return $wgServerName;
2553 return $wgScriptPath;
2554 case 'directionmark':
2555 return $wgContLang->getDirMark();
2556 case 'contentlanguage':
2557 global $wgContLanguageCode;
2558 return $wgContLanguageCode;
2561 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2569 * initialise the magic variables (like CURRENTMONTHNAME)
2573 function initialiseVariables() {
2574 $fname = 'Parser::initialiseVariables';
2575 wfProfileIn( $fname );
2576 $variableIDs = MagicWord
::getVariableIDs();
2578 $this->mVariables
= array();
2579 foreach ( $variableIDs as $id ) {
2580 $mw =& MagicWord
::get( $id );
2581 $mw->addToArray( $this->mVariables
, $id );
2583 wfProfileOut( $fname );
2587 * parse any parentheses in format ((title|part|part))
2588 * and call callbacks to get a replacement text for any found piece
2590 * @param string $text The text to parse
2591 * @param array $callbacks rules in form:
2592 * '{' => array( # opening parentheses
2593 * 'end' => '}', # closing parentheses
2594 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2595 * 3 => callback # replacement callback to call if {{{..}}} is found
2598 * 'min' => 2, # Minimum parenthesis count in cb
2599 * 'max' => 3, # Maximum parenthesis count in cb
2602 function replace_callback ($text, $callbacks) {
2603 wfProfileIn( __METHOD__
);
2604 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2605 $lastOpeningBrace = -1; # last not closed parentheses
2607 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2610 while ( $i < strlen( $text ) ) {
2611 # Find next opening brace, closing brace or pipe
2612 if ( $lastOpeningBrace == -1 ) {
2613 $currentClosing = '';
2614 $search = $validOpeningBraces;
2616 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2617 $search = $validOpeningBraces . '|' . $currentClosing;
2620 $i +
= strcspn( $text, $search, $i );
2621 if ( $i < strlen( $text ) ) {
2622 if ( $text[$i] == '|' ) {
2624 } elseif ( $text[$i] == $currentClosing ) {
2626 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2628 $rule = $callbacks[$text[$i]];
2630 # Some versions of PHP have a strcspn which stops on null characters
2631 # Ignore and continue
2640 if ( $found == 'open' ) {
2641 # found opening brace, let's add it to parentheses stack
2642 $piece = array('brace' => $text[$i],
2643 'braceEnd' => $rule['end'],
2647 # count opening brace characters
2648 $piece['count'] = strspn( $text, $piece['brace'], $i );
2649 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2650 $i +
= $piece['count'];
2652 # we need to add to stack only if opening brace count is enough for one of the rules
2653 if ( $piece['count'] >= $rule['min'] ) {
2654 $lastOpeningBrace ++
;
2655 $openingBraceStack[$lastOpeningBrace] = $piece;
2657 } elseif ( $found == 'close' ) {
2658 # lets check if it is enough characters for closing brace
2659 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2660 $count = strspn( $text, $text[$i], $i, $maxCount );
2662 # check for maximum matching characters (if there are 5 closing
2663 # characters, we will probably need only 3 - depending on the rules)
2665 $matchingCallback = null;
2666 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2667 if ( $count > $cbType['max'] ) {
2668 # The specified maximum exists in the callback array, unless the caller
2670 $matchingCount = $cbType['max'];
2672 # Count is less than the maximum
2673 # Skip any gaps in the callback array to find the true largest match
2674 # Need to use array_key_exists not isset because the callback can be null
2675 $matchingCount = $count;
2676 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2681 if ($matchingCount <= 0) {
2685 $matchingCallback = $cbType['cb'][$matchingCount];
2687 # let's set a title or last part (if '|' was found)
2688 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2689 $openingBraceStack[$lastOpeningBrace]['title'] =
2690 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2691 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2693 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2694 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2695 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2698 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2699 $pieceEnd = $i +
$matchingCount;
2701 if( is_callable( $matchingCallback ) ) {
2703 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2704 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2705 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2706 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2708 # finally we can call a user callback and replace piece of text
2709 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2710 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2711 $i = $pieceStart +
strlen($replaceWith);
2713 # null value for callback means that parentheses should be parsed, but not replaced
2714 $i +
= $matchingCount;
2717 # reset last opening parentheses, but keep it in case there are unused characters
2718 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2719 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2720 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2723 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2724 $openingBraceStack[$lastOpeningBrace--] = null;
2726 if ($matchingCount < $piece['count']) {
2727 $piece['count'] -= $matchingCount;
2728 $piece['startAt'] -= $matchingCount;
2729 $piece['partStart'] = $piece['startAt'];
2730 # do we still qualify for any callback with remaining count?
2731 $currentCbList = $callbacks[$piece['brace']]['cb'];
2732 while ( $piece['count'] ) {
2733 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2734 $lastOpeningBrace++
;
2735 $openingBraceStack[$lastOpeningBrace] = $piece;
2741 } elseif ( $found == 'pipe' ) {
2742 # lets set a title if it is a first separator, or next part otherwise
2743 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2744 $openingBraceStack[$lastOpeningBrace]['title'] =
2745 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2746 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2749 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2750 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2751 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2753 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2757 wfProfileOut( __METHOD__
);
2762 * Replace magic variables, templates, and template arguments
2763 * with the appropriate text. Templates are substituted recursively,
2764 * taking care to avoid infinite loops.
2766 * Note that the substitution depends on value of $mOutputType:
2767 * OT_WIKI: only {{subst:}} templates
2768 * OT_MSG: only magic variables
2769 * OT_HTML: all templates and magic variables
2771 * @param string $tex The text to transform
2772 * @param array $args Key-value pairs representing template parameters to substitute
2773 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2776 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2777 # Prevent too big inclusions
2778 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2782 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2783 wfProfileIn( $fname );
2785 # This function is called recursively. To keep track of arguments we need a stack:
2786 array_push( $this->mArgStack
, $args );
2788 $braceCallbacks = array();
2790 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2792 if ( $this->mOutputType
!= OT_MSG
) {
2793 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2795 if ( $braceCallbacks ) {
2799 'cb' => $braceCallbacks,
2800 'min' => $argsOnly ?
3 : 2,
2801 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2805 'cb' => array(2=>null),
2810 $text = $this->replace_callback ($text, $callbacks);
2812 array_pop( $this->mArgStack
);
2814 wfProfileOut( $fname );
2819 * Replace magic variables
2822 function variableSubstitution( $matches ) {
2824 $fname = 'Parser::variableSubstitution';
2825 $varname = $wgContLang->lc($matches[1]);
2826 wfProfileIn( $fname );
2828 if ( $this->mOutputType
== OT_WIKI
) {
2829 # Do only magic variables prefixed by SUBST
2830 $mwSubst =& MagicWord
::get( 'subst' );
2831 if (!$mwSubst->matchStartAndRemove( $varname ))
2833 # Note that if we don't substitute the variable below,
2834 # we don't remove the {{subst:}} magic word, in case
2835 # it is a template rather than a magic variable.
2837 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2838 $id = $this->mVariables
[$varname];
2839 # Now check if we did really match, case sensitive or not
2840 $mw =& MagicWord
::get( $id );
2841 if ($mw->match($matches[1])) {
2842 $text = $this->getVariableValue( $id );
2843 $this->mOutput
->mContainsOldMagic
= true;
2845 $text = $matches[0];
2848 $text = $matches[0];
2850 wfProfileOut( $fname );
2855 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2856 static function createAssocArgs( $args ) {
2857 $assocArgs = array();
2859 foreach( $args as $arg ) {
2860 $eqpos = strpos( $arg, '=' );
2861 if ( $eqpos === false ) {
2862 $assocArgs[$index++
] = $arg;
2864 $name = trim( substr( $arg, 0, $eqpos ) );
2865 $value = trim( substr( $arg, $eqpos+
1 ) );
2866 if ( $value === false ) {
2869 if ( $name !== false ) {
2870 $assocArgs[$name] = $value;
2879 * Return the text of a template, after recursively
2880 * replacing any variables or templates within the template.
2882 * @param array $piece The parts of the template
2883 * $piece['text']: matched text
2884 * $piece['title']: the title, i.e. the part before the |
2885 * $piece['parts']: the parameter array
2886 * @return string the text of the template
2889 function braceSubstitution( $piece ) {
2890 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2891 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2892 wfProfileIn( $fname );
2893 wfProfileIn( __METHOD__
.'-setup' );
2896 $found = false; # $text has been filled
2897 $nowiki = false; # wiki markup in $text should be escaped
2898 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2899 $noargs = false; # Don't replace triple-brace arguments in $text
2900 $replaceHeadings = false; # Make the edit section links go to the template not the article
2901 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2902 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2903 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2905 # Title object, where $text came from
2911 # $part1 is the bit before the first |, and must contain only title characters
2912 # $args is a list of arguments, starting from index 0, not including $part1
2914 $titleText = $part1 = $piece['title'];
2915 # If the third subpattern matched anything, it will start with |
2917 if (null == $piece['parts']) {
2918 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2919 if ($replaceWith != $piece['text']) {
2920 $text = $replaceWith;
2927 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2928 wfProfileOut( __METHOD__
.'-setup' );
2931 wfProfileIn( __METHOD__
.'-modifiers' );
2933 $mwSubst =& MagicWord
::get( 'subst' );
2934 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2935 # One of two possibilities is true:
2936 # 1) Found SUBST but not in the PST phase
2937 # 2) Didn't find SUBST and in the PST phase
2938 # In either case, return without further processing
2939 $text = $piece['text'];
2946 # MSG, MSGNW and RAW
2949 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2950 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2953 # Remove obsolete MSG:
2954 $mwMsg =& MagicWord
::get( 'msg' );
2955 $mwMsg->matchStartAndRemove( $part1 );
2959 $mwRaw =& MagicWord
::get( 'raw' );
2960 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2961 $forceRawInterwiki = true;
2964 wfProfileOut( __METHOD__
.'-modifiers' );
2966 //save path level before recursing into functions & templates.
2967 $lastPathLevel = $this->mTemplatePath
;
2971 wfProfileIn( __METHOD__
. '-pfunc' );
2973 $colonPos = strpos( $part1, ':' );
2974 if ( $colonPos !== false ) {
2975 # Case sensitive functions
2976 $function = substr( $part1, 0, $colonPos );
2977 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2978 $function = $this->mFunctionSynonyms
[1][$function];
2980 # Case insensitive functions
2981 $function = strtolower( $function );
2982 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2983 $function = $this->mFunctionSynonyms
[0][$function];
2989 $funcArgs = array_map( 'trim', $args );
2990 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2991 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2994 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2998 if ( is_array( $result ) ) {
2999 if ( isset( $result[0] ) ) {
3000 $text = $linestart . $result[0];
3001 unset( $result[0] );
3004 // Extract flags into the local scope
3005 // This allows callers to set flags such as nowiki, noparse, found, etc.
3008 $text = $linestart . $result;
3012 wfProfileOut( __METHOD__
. '-pfunc' );
3015 # Template table test
3017 # Did we encounter this template already? If yes, it is in the cache
3018 # and we need to check for loops.
3019 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3022 # Infinite loop test
3023 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3027 $text = $linestart .
3028 "[[$part1]]<!-- WARNING: template loop detected -->";
3029 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3031 # set $text to cached message.
3032 $text = $linestart . $this->mTemplates
[$piece['title']];
3036 # Load from database
3038 wfProfileIn( __METHOD__
. '-loadtpl' );
3040 # declaring $subpage directly in the function call
3041 # does not work correctly with references and breaks
3042 # {{/subpage}}-style inclusions
3044 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3045 if ($subpage !== '') {
3046 $ns = $this->mTitle
->getNamespace();
3048 $title = Title
::newFromText( $part1, $ns );
3051 if ( !is_null( $title ) ) {
3052 $titleText = $title->getPrefixedText();
3053 # Check for language variants if the template is not found
3054 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3055 $wgContLang->findVariantLink($part1, $title);
3058 if ( !$title->isExternal() ) {
3059 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3060 $text = SpecialPage
::capturePath( $title );
3061 if ( is_string( $text ) ) {
3066 $this->disableCache();
3069 $articleContent = $this->fetchTemplate( $title );
3070 if ( $articleContent !== false ) {
3072 $text = $articleContent;
3073 $replaceHeadings = true;
3077 # If the title is valid but undisplayable, make a link to it
3078 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3079 $text = "[[:$titleText]]";
3082 } elseif ( $title->isTrans() ) {
3083 // Interwiki transclusion
3084 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3085 $text = $this->interwikiTransclude( $title, 'render' );
3089 $text = $this->interwikiTransclude( $title, 'raw' );
3090 $replaceHeadings = true;
3095 # Template cache array insertion
3096 # Use the original $piece['title'] not the mangled $part1, so that
3097 # modifiers such as RAW: produce separate cache entries
3100 // A special page; don't store it in the template cache.
3102 $this->mTemplates
[$piece['title']] = $text;
3104 $text = $linestart . $text;
3107 wfProfileOut( __METHOD__
. '-loadtpl' );
3110 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3111 # Error, oversize inclusion
3112 $text = $linestart .
3113 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3118 # Recursive parsing, escaping and link table handling
3119 # Only for HTML output
3120 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3121 $text = wfEscapeWikiText( $text );
3122 } elseif ( !$this->ot
['msg'] && $found ) {
3124 $assocArgs = array();
3126 # Clean up argument array
3127 $assocArgs = self
::createAssocArgs($args);
3128 # Add a new element to the templace recursion path
3129 $this->mTemplatePath
[$part1] = 1;
3133 # If there are any <onlyinclude> tags, only include them
3134 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3135 $replacer = new OnlyIncludeReplacer
;
3136 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3137 array( &$replacer, 'replace' ), $text );
3138 $text = $replacer->output
;
3140 # Remove <noinclude> sections and <includeonly> tags
3141 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3142 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3144 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3145 # Strip <nowiki>, <pre>, etc.
3146 $text = $this->strip( $text, $this->mStripState
);
3147 if ( $this->ot
['html'] ) {
3148 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3149 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3150 $text = Sanitizer
::removeHTMLcomments( $text );
3153 $text = $this->replaceVariables( $text, $assocArgs );
3155 # If the template begins with a table or block-level
3156 # element, it should be treated as beginning a new line.
3157 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3158 $text = "\n" . $text;
3160 } elseif ( !$noargs ) {
3161 # $noparse and !$noargs
3162 # Just replace the arguments, not any double-brace items
3163 # This is used for rendered interwiki transclusion
3164 $text = $this->replaceVariables( $text, $assocArgs, true );
3167 # Prune lower levels off the recursion check path
3168 $this->mTemplatePath
= $lastPathLevel;
3170 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3171 # Error, oversize inclusion
3172 $text = $linestart .
3173 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3179 wfProfileOut( $fname );
3180 return $piece['text'];
3182 wfProfileIn( __METHOD__
. '-placeholders' );
3184 # Replace raw HTML by a placeholder
3185 # Add a blank line preceding, to prevent it from mucking up
3186 # immediately preceding headings
3187 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3189 # replace ==section headers==
3190 # XXX this needs to go away once we have a better parser.
3191 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3192 if( !is_null( $title ) )
3193 $encodedname = base64_encode($title->getPrefixedDBkey());
3195 $encodedname = base64_encode("");
3196 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3197 PREG_SPLIT_DELIM_CAPTURE
);
3199 $nsec = $headingOffset;
3200 for( $i = 0; $i < count($m); $i +
= 2 ) {
3202 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3204 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3209 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3210 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3211 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3217 wfProfileOut( __METHOD__
. '-placeholders' );
3220 # Prune lower levels off the recursion check path
3221 $this->mTemplatePath
= $lastPathLevel;
3224 wfProfileOut( $fname );
3225 return $piece['text'];
3227 wfProfileOut( $fname );
3233 * Fetch the unparsed text of a template and register a reference to it.
3235 function fetchTemplate( $title ) {
3237 // Loop to fetch the article, with up to 1 redirect
3238 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3239 $rev = Revision
::newFromTitle( $title );
3240 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3242 $text = $rev->getText();
3243 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3245 $message = $wgLang->lcfirst( $title->getText() );
3246 $text = wfMsgForContentNoTrans( $message );
3247 if( wfEmptyMsg( $message, $text ) ) {
3254 if ( $text === false ) {
3258 $title = Title
::newFromRedirect( $text );
3264 * Transclude an interwiki link.
3266 function interwikiTransclude( $title, $action ) {
3267 global $wgEnableScaryTranscluding;
3269 if (!$wgEnableScaryTranscluding)
3270 return wfMsg('scarytranscludedisabled');
3272 $url = $title->getFullUrl( "action=$action" );
3274 if (strlen($url) > 255)
3275 return wfMsg('scarytranscludetoolong');
3276 return $this->fetchScaryTemplateMaybeFromCache($url);
3279 function fetchScaryTemplateMaybeFromCache($url) {
3280 global $wgTranscludeCacheExpiry;
3281 $dbr =& wfGetDB(DB_SLAVE
);
3282 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3283 array('tc_url' => $url));
3285 $time = $obj->tc_time
;
3286 $text = $obj->tc_contents
;
3287 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3292 $text = Http
::get($url);
3294 return wfMsg('scarytranscludefailed', $url);
3296 $dbw =& wfGetDB(DB_MASTER
);
3297 $dbw->replace('transcache', array('tc_url'), array(
3299 'tc_time' => time(),
3300 'tc_contents' => $text));
3306 * Triple brace replacement -- used for template arguments
3309 function argSubstitution( $matches ) {
3310 $arg = trim( $matches['title'] );
3311 $text = $matches['text'];
3312 $inputArgs = end( $this->mArgStack
);
3314 if ( array_key_exists( $arg, $inputArgs ) ) {
3315 $text = $inputArgs[$arg];
3316 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3317 null != $matches['parts'] && count($matches['parts']) > 0) {
3318 $text = $matches['parts'][0];
3320 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3321 $text = $matches['text'] .
3322 '<!-- WARNING: argument omitted, expansion size too large -->';
3329 * Increment an include size counter
3331 * @param string $type The type of expansion
3332 * @param integer $size The size of the text
3333 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3335 function incrementIncludeSize( $type, $size ) {
3336 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3339 $this->mIncludeSizes
[$type] +
= $size;
3345 * Detect __NOGALLERY__ magic word and set a placeholder
3347 function stripNoGallery( &$text ) {
3348 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3350 $mw = MagicWord
::get( 'nogallery' );
3351 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3355 * Detect __TOC__ magic word and set a placeholder
3357 function stripToc( $text ) {
3358 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3360 $mw = MagicWord
::get( 'notoc' );
3361 if( $mw->matchAndRemove( $text ) ) {
3362 $this->mShowToc
= false;
3365 $mw = MagicWord
::get( 'toc' );
3366 if( $mw->match( $text ) ) {
3367 $this->mShowToc
= true;
3368 $this->mForceTocPosition
= true;
3370 // Set a placeholder. At the end we'll fill it in with the TOC.
3371 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3373 // Only keep the first one.
3374 $text = $mw->replace( '', $text );
3380 * This function accomplishes several tasks:
3381 * 1) Auto-number headings if that option is enabled
3382 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3383 * 3) Add a Table of contents on the top for users who have enabled the option
3384 * 4) Auto-anchor headings
3386 * It loops through all headlines, collects the necessary data, then splits up the
3387 * string and re-inserts the newly formatted headlines.
3389 * @param string $text
3390 * @param boolean $isMain
3393 function formatHeadings( $text, $isMain=true ) {
3394 global $wgMaxTocLevel, $wgContLang;
3396 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3397 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3400 $showEditLink = $this->mOptions
->getEditSection();
3403 # Inhibit editsection links if requested in the page
3404 $esw =& MagicWord
::get( 'noeditsection' );
3405 if( $esw->matchAndRemove( $text ) ) {
3409 # Get all headlines for numbering them and adding funky stuff like [edit]
3410 # links - this is for later, but we need the number of headlines right now
3412 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3414 # if there are fewer than 4 headlines in the article, do not show TOC
3415 # unless it's been explicitly enabled.
3416 $enoughToc = $this->mShowToc
&&
3417 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3419 # Allow user to stipulate that a page should have a "new section"
3420 # link added via __NEWSECTIONLINK__
3421 $mw =& MagicWord
::get( 'newsectionlink' );
3422 if( $mw->matchAndRemove( $text ) )
3423 $this->mOutput
->setNewSection( true );
3425 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3426 # override above conditions and always show TOC above first header
3427 $mw =& MagicWord
::get( 'forcetoc' );
3428 if ($mw->matchAndRemove( $text ) ) {
3429 $this->mShowToc
= true;
3433 # Never ever show TOC if no headers
3434 if( $numMatches < 1 ) {
3438 # We need this to perform operations on the HTML
3439 $sk =& $this->mOptions
->getSkin();
3443 $sectionCount = 0; # headlineCount excluding template sections
3445 # Ugh .. the TOC should have neat indentation levels which can be
3446 # passed to the skin functions. These are determined here
3450 $sublevelCount = array();
3451 $levelCount = array();
3458 foreach( $matches[3] as $headline ) {
3460 $templatetitle = '';
3461 $templatesection = 0;
3464 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3466 $templatetitle = base64_decode($mat[1]);
3467 $templatesection = 1 +
(int)base64_decode($mat[2]);
3468 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3472 $prevlevel = $level;
3473 $prevtoclevel = $toclevel;
3475 $level = $matches[1][$headlineCount];
3477 if( $doNumberHeadings ||
$enoughToc ) {
3479 if ( $level > $prevlevel ) {
3480 # Increase TOC level
3482 $sublevelCount[$toclevel] = 0;
3483 if( $toclevel<$wgMaxTocLevel ) {
3484 $toc .= $sk->tocIndent();
3487 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3488 # Decrease TOC level, find level to jump to
3490 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3491 # Can only go down to level 1
3494 for ($i = $toclevel; $i > 0; $i--) {
3495 if ( $levelCount[$i] == $level ) {
3496 # Found last matching level
3500 elseif ( $levelCount[$i] < $level ) {
3501 # Found first matching level below current level
3507 if( $toclevel<$wgMaxTocLevel ) {
3508 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3512 # No change in level, end TOC line
3513 if( $toclevel<$wgMaxTocLevel ) {
3514 $toc .= $sk->tocLineEnd();
3518 $levelCount[$toclevel] = $level;
3520 # count number of headlines for each level
3521 @$sublevelCount[$toclevel]++
;
3523 for( $i = 1; $i <= $toclevel; $i++
) {
3524 if( !empty( $sublevelCount[$i] ) ) {
3528 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3534 # The canonized header is a version of the header text safe to use for links
3535 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3536 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3538 # Remove link placeholders by the link text.
3539 # <!--LINK number-->
3541 # link text with suffix
3542 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3543 "\$this->mLinkHolders['texts'][\$1]",
3544 $canonized_headline );
3545 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3546 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3547 $canonized_headline );
3550 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3551 $tocline = trim( $canonized_headline );
3552 # Save headline for section edit hint before it's escaped
3553 $headline_hint = trim( $canonized_headline );
3554 $canonized_headline = Sanitizer
::escapeId( $tocline );
3555 $refers[$headlineCount] = $canonized_headline;
3557 # count how many in assoc. array so we can track dupes in anchors
3558 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3559 $refcount[$headlineCount]=$refers[$canonized_headline];
3561 # Don't number the heading if it is the only one (looks silly)
3562 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3563 # the two are different if the line contains a link
3564 $headline=$numbering . ' ' . $headline;
3567 # Create the anchor for linking from the TOC to the section
3568 $anchor = $canonized_headline;
3569 if($refcount[$headlineCount] > 1 ) {
3570 $anchor .= '_' . $refcount[$headlineCount];
3572 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3573 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3575 # give headline the correct <h#> tag
3576 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3578 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3580 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3584 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3592 if( $toclevel<$wgMaxTocLevel ) {
3593 $toc .= $sk->tocUnindent( $toclevel - 1 );
3595 $toc = $sk->tocList( $toc );
3598 # split up and insert constructed headlines
3600 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3603 foreach( $blocks as $block ) {
3604 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3605 # This is the [edit] link that appears for the top block of text when
3606 # section editing is enabled
3608 # Disabled because it broke block formatting
3609 # For example, a bullet point in the top line
3610 # $full .= $sk->editSectionLink(0);
3613 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3614 # Top anchor now in skin
3618 if( !empty( $head[$i] ) ) {
3623 if( $this->mForceTocPosition
) {
3624 return str_replace( '<!--MWTOC-->', $toc, $full );
3631 * Transform wiki markup when saving a page by doing \r\n -> \n
3632 * conversion, substitting signatures, {{subst:}} templates, etc.
3634 * @param string $text the text to transform
3635 * @param Title &$title the Title object for the current article
3636 * @param User &$user the User object describing the current user
3637 * @param ParserOptions $options parsing options
3638 * @param bool $clearState whether to clear the parser state first
3639 * @return string the altered wiki markup
3642 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3643 $this->mOptions
= $options;
3644 $this->mTitle
=& $title;
3645 $this->setOutputType( OT_WIKI
);
3647 if ( $clearState ) {
3648 $this->clearState();
3651 $stripState = new StripState
;
3655 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3656 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3657 $text = $this->pstPass2( $text, $stripState, $user );
3658 $text = $stripState->unstripBoth( $text );
3663 * Pre-save transform helper function
3666 function pstPass2( $text, &$stripState, $user ) {
3667 global $wgContLang, $wgLocaltimezone;
3669 /* Note: This is the timestamp saved as hardcoded wikitext to
3670 * the database, we use $wgContLang here in order to give
3671 * everyone the same signature and use the default one rather
3672 * than the one selected in each user's preferences.
3674 if ( isset( $wgLocaltimezone ) ) {
3675 $oldtz = getenv( 'TZ' );
3676 putenv( 'TZ='.$wgLocaltimezone );
3678 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3679 ' (' . date( 'T' ) . ')';
3680 if ( isset( $wgLocaltimezone ) ) {
3681 putenv( 'TZ='.$oldtz );
3684 # Variable replacement
3685 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3686 $text = $this->replaceVariables( $text );
3688 # Strip out <nowiki> etc. added via replaceVariables
3689 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3692 $sigText = $this->getUserSig( $user );
3693 $text = strtr( $text, array(
3695 '~~~~' => "$sigText $d",
3699 # Context links: [[|name]] and [[name (context)|]]
3701 global $wgLegalTitleChars;
3702 $tc = "[$wgLegalTitleChars]";
3703 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3705 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3706 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3707 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3709 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3710 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3711 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3713 $t = $this->mTitle
->getText();
3715 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3716 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3717 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3718 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3720 # if there's no context, don't bother duplicating the title
3721 $text = preg_replace( $p2, '[[\\1]]', $text );
3724 # Trim trailing whitespace
3725 $text = rtrim( $text );
3731 * Fetch the user's signature text, if any, and normalize to
3732 * validated, ready-to-insert wikitext.
3738 function getUserSig( &$user ) {
3739 $username = $user->getName();
3740 $nickname = $user->getOption( 'nickname' );
3741 $nickname = $nickname === '' ?
$username : $nickname;
3743 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3744 # Sig. might contain markup; validate this
3745 if( $this->validateSig( $nickname ) !== false ) {
3746 # Validated; clean up (if needed) and return it
3747 return $this->cleanSig( $nickname, true );
3749 # Failed to validate; fall back to the default
3750 $nickname = $username;
3751 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3755 // Make sure nickname doesnt get a sig in a sig
3756 $nickname = $this->cleanSigInSig( $nickname );
3758 # If we're still here, make it a link to the user page
3759 $userpage = $user->getUserPage();
3760 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3764 * Check that the user's signature contains no bad XML
3766 * @param string $text
3767 * @return mixed An expanded string, or false if invalid.
3769 function validateSig( $text ) {
3770 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3774 * Clean up signature text
3776 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3777 * 2) Substitute all transclusions
3779 * @param string $text
3780 * @param $parsing Whether we're cleaning (preferences save) or parsing
3781 * @return string Signature text
3783 function cleanSig( $text, $parsing = false ) {
3785 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3787 $substWord = MagicWord
::get( 'subst' );
3788 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3789 $substText = '{{' . $substWord->getSynonym( 0 );
3791 $text = preg_replace( $substRegex, $substText, $text );
3792 $text = $this->cleanSigInSig( $text );
3793 $text = $this->replaceVariables( $text );
3795 $this->clearState();
3800 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3801 * @param string $text
3802 * @return string Signature text with /~{3,5}/ removed
3804 function cleanSigInSig( $text ) {
3805 $text = preg_replace( '/~{3,5}/', '', $text );
3810 * Set up some variables which are usually set up in parse()
3811 * so that an external function can call some class members with confidence
3814 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3815 $this->mTitle
=& $title;
3816 $this->mOptions
= $options;
3817 $this->setOutputType( $outputType );
3818 if ( $clearState ) {
3819 $this->clearState();
3824 * Transform a MediaWiki message by replacing magic variables.
3826 * @param string $text the text to transform
3827 * @param ParserOptions $options options
3828 * @return string the text with variables substituted
3831 function transformMsg( $text, $options ) {
3833 static $executing = false;
3835 $fname = "Parser::transformMsg";
3837 # Guard against infinite recursion
3843 wfProfileIn($fname);
3845 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3846 $this->mTitle
= $wgTitle;
3848 $this->mTitle
= Title
::newFromText('msg');
3850 $this->mOptions
= $options;
3851 $this->setOutputType( OT_MSG
);
3852 $this->clearState();
3853 $text = $this->replaceVariables( $text );
3856 wfProfileOut($fname);
3861 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3862 * The callback should have the following form:
3863 * function myParserHook( $text, $params, &$parser ) { ... }
3865 * Transform and return $text. Use $parser for any required context, e.g. use
3866 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3870 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3871 * @param mixed $callback The callback function (and object) to use for the tag
3873 * @return The old value of the mTagHooks array associated with the hook
3875 function setHook( $tag, $callback ) {
3876 $tag = strtolower( $tag );
3877 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3878 $this->mTagHooks
[$tag] = $callback;
3884 * Create a function, e.g. {{sum:1|2|3}}
3885 * The callback function should have the form:
3886 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3888 * The callback may either return the text result of the function, or an array with the text
3889 * in element 0, and a number of flags in the other elements. The names of the flags are
3890 * specified in the keys. Valid flags are:
3891 * found The text returned is valid, stop processing the template. This
3893 * nowiki Wiki markup in the return value should be escaped
3894 * noparse Unsafe HTML tags should not be stripped, etc.
3895 * noargs Don't replace triple-brace arguments in the return value
3896 * isHTML The returned text is HTML, armour it against wikitext transformation
3900 * @param string $id The magic word ID
3901 * @param mixed $callback The callback function (and object) to use
3902 * @param integer $flags a combination of the following flags:
3903 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3905 * @return The old callback function for this name, if any
3907 function setFunctionHook( $id, $callback, $flags = 0 ) {
3908 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3909 $this->mFunctionHooks
[$id] = $callback;
3911 # Add to function cache
3912 $mw = MagicWord
::get( $id );
3914 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3916 $synonyms = $mw->getSynonyms();
3917 $sensitive = intval( $mw->isCaseSensitive() );
3919 foreach ( $synonyms as $syn ) {
3921 if ( !$sensitive ) {
3922 $syn = strtolower( $syn );
3925 if ( !( $flags & SFH_NO_HASH
) ) {
3928 # Remove trailing colon
3929 if ( substr( $syn, -1, 1 ) == ':' ) {
3930 $syn = substr( $syn, 0, -1 );
3932 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3938 * Get all registered function hook identifiers
3942 function getFunctionHooks() {
3943 return array_keys( $this->mFunctionHooks
);
3947 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3948 * Placeholders created in Skin::makeLinkObj()
3949 * Returns an array of links found, indexed by PDBK:
3953 * $options is a bit field, RLH_FOR_UPDATE to select for update
3955 function replaceLinkHolders( &$text, $options = 0 ) {
3959 $fname = 'Parser::replaceLinkHolders';
3960 wfProfileIn( $fname );
3964 $sk =& $this->mOptions
->getSkin();
3965 $linkCache =& LinkCache
::singleton();
3967 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3968 wfProfileIn( $fname.'-check' );
3969 $dbr =& wfGetDB( DB_SLAVE
);
3970 $page = $dbr->tableName( 'page' );
3971 $threshold = $wgUser->getOption('stubthreshold');
3974 asort( $this->mLinkHolders
['namespaces'] );
3979 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3981 $title = $this->mLinkHolders
['titles'][$key];
3983 # Skip invalid entries.
3984 # Result will be ugly, but prevents crash.
3985 if ( is_null( $title ) ) {
3988 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3990 # Check if it's a static known link, e.g. interwiki
3991 if ( $title->isAlwaysKnown() ) {
3992 $colours[$pdbk] = 1;
3993 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3994 $colours[$pdbk] = 1;
3995 $this->mOutput
->addLink( $title, $id );
3996 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3997 $colours[$pdbk] = 0;
3999 # Not in the link cache, add it to the query
4000 if ( !isset( $current ) ) {
4002 $query = "SELECT page_id, page_namespace, page_title";
4003 if ( $threshold > 0 ) {
4004 $query .= ', page_len, page_is_redirect';
4006 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4007 } elseif ( $current != $ns ) {
4009 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4014 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4019 if ( $options & RLH_FOR_UPDATE
) {
4020 $query .= ' FOR UPDATE';
4023 $res = $dbr->query( $query, $fname );
4025 # Fetch data and form into an associative array
4026 # non-existent = broken
4029 while ( $s = $dbr->fetchObject($res) ) {
4030 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4031 $pdbk = $title->getPrefixedDBkey();
4032 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4033 $this->mOutput
->addLink( $title, $s->page_id
);
4035 if ( $threshold > 0 ) {
4036 $size = $s->page_len
;
4037 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4038 $colours[$pdbk] = 1;
4040 $colours[$pdbk] = 2;
4043 $colours[$pdbk] = 1;
4047 wfProfileOut( $fname.'-check' );
4049 # Do a second query for different language variants of links and categories
4050 if($wgContLang->hasVariants()){
4051 $linkBatch = new LinkBatch();
4052 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4053 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4054 $varCategories = array(); // category replacements oldDBkey => newDBkey
4056 $categories = $this->mOutput
->getCategoryLinks();
4058 // Add variants of links to link batch
4059 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4060 $title = $this->mLinkHolders
['titles'][$key];
4061 if ( is_null( $title ) )
4064 $pdbk = $title->getPrefixedDBkey();
4065 $titleText = $title->getText();
4067 // generate all variants of the link title text
4068 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4070 // if link was not found (in first query), add all variants to query
4071 if ( !isset($colours[$pdbk]) ){
4072 foreach($allTextVariants as $textVariant){
4073 if($textVariant != $titleText){
4074 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4075 if(is_null($variantTitle)) continue;
4076 $linkBatch->addObj( $variantTitle );
4077 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4083 // process categories, check if a category exists in some variant
4084 foreach( $categories as $category){
4085 $variants = $wgContLang->convertLinkToAllVariants($category);
4086 foreach($variants as $variant){
4087 if($variant != $category){
4088 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4089 if(is_null($variantTitle)) continue;
4090 $linkBatch->addObj( $variantTitle );
4091 $categoryMap[$variant] = $category;
4097 if(!$linkBatch->isEmpty()){
4099 $titleClause = $linkBatch->constructSet('page', $dbr);
4101 $variantQuery = "SELECT page_id, page_namespace, page_title";
4102 if ( $threshold > 0 ) {
4103 $variantQuery .= ', page_len, page_is_redirect';
4106 $variantQuery .= " FROM $page WHERE $titleClause";
4107 if ( $options & RLH_FOR_UPDATE
) {
4108 $variantQuery .= ' FOR UPDATE';
4111 $varRes = $dbr->query( $variantQuery, $fname );
4113 // for each found variants, figure out link holders and replace
4114 while ( $s = $dbr->fetchObject($varRes) ) {
4116 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4117 $varPdbk = $variantTitle->getPrefixedDBkey();
4118 $vardbk = $variantTitle->getDBkey();
4120 $holderKeys = array();
4121 if(isset($variantMap[$varPdbk])){
4122 $holderKeys = $variantMap[$varPdbk];
4123 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4124 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4127 // loop over link holders
4128 foreach($holderKeys as $key){
4129 $title = $this->mLinkHolders
['titles'][$key];
4130 if ( is_null( $title ) ) continue;
4132 $pdbk = $title->getPrefixedDBkey();
4134 if(!isset($colours[$pdbk])){
4135 // found link in some of the variants, replace the link holder data
4136 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4137 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4139 // set pdbk and colour
4140 $pdbks[$key] = $varPdbk;
4141 if ( $threshold > 0 ) {
4142 $size = $s->page_len
;
4143 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4144 $colours[$varPdbk] = 1;
4146 $colours[$varPdbk] = 2;
4150 $colours[$varPdbk] = 1;
4155 // check if the object is a variant of a category
4156 if(isset($categoryMap[$vardbk])){
4157 $oldkey = $categoryMap[$vardbk];
4158 if($oldkey != $vardbk)
4159 $varCategories[$oldkey]=$vardbk;
4163 // rebuild the categories in original order (if there are replacements)
4164 if(count($varCategories)>0){
4166 $originalCats = $this->mOutput
->getCategories();
4167 foreach($originalCats as $cat => $sortkey){
4168 // make the replacement
4169 if( array_key_exists($cat,$varCategories) )
4170 $newCats[$varCategories[$cat]] = $sortkey;
4171 else $newCats[$cat] = $sortkey;
4173 $this->mOutput
->setCategoryLinks($newCats);
4178 # Construct search and replace arrays
4179 wfProfileIn( $fname.'-construct' );
4180 $replacePairs = array();
4181 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4182 $pdbk = $pdbks[$key];
4183 $searchkey = "<!--LINK $key-->";
4184 $title = $this->mLinkHolders
['titles'][$key];
4185 if ( empty( $colours[$pdbk] ) ) {
4186 $linkCache->addBadLinkObj( $title );
4187 $colours[$pdbk] = 0;
4188 $this->mOutput
->addLink( $title, 0 );
4189 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4190 $this->mLinkHolders
['texts'][$key],
4191 $this->mLinkHolders
['queries'][$key] );
4192 } elseif ( $colours[$pdbk] == 1 ) {
4193 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4194 $this->mLinkHolders
['texts'][$key],
4195 $this->mLinkHolders
['queries'][$key] );
4196 } elseif ( $colours[$pdbk] == 2 ) {
4197 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4198 $this->mLinkHolders
['texts'][$key],
4199 $this->mLinkHolders
['queries'][$key] );
4202 $replacer = new HashtableReplacer( $replacePairs, 1 );
4203 wfProfileOut( $fname.'-construct' );
4206 wfProfileIn( $fname.'-replace' );
4207 $text = preg_replace_callback(
4208 '/(<!--LINK .*?-->)/',
4212 wfProfileOut( $fname.'-replace' );
4215 # Now process interwiki link holders
4216 # This is quite a bit simpler than internal links
4217 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4218 wfProfileIn( $fname.'-interwiki' );
4219 # Make interwiki link HTML
4220 $replacePairs = array();
4221 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4222 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4223 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4225 $replacer = new HashtableReplacer( $replacePairs, 1 );
4227 $text = preg_replace_callback(
4228 '/<!--IWLINK (.*?)-->/',
4231 wfProfileOut( $fname.'-interwiki' );
4234 wfProfileOut( $fname );
4239 * Replace <!--LINK--> link placeholders with plain text of links
4240 * (not HTML-formatted).
4241 * @param string $text
4244 function replaceLinkHoldersText( $text ) {
4245 $fname = 'Parser::replaceLinkHoldersText';
4246 wfProfileIn( $fname );
4248 $text = preg_replace_callback(
4249 '/<!--(LINK|IWLINK) (.*?)-->/',
4250 array( &$this, 'replaceLinkHoldersTextCallback' ),
4253 wfProfileOut( $fname );
4258 * @param array $matches
4262 function replaceLinkHoldersTextCallback( $matches ) {
4263 $type = $matches[1];
4265 if( $type == 'LINK' ) {
4266 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4267 return $this->mLinkHolders
['texts'][$key];
4269 } elseif( $type == 'IWLINK' ) {
4270 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4271 return $this->mInterwikiLinkHolders
['texts'][$key];
4278 * Tag hook handler for 'pre'.
4280 function renderPreTag( $text, $attribs ) {
4281 // Backwards-compatibility hack
4282 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4284 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4285 return wfOpenElement( 'pre', $attribs ) .
4286 Xml
::escapeTagsOnly( $content ) .
4291 * Renders an image gallery from a text with one line per image.
4292 * text labels may be given by using |-style alternative text. E.g.
4293 * Image:one.jpg|The number "1"
4294 * Image:tree.jpg|A tree
4295 * given as text will return the HTML of a gallery with two images,
4296 * labeled 'The number "1"' and
4299 function renderImageGallery( $text, $params ) {
4300 $ig = new ImageGallery();
4301 $ig->setShowBytes( false );
4302 $ig->setShowFilename( false );
4304 $ig->useSkin( $this->mOptions
->getSkin() );
4306 if( isset( $params['caption'] ) ) {
4307 $caption = $params['caption'];
4308 $caption = htmlspecialchars( $caption );
4309 $caption = $this->replaceInternalLinks( $caption );
4310 $ig->setCaptionHtml( $caption );
4313 $lines = explode( "\n", $text );
4314 foreach ( $lines as $line ) {
4315 # match lines like these:
4316 # Image:someimage.jpg|This is some image
4318 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4320 if ( count( $matches ) == 0 ) {
4323 $tp = Title
::newFromText( $matches[1] );
4325 if( is_null( $nt ) ) {
4326 # Bogus title. Ignore these so we don't bomb out later.
4329 if ( isset( $matches[3] ) ) {
4330 $label = $matches[3];
4335 $pout = $this->parse( $label,
4338 false, // Strip whitespace...?
4339 false // Don't clear state!
4341 $html = $pout->getText();
4343 $ig->add( new Image( $nt ), $html );
4345 # Only add real images (bug #5586)
4346 if ( $nt->getNamespace() == NS_IMAGE
) {
4347 $this->mOutput
->addImage( $nt->getDBkey() );
4350 return $ig->toHTML();
4354 * Parse image options text and use it to make an image
4356 function makeImage( $nt, $options ) {
4357 global $wgUseImageResize, $wgDjvuRenderer;
4361 # Check if the options text is of the form "options|alt text"
4363 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4364 # * left no resizing, just left align. label is used for alt= only
4365 # * right same, but right aligned
4366 # * none same, but not aligned
4367 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4368 # * center center the image
4369 # * framed Keep original image size, no magnify-button.
4371 $part = explode( '|', $options);
4373 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4374 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4375 $mwLeft =& MagicWord
::get( 'img_left' );
4376 $mwRight =& MagicWord
::get( 'img_right' );
4377 $mwNone =& MagicWord
::get( 'img_none' );
4378 $mwWidth =& MagicWord
::get( 'img_width' );
4379 $mwCenter =& MagicWord
::get( 'img_center' );
4380 $mwFramed =& MagicWord
::get( 'img_framed' );
4381 $mwPage =& MagicWord
::get( 'img_page' );
4384 $width = $height = $framed = $thumb = false;
4386 $manual_thumb = '' ;
4388 foreach( $part as $val ) {
4389 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4391 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4392 # use manually specified thumbnail
4394 $manual_thumb = $match;
4395 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4396 # remember to set an alignment, don't render immediately
4398 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4399 # remember to set an alignment, don't render immediately
4401 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4402 # remember to set an alignment, don't render immediately
4404 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4405 # remember to set an alignment, don't render immediately
4407 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4408 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4409 # Select a page in a multipage document
4411 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4412 wfDebug( "img_width match: $match\n" );
4413 # $match is the image width in pixels
4415 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4416 $width = intval( $m[1] );
4417 $height = intval( $m[2] );
4419 $width = intval($match);
4421 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4427 # Strip bad stuff out of the alt text
4428 $alt = $this->replaceLinkHoldersText( $caption );
4430 # make sure there are no placeholders in thumbnail attributes
4431 # that are later expanded to html- so expand them now and
4433 $alt = $this->mStripState
->unstripBoth( $alt );
4434 $alt = Sanitizer
::stripAllTags( $alt );
4436 # Linker does the rest
4437 $sk =& $this->mOptions
->getSkin();
4438 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4442 * Set a flag in the output object indicating that the content is dynamic and
4443 * shouldn't be cached.
4445 function disableCache() {
4446 wfDebug( "Parser output marked as uncacheable.\n" );
4447 $this->mOutput
->mCacheTime
= -1;
4451 * Callback from the Sanitizer for expanding items found in HTML attribute
4452 * values, so they can be safely tested and escaped.
4453 * @param string $text
4454 * @param array $args
4458 function attributeStripCallback( &$text, $args ) {
4459 $text = $this->replaceVariables( $text, $args );
4460 $text = $this->mStripState
->unstripBoth( $text );
4469 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4470 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4471 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4477 function getTags() { return array_keys( $this->mTagHooks
); }
4482 * Break wikitext input into sections, and either pull or replace
4483 * some particular section's text.
4485 * External callers should use the getSection and replaceSection methods.
4487 * @param $text Page wikitext
4488 * @param $section Numbered section. 0 pulls the text before the first
4489 * heading; other numbers will pull the given section
4490 * along with its lower-level subsections.
4491 * @param $mode One of "get" or "replace"
4492 * @param $newtext Replacement text for section data.
4493 * @return string for "get", the extracted section text.
4494 * for "replace", the whole page with the section replaced.
4496 private function extractSections( $text, $section, $mode, $newtext='' ) {
4497 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4498 # comments to be stripped as well)
4499 $stripState = new StripState
;
4501 $oldOutputType = $this->mOutputType
;
4502 $oldOptions = $this->mOptions
;
4503 $this->mOptions
= new ParserOptions();
4504 $this->setOutputType( OT_WIKI
);
4506 $striptext = $this->strip( $text, $stripState, true );
4508 $this->setOutputType( $oldOutputType );
4509 $this->mOptions
= $oldOptions;
4511 # now that we can be sure that no pseudo-sections are in the source,
4512 # split it up by section
4513 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4514 $comment = "(?:$uniq-!--.*?QINU)";
4519 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4521 (=+) # Should this be limited to 6?
4522 .+? # Section title...
4523 \\2 # Ending = count must match start
4530 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4537 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4538 (=+) # Should this be limited to 6?
4539 .+? # Section title...
4540 \\2 # Ending = count must match start
4541 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4550 PREG_SPLIT_DELIM_CAPTURE
);
4552 if( $mode == "get" ) {
4553 if( $section == 0 ) {
4554 // "Section 0" returns the content before any other section.
4559 } elseif( $mode == "replace" ) {
4560 if( $section == 0 ) {
4561 $rv = $newtext . "\n\n";
4570 for( $index = 1; $index < count( $secs ); ) {
4571 $headerLine = $secs[$index++
];
4572 if( $secs[$index] ) {
4574 $headerLevel = strlen( $secs[$index++
] );
4578 $headerLevel = intval( $secs[$index++
] );
4580 $content = $secs[$index++
];
4583 if( $mode == "get" ) {
4584 if( $count == $section ) {
4585 $rv = $headerLine . $content;
4586 $sectionLevel = $headerLevel;
4587 } elseif( $count > $section ) {
4588 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4589 $rv .= $headerLine . $content;
4591 // Broke out to a higher-level section
4595 } elseif( $mode == "replace" ) {
4596 if( $count < $section ) {
4597 $rv .= $headerLine . $content;
4598 } elseif( $count == $section ) {
4599 $rv .= $newtext . "\n\n";
4600 $sectionLevel = $headerLevel;
4601 } elseif( $count > $section ) {
4602 if( $headerLevel <= $sectionLevel ) {
4603 // Passed the section's sub-parts.
4607 $rv .= $headerLine . $content;
4612 # reinsert stripped tags
4613 $rv = trim( $stripState->unstripBoth( $rv ) );
4618 * This function returns the text of a section, specified by a number ($section).
4619 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4620 * the first section before any such heading (section 0).
4622 * If a section contains subsections, these are also returned.
4624 * @param $text String: text to look in
4625 * @param $section Integer: section number
4626 * @return string text of the requested section
4628 function getSection( $text, $section ) {
4629 return $this->extractSections( $text, $section, "get" );
4632 function replaceSection( $oldtext, $section, $text ) {
4633 return $this->extractSections( $oldtext, $section, "replace", $text );
4637 * Get the timestamp associated with the current revision, adjusted for
4638 * the default server-local timestamp
4640 function getRevisionTimestamp() {
4641 if ( is_null( $this->mRevisionTimestamp
) ) {
4642 wfProfileIn( __METHOD__
);
4644 $dbr =& wfGetDB( DB_SLAVE
);
4645 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4646 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4648 // Normalize timestamp to internal MW format for timezone processing.
4649 // This has the added side-effect of replacing a null value with
4650 // the current time, which gives us more sensible behavior for
4652 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4654 // The cryptic '' timezone parameter tells to use the site-default
4655 // timezone offset instead of the user settings.
4657 // Since this value will be saved into the parser cache, served
4658 // to other users, and potentially even used inside links and such,
4659 // it needs to be consistent for all visitors.
4660 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4662 wfProfileOut( __METHOD__
);
4664 return $this->mRevisionTimestamp
;
4668 * Mutator for $mDefaultSort
4670 * @param $sort New value
4672 public function setDefaultSort( $sort ) {
4673 $this->mDefaultSort
= $sort;
4677 * Accessor for $mDefaultSort
4678 * Will use the title/prefixed title if none is set
4682 public function getDefaultSort() {
4683 if( $this->mDefaultSort
!== false ) {
4684 return $this->mDefaultSort
;
4686 return $this->mTitle
->getNamespace() == NS_CATEGORY
4687 ?
$this->mTitle
->getText()
4688 : $this->mTitle
->getPrefixedText();
4696 * @package MediaWiki
4700 var $mText, # The output text
4701 $mLanguageLinks, # List of the full text of language links, in the order they appear
4702 $mCategories, # Map of category names to sort keys
4703 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4704 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4705 $mVersion, # Compatibility check
4706 $mTitleText, # title text of the chosen language variant
4707 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4708 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4709 $mImages, # DB keys of the images used, in the array key only
4710 $mExternalLinks, # External link URLs, in the key only
4711 $mHTMLtitle, # Display HTML title
4712 $mSubtitle, # Additional subtitle
4713 $mNewSection, # Show a new section link?
4714 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4716 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4717 $containsOldMagic = false, $titletext = '' )
4719 $this->mText
= $text;
4720 $this->mLanguageLinks
= $languageLinks;
4721 $this->mCategories
= $categoryLinks;
4722 $this->mContainsOldMagic
= $containsOldMagic;
4723 $this->mCacheTime
= '';
4724 $this->mVersion
= MW_PARSER_VERSION
;
4725 $this->mTitleText
= $titletext;
4726 $this->mLinks
= array();
4727 $this->mTemplates
= array();
4728 $this->mImages
= array();
4729 $this->mExternalLinks
= array();
4730 $this->mHTMLtitle
= "" ;
4731 $this->mSubtitle
= "" ;
4732 $this->mNewSection
= false;
4733 $this->mNoGallery
= false;
4736 function getText() { return $this->mText
; }
4737 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4738 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4739 function &getCategories() { return $this->mCategories
; }
4740 function getCacheTime() { return $this->mCacheTime
; }
4741 function getTitleText() { return $this->mTitleText
; }
4742 function &getLinks() { return $this->mLinks
; }
4743 function &getTemplates() { return $this->mTemplates
; }
4744 function &getImages() { return $this->mImages
; }
4745 function &getExternalLinks() { return $this->mExternalLinks
; }
4746 function getNoGallery() { return $this->mNoGallery
; }
4747 function getSubtitle() { return $this->mSubtitle
; }
4749 function containsOldMagic() { return $this->mContainsOldMagic
; }
4750 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4751 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4752 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4753 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4754 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4755 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4756 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4758 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4759 function addImage( $name ) { $this->mImages
[$name] = 1; }
4760 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4761 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4763 function setNewSection( $value ) {
4764 $this->mNewSection
= (bool)$value;
4766 function getNewSection() {
4767 return (bool)$this->mNewSection
;
4770 function addLink( $title, $id = null ) {
4771 $ns = $title->getNamespace();
4772 $dbk = $title->getDBkey();
4773 if ( !isset( $this->mLinks
[$ns] ) ) {
4774 $this->mLinks
[$ns] = array();
4776 if ( is_null( $id ) ) {
4777 $id = $title->getArticleID();
4779 $this->mLinks
[$ns][$dbk] = $id;
4782 function addTemplate( $title, $id ) {
4783 $ns = $title->getNamespace();
4784 $dbk = $title->getDBkey();
4785 if ( !isset( $this->mTemplates
[$ns] ) ) {
4786 $this->mTemplates
[$ns] = array();
4788 $this->mTemplates
[$ns][$dbk] = $id;
4792 * Return true if this cached output object predates the global or
4793 * per-article cache invalidation timestamps, or if it comes from
4794 * an incompatible older version.
4796 * @param string $touched the affected article's last touched timestamp
4800 function expired( $touched ) {
4801 global $wgCacheEpoch;
4802 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4803 $this->getCacheTime() < $touched ||
4804 $this->getCacheTime() <= $wgCacheEpoch ||
4805 !isset( $this->mVersion
) ||
4806 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4811 * Set options of the Parser
4813 * @package MediaWiki
4817 # All variables are supposed to be private in theory, although in practise this is not the case.
4818 var $mUseTeX; # Use texvc to expand <math> tags
4819 var $mUseDynamicDates; # Use DateFormatter to format dates
4820 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4821 var $mAllowExternalImages; # Allow external images inline
4822 var $mAllowExternalImagesFrom; # If not, any exception?
4823 var $mSkin; # Reference to the preferred skin
4824 var $mDateFormat; # Date format index
4825 var $mEditSection; # Create "edit section" links
4826 var $mNumberHeadings; # Automatically number headings
4827 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4828 var $mTidy; # Ask for tidy cleanup
4829 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4830 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4831 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4833 var $mUser; # Stored user object, just used to initialise the skin
4835 function getUseTeX() { return $this->mUseTeX
; }
4836 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4837 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4838 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4839 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4840 function getEditSection() { return $this->mEditSection
; }
4841 function getNumberHeadings() { return $this->mNumberHeadings
; }
4842 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4843 function getTidy() { return $this->mTidy
; }
4844 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4845 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4846 function getRemoveComments() { return $this->mRemoveComments
; }
4848 function &getSkin() {
4849 if ( !isset( $this->mSkin
) ) {
4850 $this->mSkin
= $this->mUser
->getSkin();
4852 return $this->mSkin
;
4855 function getDateFormat() {
4856 if ( !isset( $this->mDateFormat
) ) {
4857 $this->mDateFormat
= $this->mUser
->getDatePreference();
4859 return $this->mDateFormat
;
4862 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4863 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4864 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4865 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4866 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4867 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4868 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4869 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4870 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4871 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4872 function setSkin( $x ) { $this->mSkin
= $x; }
4873 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4874 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4875 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4877 function ParserOptions( $user = null ) {
4878 $this->initialiseFromUser( $user );
4882 * Get parser options
4885 static function newFromUser( $user ) {
4886 return new ParserOptions( $user );
4889 /** Get user options */
4890 function initialiseFromUser( $userInput ) {
4891 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4892 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4893 $fname = 'ParserOptions::initialiseFromUser';
4894 wfProfileIn( $fname );
4895 if ( !$userInput ) {
4897 if ( isset( $wgUser ) ) {
4903 $user =& $userInput;
4906 $this->mUser
= $user;
4908 $this->mUseTeX
= $wgUseTeX;
4909 $this->mUseDynamicDates
= $wgUseDynamicDates;
4910 $this->mInterwikiMagic
= $wgInterwikiMagic;
4911 $this->mAllowExternalImages
= $wgAllowExternalImages;
4912 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4913 $this->mSkin
= null; # Deferred
4914 $this->mDateFormat
= null; # Deferred
4915 $this->mEditSection
= true;
4916 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4917 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4918 $this->mTidy
= false;
4919 $this->mInterfaceMessage
= false;
4920 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4921 $this->mRemoveComments
= true;
4922 wfProfileOut( $fname );
4926 class OnlyIncludeReplacer
{
4929 function replace( $matches ) {
4930 if ( substr( $matches[1], -1 ) == "\n" ) {
4931 $this->output
.= substr( $matches[1], 0, -1 );
4933 $this->output
.= $matches[1];
4939 var $general, $nowiki;
4941 function __construct() {
4942 $this->general
= new ReplacementArray
;
4943 $this->nowiki
= new ReplacementArray
;
4946 function unstripGeneral( $text ) {
4947 wfProfileIn( __METHOD__
);
4948 $text = $this->general
->replace( $text );
4949 wfProfileOut( __METHOD__
);
4953 function unstripNoWiki( $text ) {
4954 wfProfileIn( __METHOD__
);
4955 $text = $this->nowiki
->replace( $text );
4956 wfProfileOut( __METHOD__
);
4960 function unstripBoth( $text ) {
4961 wfProfileIn( __METHOD__
);
4962 $text = $this->general
->replace( $text );
4963 $text = $this->nowiki
->replace( $text );
4964 wfProfileOut( __METHOD__
);