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.
266 * @param string $text Text we want to parse
267 * @param Title &$title A title object
268 * @param array $options
269 * @param boolean $linestart
270 * @param boolean $clearState
271 * @param int $revid number to pass in {{REVISIONID}}
272 * @return ParserOutput a ParserOutput
274 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
276 * First pass--just handle <nowiki> sections, pass the rest off
277 * to internalParse() which does all the real work.
280 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
281 $fname = 'Parser::parse-' . wfGetCaller();
282 wfProfileIn( __METHOD__
);
283 wfProfileIn( $fname );
289 $this->mOptions
= $options;
290 $this->mTitle
=& $title;
291 $oldRevisionId = $this->mRevisionId
;
292 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
293 if( $revid !== null ) {
294 $this->mRevisionId
= $revid;
295 $this->mRevisionTimestamp
= null;
297 $this->setOutputType( OT_HTML
);
298 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
299 $text = $this->strip( $text, $this->mStripState
);
300 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
301 $text = $this->internalParse( $text );
302 $text = $this->mStripState
->unstripGeneral( $text );
304 # Clean up special characters, only run once, next-to-last before doBlockLevels
306 # french spaces, last one Guillemet-left
307 # only if there is something before the space
308 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
309 # french spaces, Guillemet-right
310 '/(\\302\\253) /' => '\\1 ',
312 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
315 $text = $this->doBlockLevels( $text, $linestart );
317 $this->replaceLinkHolders( $text );
319 # the position of the parserConvert() call should not be changed. it
320 # assumes that the links are all replaced and the only thing left
321 # is the <nowiki> mark.
322 # Side-effects: this calls $this->mOutput->setTitleText()
323 $text = $wgContLang->parserConvert( $text, $this );
325 $text = $this->mStripState
->unstripNoWiki( $text );
327 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
329 $text = Sanitizer
::normalizeCharReferences( $text );
331 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
332 $text = Parser
::tidy($text);
334 # attempt to sanitize at least some nesting problems
335 # (bug #2702 and quite a few others)
337 # ''Something [http://www.cool.com cool''] -->
338 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
339 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
340 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
341 # fix up an anchor inside another anchor, only
342 # at least for a single single nested link (bug 3695)
343 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
344 '\\1\\2</a>\\3</a>\\1\\4</a>',
345 # fix div inside inline elements- doBlockLevels won't wrap a line which
346 # contains a div, so fix it up here; replace
347 # div with escaped text
348 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
349 '\\1\\3<div\\5>\\6</div>\\8\\9',
350 # remove empty italic or bold tag pairs, some
351 # introduced by rules above
352 '/<([bi])><\/\\1>/' => '',
355 $text = preg_replace(
356 array_keys( $tidyregs ),
357 array_values( $tidyregs ),
361 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
363 # Information on include size limits, for the benefit of users who try to skirt them
364 if ( max( $this->mIncludeSizes
) > 1000 ) {
365 $max = $this->mOptions
->getMaxIncludeSize();
367 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
368 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
369 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
370 "Maximum: $max bytes\n" .
373 $this->mOutput
->setText( $text );
374 $this->mRevisionId
= $oldRevisionId;
375 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
376 wfProfileOut( $fname );
377 wfProfileOut( __METHOD__
);
379 return $this->mOutput
;
383 * Recursive parser entry point that can be called from an extension tag
386 function recursiveTagParse( $text ) {
387 wfProfileIn( __METHOD__
);
388 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
389 $text = $this->strip( $text, $this->mStripState
);
390 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
391 $text = $this->internalParse( $text );
392 wfProfileOut( __METHOD__
);
397 * Expand templates and variables in the text, producing valid, static wikitext.
398 * Also removes comments.
400 function preprocess( $text, $title, $options ) {
401 wfProfileIn( __METHOD__
);
403 $this->setOutputType( OT_PREPROCESS
);
404 $this->mOptions
= $options;
405 $this->mTitle
= $title;
406 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
407 $text = $this->strip( $text, $this->mStripState
);
408 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
409 if ( $this->mOptions
->getRemoveComments() ) {
410 $text = Sanitizer
::removeHTMLcomments( $text );
412 $text = $this->replaceVariables( $text );
413 $text = $this->mStripState
->unstripBoth( $text );
414 wfProfileOut( __METHOD__
);
419 * Get a random string
424 function getRandomString() {
425 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
428 function &getTitle() { return $this->mTitle
; }
429 function getOptions() { return $this->mOptions
; }
431 function getFunctionLang() {
432 global $wgLang, $wgContLang;
433 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
437 * Replaces all occurrences of HTML-style comments and the given tags
438 * in the text with a random marker and returns teh next text. The output
439 * parameter $matches will be an associative array filled with data in
441 * 'UNIQ-xxxxx' => array(
444 * array( 'param' => 'x' ),
445 * '<element param="x">tag content</element>' ) )
447 * @param $elements list of element names. Comments are always extracted.
448 * @param $text Source text string.
449 * @param $uniq_prefix
454 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
459 $taglist = implode( '|', $elements );
460 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
462 while ( '' != $text ) {
463 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
465 if( count( $p ) < 5 ) {
468 if( count( $p ) > 5 ) {
482 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
483 $stripped .= $marker;
485 if ( $close === '/>' ) {
486 // Empty element tag, <tag />
491 if( $element == '!--' ) {
494 $end = "/(<\\/$element\\s*>)/i";
496 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
498 if( count( $q ) < 3 ) {
499 # No end tag -- let it run out to the end of the text.
508 $matches[$marker] = array( $element,
510 Sanitizer
::decodeTagAttributes( $attributes ),
511 "<$element$attributes$close$content$tail" );
517 * Strips and renders nowiki, pre, math, hiero
518 * If $render is set, performs necessary rendering operations on plugins
519 * Returns the text, and fills an array with data needed in unstrip()
521 * @param StripState $state
523 * @param bool $stripcomments when set, HTML comments <!-- like this -->
524 * will be stripped in addition to other tags. This is important
525 * for section editing, where these comments cause confusion when
526 * counting the sections in the wikisource
528 * @param array dontstrip contains tags which should not be stripped;
529 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
533 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
535 wfProfileIn( __METHOD__
);
536 $render = ($this->mOutputType
== OT_HTML
);
538 $uniq_prefix = $this->mUniqPrefix
;
539 $commentState = new ReplacementArray
;
540 $nowikiItems = array();
541 $generalItems = array();
543 $elements = array_merge(
544 array( 'nowiki', 'gallery' ),
545 array_keys( $this->mTagHooks
) );
548 $elements[] = 'html';
550 if( $this->mOptions
->getUseTeX() ) {
551 $elements[] = 'math';
554 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
555 foreach ( $elements AS $k => $v ) {
556 if ( !in_array ( $v , $dontstrip ) ) continue;
557 unset ( $elements[$k] );
561 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
563 foreach( $matches as $marker => $data ) {
564 list( $element, $content, $params, $tag ) = $data;
566 $tagName = strtolower( $element );
567 wfProfileIn( __METHOD__
."-render-$tagName" );
571 if( substr( $tag, -3 ) == '-->' ) {
574 // Unclosed comment in input.
575 // Close it so later stripping can remove it
584 // Shouldn't happen otherwise. :)
586 $output = Xml
::escapeTagsOnly( $content );
589 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
592 $output = $this->renderImageGallery( $content, $params );
595 if( isset( $this->mTagHooks
[$tagName] ) ) {
596 $output = call_user_func_array( $this->mTagHooks
[$tagName],
597 array( $content, $params, $this ) );
599 throw new MWException( "Invalid call hook $element" );
602 wfProfileOut( __METHOD__
."-render-$tagName" );
604 // Just stripping tags; keep the source
608 // Unstrip the output, to support recursive strip() calls
609 $output = $state->unstripBoth( $output );
611 if( !$stripcomments && $element == '!--' ) {
612 $commentState->setPair( $marker, $output );
613 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
614 $nowikiItems[$marker] = $output;
616 $generalItems[$marker] = $output;
619 # Add the new items to the state
620 # We do this after the loop instead of during it to avoid slowing
621 # down the recursive unstrip
622 $state->nowiki
->mergeArray( $nowikiItems );
623 $state->general
->mergeArray( $generalItems );
625 # Unstrip comments unless explicitly told otherwise.
626 # (The comments are always stripped prior to this point, so as to
627 # not invoke any extension tags / parser hooks contained within
629 if ( !$stripcomments ) {
630 // Put them all back and forget them
631 $text = $commentState->replace( $text );
634 wfProfileOut( __METHOD__
);
639 * Restores pre, math, and other extensions removed by strip()
641 * always call unstripNoWiki() after this one
643 * @deprecated use $this->mStripState->unstrip()
645 function unstrip( $text, $state ) {
646 return $state->unstripGeneral( $text );
650 * Always call this after unstrip() to preserve the order
653 * @deprecated use $this->mStripState->unstrip()
655 function unstripNoWiki( $text, $state ) {
656 return $state->unstripNoWiki( $text );
660 * @deprecated use $this->mStripState->unstripBoth()
662 function unstripForHTML( $text ) {
663 return $this->mStripState
->unstripBoth( $text );
667 * Add an item to the strip state
668 * Returns the unique tag which must be inserted into the stripped text
669 * The tag will be replaced with the original text in unstrip()
673 function insertStripItem( $text, &$state ) {
674 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
675 $state->general
->setPair( $rnd, $text );
680 * Interface with html tidy, used if $wgUseTidy = true.
681 * If tidy isn't able to correct the markup, the original will be
682 * returned in all its glory with a warning comment appended.
684 * Either the external tidy program or the in-process tidy extension
685 * will be used depending on availability. Override the default
686 * $wgTidyInternal setting to disable the internal if it's not working.
688 * @param string $text Hideous HTML input
689 * @return string Corrected HTML output
693 function tidy( $text ) {
694 global $wgTidyInternal;
695 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
696 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
697 '<head><title>test</title></head><body>'.$text.'</body></html>';
698 if( $wgTidyInternal ) {
699 $correctedtext = Parser
::internalTidy( $wrappedtext );
701 $correctedtext = Parser
::externalTidy( $wrappedtext );
703 if( is_null( $correctedtext ) ) {
704 wfDebug( "Tidy error detected!\n" );
705 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
707 return $correctedtext;
711 * Spawn an external HTML tidy process and get corrected markup back from it.
716 function externalTidy( $text ) {
717 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
718 $fname = 'Parser::externalTidy';
719 wfProfileIn( $fname );
724 $descriptorspec = array(
725 0 => array('pipe', 'r'),
726 1 => array('pipe', 'w'),
727 2 => array('file', '/dev/null', 'a')
730 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
731 if (is_resource($process)) {
732 // Theoretically, this style of communication could cause a deadlock
733 // here. If the stdout buffer fills up, then writes to stdin could
734 // block. This doesn't appear to happen with tidy, because tidy only
735 // writes to stdout after it's finished reading from stdin. Search
736 // for tidyParseStdin and tidySaveStdout in console/tidy.c
737 fwrite($pipes[0], $text);
739 while (!feof($pipes[1])) {
740 $cleansource .= fgets($pipes[1], 1024);
743 proc_close($process);
746 wfProfileOut( $fname );
748 if( $cleansource == '' && $text != '') {
749 // Some kind of error happened, so we couldn't get the corrected text.
750 // Just give up; we'll use the source text and append a warning.
758 * Use the HTML tidy PECL extension to use the tidy library in-process,
759 * saving the overhead of spawning a new process. Currently written to
760 * the PHP 4.3.x version of the extension, may not work on PHP 5.
762 * 'pear install tidy' should be able to compile the extension module.
767 function internalTidy( $text ) {
769 $fname = 'Parser::internalTidy';
770 wfProfileIn( $fname );
772 tidy_load_config( $wgTidyConf );
773 tidy_set_encoding( 'utf8' );
774 tidy_parse_string( $text );
776 if( tidy_get_status() == 2 ) {
777 // 2 is magic number for fatal error
778 // http://www.php.net/manual/en/function.tidy-get-status.php
781 $cleansource = tidy_get_output();
783 wfProfileOut( $fname );
788 * parse the wiki syntax used to render tables
792 function doTableStuff ( $text ) {
793 $fname = 'Parser::doTableStuff';
794 wfProfileIn( $fname );
796 $lines = explode ( "\n" , $text );
797 $td_history = array (); // Is currently a td tag open?
798 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
799 $tr_history = array (); // Is currently a tr tag open?
800 $tr_attributes = array (); // history of tr attributes
801 $has_opened_tr = array(); // Did this table open a <tr> element?
802 $indent_level = 0; // indent level of the table
803 foreach ( $lines as $key => $line )
805 $line = trim ( $line );
807 if( $line == '' ) { // empty line, go to next line
810 $first_character = $line{0};
813 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
814 // First check if we are starting a new table
815 $indent_level = strlen( $matches[1] );
817 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
818 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
820 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
821 array_push ( $td_history , false );
822 array_push ( $last_tag_history , '' );
823 array_push ( $tr_history , false );
824 array_push ( $tr_attributes , '' );
825 array_push ( $has_opened_tr , false );
826 } else if ( count ( $td_history ) == 0 ) {
827 // Don't do any of the following
829 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
830 // We are ending a table
831 $line = '</table>' . substr ( $line , 2 );
832 $last_tag = array_pop ( $last_tag_history );
834 if ( !array_pop ( $has_opened_tr ) ) {
835 $line = "<tr><td></td></tr>{$line}";
838 if ( array_pop ( $tr_history ) ) {
839 $line = "</tr>{$line}";
842 if ( array_pop ( $td_history ) ) {
843 $line = "</{$last_tag}>{$line}";
845 array_pop ( $tr_attributes );
846 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
847 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
848 // Now we have a table row
849 $line = preg_replace( '#^\|-+#', '', $line );
851 // Whats after the tag is now only attributes
852 $attributes = $this->mStripState
->unstripBoth( $line );
853 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
854 array_pop ( $tr_attributes );
855 array_push ( $tr_attributes , $attributes );
858 $last_tag = array_pop ( $last_tag_history );
859 array_pop ( $has_opened_tr );
860 array_push ( $has_opened_tr , true );
862 if ( array_pop ( $tr_history ) ) {
866 if ( array_pop ( $td_history ) ) {
867 $line = "</{$last_tag}>{$line}";
870 $lines[$key] = $line;
871 array_push ( $tr_history , false );
872 array_push ( $td_history , false );
873 array_push ( $last_tag_history , '' );
875 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
876 // This might be cell elements, td, th or captions
877 if ( substr ( $line , 0 , 2 ) == '|+' ) {
878 $first_character = '+';
879 $line = substr ( $line , 1 );
882 $line = substr ( $line , 1 );
884 if ( $first_character == '!' ) {
885 $line = str_replace ( '!!' , '||' , $line );
888 // Split up multiple cells on the same line.
889 // FIXME : This can result in improper nesting of tags processed
890 // by earlier parser steps, but should avoid splitting up eg
891 // attribute values containing literal "||".
892 $cells = StringUtils
::explodeMarkup( '||' , $line );
896 // Loop through each table cell
897 foreach ( $cells as $cell )
900 if ( $first_character != '+' )
902 $tr_after = array_pop ( $tr_attributes );
903 if ( !array_pop ( $tr_history ) ) {
904 $previous = "<tr{$tr_after}>\n";
906 array_push ( $tr_history , true );
907 array_push ( $tr_attributes , '' );
908 array_pop ( $has_opened_tr );
909 array_push ( $has_opened_tr , true );
912 $last_tag = array_pop ( $last_tag_history );
914 if ( array_pop ( $td_history ) ) {
915 $previous = "</{$last_tag}>{$previous}";
918 if ( $first_character == '|' ) {
920 } else if ( $first_character == '!' ) {
922 } else if ( $first_character == '+' ) {
923 $last_tag = 'caption';
928 array_push ( $last_tag_history , $last_tag );
930 // A cell could contain both parameters and data
931 $cell_data = explode ( '|' , $cell , 2 );
933 // Bug 553: Note that a '|' inside an invalid link should not
934 // be mistaken as delimiting cell parameters
935 if ( strpos( $cell_data[0], '[[' ) !== false ) {
936 $cell = "{$previous}<{$last_tag}>{$cell}";
937 } else if ( count ( $cell_data ) == 1 )
938 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
940 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
941 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
942 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
945 $lines[$key] .= $cell;
946 array_push ( $td_history , true );
951 // Closing open td, tr && table
952 while ( count ( $td_history ) > 0 )
954 if ( array_pop ( $td_history ) ) {
957 if ( array_pop ( $tr_history ) ) {
960 if ( !array_pop ( $has_opened_tr ) ) {
961 $lines[] = "<tr><td></td></tr>" ;
964 $lines[] = '</table>' ;
967 $output = implode ( "\n" , $lines ) ;
969 // special case: don't return empty table
970 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
974 wfProfileOut( $fname );
980 * Helper function for parse() that transforms wiki markup into
981 * HTML. Only called for $mOutputType == OT_HTML.
985 function internalParse( $text ) {
988 $fname = 'Parser::internalParse';
989 wfProfileIn( $fname );
991 # Hook to suspend the parser in this state
992 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
993 wfProfileOut( $fname );
997 # Remove <noinclude> tags and <includeonly> sections
998 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
999 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1000 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1002 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1004 $text = $this->replaceVariables( $text, $args );
1006 // Tables need to come after variable replacement for things to work
1007 // properly; putting them before other transformations should keep
1008 // exciting things like link expansions from showing up in surprising
1010 $text = $this->doTableStuff( $text );
1012 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1014 $text = $this->stripToc( $text );
1015 $this->stripNoGallery( $text );
1016 $text = $this->doHeadings( $text );
1017 if($this->mOptions
->getUseDynamicDates()) {
1018 $df =& DateFormatter
::getInstance();
1019 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1021 $text = $this->doAllQuotes( $text );
1022 $text = $this->replaceInternalLinks( $text );
1023 $text = $this->replaceExternalLinks( $text );
1025 # replaceInternalLinks may sometimes leave behind
1026 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1027 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1029 $text = $this->doMagicLinks( $text );
1030 $text = $this->formatHeadings( $text, $isMain );
1032 wfProfileOut( $fname );
1037 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1038 * magic external links.
1042 function &doMagicLinks( &$text ) {
1043 wfProfileIn( __METHOD__
);
1044 $text = preg_replace_callback(
1046 <a.*?</a> | # Skip link text
1047 <.*?> | # Skip stuff inside HTML elements
1048 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1049 ISBN\s+(\b # ISBN, capture number as m[2]
1050 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1051 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1052 [0-9Xx] # check digit
1054 )!x', array( &$this, 'magicLinkCallback' ), $text );
1055 wfProfileOut( __METHOD__
);
1059 function magicLinkCallback( $m ) {
1060 if ( substr( $m[0], 0, 1 ) == '<' ) {
1063 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1065 $num = strtr( $isbn, array(
1070 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1071 $text = '<a href="' .
1072 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1073 "\" class=\"internal\">ISBN $isbn</a>";
1075 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1079 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1081 $urlmsg = 'pubmedurl';
1084 throw new MWException( __METHOD__
.': unrecognised match type "' .
1085 substr($m[0], 0, 20 ) . '"' );
1088 $url = wfMsg( $urlmsg, $id);
1089 $sk =& $this->mOptions
->getSkin();
1090 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1091 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1097 * Parse headers and return html
1101 function doHeadings( $text ) {
1102 $fname = 'Parser::doHeadings';
1103 wfProfileIn( $fname );
1104 for ( $i = 6; $i >= 1; --$i ) {
1105 $h = str_repeat( '=', $i );
1106 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1107 "<h{$i}>\\1</h{$i}>\\2", $text );
1109 wfProfileOut( $fname );
1114 * Replace single quotes with HTML markup
1116 * @return string the altered text
1118 function doAllQuotes( $text ) {
1119 $fname = 'Parser::doAllQuotes';
1120 wfProfileIn( $fname );
1122 $lines = explode( "\n", $text );
1123 foreach ( $lines as $line ) {
1124 $outtext .= $this->doQuotes ( $line ) . "\n";
1126 $outtext = substr($outtext, 0,-1);
1127 wfProfileOut( $fname );
1132 * Helper function for doAllQuotes()
1135 function doQuotes( $text ) {
1136 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1137 if ( count( $arr ) == 1 )
1141 # First, do some preliminary work. This may shift some apostrophes from
1142 # being mark-up to being text. It also counts the number of occurrences
1143 # of bold and italics mark-ups.
1147 foreach ( $arr as $r )
1149 if ( ( $i %
2 ) == 1 )
1151 # If there are ever four apostrophes, assume the first is supposed to
1152 # be text, and the remaining three constitute mark-up for bold text.
1153 if ( strlen( $arr[$i] ) == 4 )
1158 # If there are more than 5 apostrophes in a row, assume they're all
1159 # text except for the last 5.
1160 else if ( strlen( $arr[$i] ) > 5 )
1162 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1165 # Count the number of occurrences of bold and italics mark-ups.
1166 # We are not counting sequences of five apostrophes.
1167 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1168 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1169 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1174 # If there is an odd number of both bold and italics, it is likely
1175 # that one of the bold ones was meant to be an apostrophe followed
1176 # by italics. Which one we cannot know for certain, but it is more
1177 # likely to be one that has a single-letter word before it.
1178 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1181 $firstsingleletterword = -1;
1182 $firstmultiletterword = -1;
1184 foreach ( $arr as $r )
1186 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1188 $x1 = substr ($arr[$i-1], -1);
1189 $x2 = substr ($arr[$i-1], -2, 1);
1191 if ($firstspace == -1) $firstspace = $i;
1192 } else if ($x2 == ' ') {
1193 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1195 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1201 # If there is a single-letter word, use it!
1202 if ($firstsingleletterword > -1)
1204 $arr [ $firstsingleletterword ] = "''";
1205 $arr [ $firstsingleletterword-1 ] .= "'";
1207 # If not, but there's a multi-letter word, use that one.
1208 else if ($firstmultiletterword > -1)
1210 $arr [ $firstmultiletterword ] = "''";
1211 $arr [ $firstmultiletterword-1 ] .= "'";
1213 # ... otherwise use the first one that has neither.
1214 # (notice that it is possible for all three to be -1 if, for example,
1215 # there is only one pentuple-apostrophe in the line)
1216 else if ($firstspace > -1)
1218 $arr [ $firstspace ] = "''";
1219 $arr [ $firstspace-1 ] .= "'";
1223 # Now let's actually convert our apostrophic mush to HTML!
1228 foreach ($arr as $r)
1232 if ($state == 'both')
1239 if (strlen ($r) == 2)
1242 { $output .= '</i>'; $state = ''; }
1243 else if ($state == 'bi')
1244 { $output .= '</i>'; $state = 'b'; }
1245 else if ($state == 'ib')
1246 { $output .= '</b></i><b>'; $state = 'b'; }
1247 else if ($state == 'both')
1248 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1249 else # $state can be 'b' or ''
1250 { $output .= '<i>'; $state .= 'i'; }
1252 else if (strlen ($r) == 3)
1255 { $output .= '</b>'; $state = ''; }
1256 else if ($state == 'bi')
1257 { $output .= '</i></b><i>'; $state = 'i'; }
1258 else if ($state == 'ib')
1259 { $output .= '</b>'; $state = 'i'; }
1260 else if ($state == 'both')
1261 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1262 else # $state can be 'i' or ''
1263 { $output .= '<b>'; $state .= 'b'; }
1265 else if (strlen ($r) == 5)
1268 { $output .= '</b><i>'; $state = 'i'; }
1269 else if ($state == 'i')
1270 { $output .= '</i><b>'; $state = 'b'; }
1271 else if ($state == 'bi')
1272 { $output .= '</i></b>'; $state = ''; }
1273 else if ($state == 'ib')
1274 { $output .= '</b></i>'; $state = ''; }
1275 else if ($state == 'both')
1276 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1277 else # ($state == '')
1278 { $buffer = ''; $state = 'both'; }
1283 # Now close all remaining tags. Notice that the order is important.
1284 if ($state == 'b' ||
$state == 'ib')
1286 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1290 if ($state == 'both')
1291 $output .= '<b><i>'.$buffer.'</i></b>';
1297 * Replace external links
1299 * Note: this is all very hackish and the order of execution matters a lot.
1300 * Make sure to run maintenance/parserTests.php if you change this code.
1304 function replaceExternalLinks( $text ) {
1306 $fname = 'Parser::replaceExternalLinks';
1307 wfProfileIn( $fname );
1309 $sk =& $this->mOptions
->getSkin();
1311 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1313 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1316 while ( $i<count( $bits ) ) {
1318 $protocol = $bits[$i++
];
1319 $text = $bits[$i++
];
1320 $trail = $bits[$i++
];
1322 # The characters '<' and '>' (which were escaped by
1323 # removeHTMLtags()) should not be included in
1324 # URLs, per RFC 2396.
1326 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1327 $text = substr($url, $m2[0][1]) . ' ' . $text;
1328 $url = substr($url, 0, $m2[0][1]);
1331 # If the link text is an image URL, replace it with an <img> tag
1332 # This happened by accident in the original parser, but some people used it extensively
1333 $img = $this->maybeMakeExternalImage( $text );
1334 if ( $img !== false ) {
1340 # Set linktype for CSS - if URL==text, link is essentially free
1341 $linktype = ($text == $url) ?
'free' : 'text';
1343 # No link text, e.g. [http://domain.tld/some.link]
1344 if ( $text == '' ) {
1345 # Autonumber if allowed. See bug #5918
1346 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1347 $text = '[' . ++
$this->mAutonumber
. ']';
1348 $linktype = 'autonumber';
1350 # Otherwise just use the URL
1351 $text = htmlspecialchars( $url );
1355 # Have link text, e.g. [http://domain.tld/some.link text]s
1357 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1360 $text = $wgContLang->markNoConversion($text);
1362 $url = Sanitizer
::cleanUrl( $url );
1364 # Process the trail (i.e. everything after this link up until start of the next link),
1365 # replacing any non-bracketed links
1366 $trail = $this->replaceFreeExternalLinks( $trail );
1368 # Use the encoded URL
1369 # This means that users can paste URLs directly into the text
1370 # Funny characters like ö aren't valid in URLs anyway
1371 # This was changed in August 2004
1372 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1374 # Register link in the output object.
1375 # Replace unnecessary URL escape codes with the referenced character
1376 # This prevents spammers from hiding links from the filters
1377 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1378 $this->mOutput
->addExternalLink( $pasteurized );
1381 wfProfileOut( $fname );
1386 * Replace anything that looks like a URL with a link
1389 function replaceFreeExternalLinks( $text ) {
1391 $fname = 'Parser::replaceFreeExternalLinks';
1392 wfProfileIn( $fname );
1394 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1395 $s = array_shift( $bits );
1398 $sk =& $this->mOptions
->getSkin();
1400 while ( $i < count( $bits ) ){
1401 $protocol = $bits[$i++
];
1402 $remainder = $bits[$i++
];
1405 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1406 # Found some characters after the protocol that look promising
1407 $url = $protocol . $m[1];
1410 # special case: handle urls as url args:
1411 # http://www.example.com/foo?=http://www.example.com/bar
1412 if(strlen($trail) == 0 &&
1414 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1415 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1418 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1423 # The characters '<' and '>' (which were escaped by
1424 # removeHTMLtags()) should not be included in
1425 # URLs, per RFC 2396.
1427 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1428 $trail = substr($url, $m2[0][1]) . $trail;
1429 $url = substr($url, 0, $m2[0][1]);
1432 # Move trailing punctuation to $trail
1434 # If there is no left bracket, then consider right brackets fair game too
1435 if ( strpos( $url, '(' ) === false ) {
1439 $numSepChars = strspn( strrev( $url ), $sep );
1440 if ( $numSepChars ) {
1441 $trail = substr( $url, -$numSepChars ) . $trail;
1442 $url = substr( $url, 0, -$numSepChars );
1445 $url = Sanitizer
::cleanUrl( $url );
1447 # Is this an external image?
1448 $text = $this->maybeMakeExternalImage( $url );
1449 if ( $text === false ) {
1450 # Not an image, make a link
1451 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1452 # Register it in the output object...
1453 # Replace unnecessary URL escape codes with their equivalent characters
1454 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1455 $this->mOutput
->addExternalLink( $pasteurized );
1457 $s .= $text . $trail;
1459 $s .= $protocol . $remainder;
1462 wfProfileOut( $fname );
1467 * Replace unusual URL escape codes with their equivalent characters
1471 * @fixme This can merge genuinely required bits in the path or query string,
1472 * breaking legit URLs. A proper fix would treat the various parts of
1473 * the URL differently; as a workaround, just use the output for
1474 * statistical records, not for actual linking/output.
1476 static function replaceUnusualEscapes( $url ) {
1477 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1478 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1482 * Callback function used in replaceUnusualEscapes().
1483 * Replaces unusual URL escape codes with their equivalent character
1487 private static function replaceUnusualEscapesCallback( $matches ) {
1488 $char = urldecode( $matches[0] );
1489 $ord = ord( $char );
1490 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1491 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1492 // No, shouldn't be escaped
1495 // Yes, leave it escaped
1501 * make an image if it's allowed, either through the global
1502 * option or through the exception
1505 function maybeMakeExternalImage( $url ) {
1506 $sk =& $this->mOptions
->getSkin();
1507 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1508 $imagesexception = !empty($imagesfrom);
1510 if ( $this->mOptions
->getAllowExternalImages()
1511 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1512 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1514 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1521 * Process [[ ]] wikilinks
1525 function replaceInternalLinks( $s ) {
1527 static $fname = 'Parser::replaceInternalLinks' ;
1529 wfProfileIn( $fname );
1531 wfProfileIn( $fname.'-setup' );
1533 # the % is needed to support urlencoded titles as well
1534 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1536 $sk =& $this->mOptions
->getSkin();
1538 #split the entire text string on occurences of [[
1539 $a = explode( '[[', ' ' . $s );
1540 #get the first element (all text up to first [[), and remove the space we added
1541 $s = array_shift( $a );
1542 $s = substr( $s, 1 );
1544 # Match a link having the form [[namespace:link|alternate]]trail
1546 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1547 # Match cases where there is no "]]", which might still be images
1548 static $e1_img = FALSE;
1549 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1550 # Match the end of a line for a word that's not followed by whitespace,
1551 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1552 $e2 = wfMsgForContent( 'linkprefix' );
1554 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1556 if( is_null( $this->mTitle
) ) {
1557 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1559 $nottalk = !$this->mTitle
->isTalkPage();
1561 if ( $useLinkPrefixExtension ) {
1563 if ( preg_match( $e2, $s, $m ) ) {
1564 $first_prefix = $m[2];
1566 $first_prefix = false;
1572 if($wgContLang->hasVariants())
1573 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1575 $selflink = array($this->mTitle
->getPrefixedText());
1576 $useSubpages = $this->areSubpagesAllowed();
1577 wfProfileOut( $fname.'-setup' );
1579 # Loop for each link
1580 for ($k = 0; isset( $a[$k] ); $k++
) {
1582 if ( $useLinkPrefixExtension ) {
1583 wfProfileIn( $fname.'-prefixhandling' );
1584 if ( preg_match( $e2, $s, $m ) ) {
1592 $prefix = $first_prefix;
1593 $first_prefix = false;
1595 wfProfileOut( $fname.'-prefixhandling' );
1598 $might_be_img = false;
1600 wfProfileIn( "$fname-e1" );
1601 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1603 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1604 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1605 # the real problem is with the $e1 regex
1608 # Still some problems for cases where the ] is meant to be outside punctuation,
1609 # and no image is in sight. See bug 2095.
1612 substr( $m[3], 0, 1 ) === ']' &&
1613 strpos($text, '[') !== false
1616 $text .= ']'; # so that replaceExternalLinks($text) works later
1617 $m[3] = substr( $m[3], 1 );
1619 # fix up urlencoded title texts
1620 if( strpos( $m[1], '%' ) !== false ) {
1621 # Should anchors '#' also be rejected?
1622 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1625 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1626 $might_be_img = true;
1628 if ( strpos( $m[1], '%' ) !== false ) {
1629 $m[1] = urldecode($m[1]);
1632 } else { # Invalid form; output directly
1633 $s .= $prefix . '[[' . $line ;
1634 wfProfileOut( "$fname-e1" );
1637 wfProfileOut( "$fname-e1" );
1638 wfProfileIn( "$fname-misc" );
1640 # Don't allow internal links to pages containing
1641 # PROTO: where PROTO is a valid URL protocol; these
1642 # should be external links.
1643 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1644 $s .= $prefix . '[[' . $line ;
1648 # Make subpage if necessary
1649 if( $useSubpages ) {
1650 $link = $this->maybeDoSubpageLink( $m[1], $text );
1655 $noforce = (substr($m[1], 0, 1) != ':');
1657 # Strip off leading ':'
1658 $link = substr($link, 1);
1661 wfProfileOut( "$fname-misc" );
1662 wfProfileIn( "$fname-title" );
1663 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1665 $s .= $prefix . '[[' . $line;
1666 wfProfileOut( "$fname-title" );
1670 $ns = $nt->getNamespace();
1671 $iw = $nt->getInterWiki();
1672 wfProfileOut( "$fname-title" );
1674 if ($might_be_img) { # if this is actually an invalid link
1675 wfProfileIn( "$fname-might_be_img" );
1676 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1678 while (isset ($a[$k+
1]) ) {
1679 #look at the next 'line' to see if we can close it there
1680 $spliced = array_splice( $a, $k +
1, 1 );
1681 $next_line = array_shift( $spliced );
1682 $m = explode( ']]', $next_line, 3 );
1683 if ( count( $m ) == 3 ) {
1684 # the first ]] closes the inner link, the second the image
1686 $text .= "[[{$m[0]}]]{$m[1]}";
1689 } elseif ( count( $m ) == 2 ) {
1690 #if there's exactly one ]] that's fine, we'll keep looking
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1693 #if $next_line is invalid too, we need look no further
1694 $text .= '[[' . $next_line;
1699 # we couldn't find the end of this imageLink, so output it raw
1700 #but don't ignore what might be perfectly normal links in the text we've examined
1701 $text = $this->replaceInternalLinks($text);
1702 $s .= "{$prefix}[[$link|$text";
1703 # note: no $trail, because without an end, there *is* no trail
1704 wfProfileOut( "$fname-might_be_img" );
1707 } else { #it's not an image, so output it raw
1708 $s .= "{$prefix}[[$link|$text";
1709 # note: no $trail, because without an end, there *is* no trail
1710 wfProfileOut( "$fname-might_be_img" );
1713 wfProfileOut( "$fname-might_be_img" );
1716 $wasblank = ( '' == $text );
1717 if( $wasblank ) $text = $link;
1719 # Link not escaped by : , create the various objects
1723 wfProfileIn( "$fname-interwiki" );
1724 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1725 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1726 $s = rtrim($s . "\n");
1727 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1728 wfProfileOut( "$fname-interwiki" );
1731 wfProfileOut( "$fname-interwiki" );
1733 if ( $ns == NS_IMAGE
) {
1734 wfProfileIn( "$fname-image" );
1735 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1736 # recursively parse links inside the image caption
1737 # actually, this will parse them in any other parameters, too,
1738 # but it might be hard to fix that, and it doesn't matter ATM
1739 $text = $this->replaceExternalLinks($text);
1740 $text = $this->replaceInternalLinks($text);
1742 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1743 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1744 $this->mOutput
->addImage( $nt->getDBkey() );
1746 wfProfileOut( "$fname-image" );
1749 # We still need to record the image's presence on the page
1750 $this->mOutput
->addImage( $nt->getDBkey() );
1752 wfProfileOut( "$fname-image" );
1756 if ( $ns == NS_CATEGORY
) {
1757 wfProfileIn( "$fname-category" );
1758 $s = rtrim($s . "\n"); # bug 87
1761 $sortkey = $this->getDefaultSort();
1765 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1766 $sortkey = str_replace( "\n", '', $sortkey );
1767 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1768 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1771 * Strip the whitespace Category links produce, see bug 87
1772 * @todo We might want to use trim($tmp, "\n") here.
1774 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1776 wfProfileOut( "$fname-category" );
1781 if( ( in_array( $nt->getPrefixedText(), $selflink ) ) &&
1782 ( $nt->getFragment() === '' ) ) {
1783 # Self-links are handled specially; generally de-link and change to bold.
1784 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1788 # Special and Media are pseudo-namespaces; no pages actually exist in them
1789 if( $ns == NS_MEDIA
) {
1790 $link = $sk->makeMediaLinkObj( $nt, $text );
1791 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1792 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1793 $this->mOutput
->addImage( $nt->getDBkey() );
1795 } elseif( $ns == NS_SPECIAL
) {
1796 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1798 } elseif( $ns == NS_IMAGE
) {
1799 $img = new Image( $nt );
1800 if( $img->exists() ) {
1801 // Force a blue link if the file exists; may be a remote
1802 // upload on the shared repository, and we want to see its
1803 // auto-generated page.
1804 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1805 $this->mOutput
->addLink( $nt );
1809 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1811 wfProfileOut( $fname );
1816 * Make a link placeholder. The text returned can be later resolved to a real link with
1817 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1818 * parsing of interwiki links, and secondly to allow all existence checks and
1819 * article length checks (for stub links) to be bundled into a single query.
1822 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1823 wfProfileIn( __METHOD__
);
1824 if ( ! is_object($nt) ) {
1826 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1828 # Separate the link trail from the rest of the link
1829 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1831 if ( $nt->isExternal() ) {
1832 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1833 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1834 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1836 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1837 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1838 $this->mLinkHolders
['queries'][] = $query;
1839 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1840 $this->mLinkHolders
['titles'][] = $nt;
1842 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1845 wfProfileOut( __METHOD__
);
1850 * Render a forced-blue link inline; protect against double expansion of
1851 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1852 * Since this little disaster has to split off the trail text to avoid
1853 * breaking URLs in the following text without breaking trails on the
1854 * wiki links, it's been made into a horrible function.
1857 * @param string $text
1858 * @param string $query
1859 * @param string $trail
1860 * @param string $prefix
1861 * @return string HTML-wikitext mix oh yuck
1863 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1864 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1865 $sk =& $this->mOptions
->getSkin();
1866 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1867 return $this->armorLinks( $link ) . $trail;
1871 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1872 * going to go through further parsing steps before inline URL expansion.
1874 * In particular this is important when using action=render, which causes
1875 * full URLs to be included.
1877 * Oh man I hate our multi-layer parser!
1879 * @param string more-or-less HTML
1880 * @return string less-or-more HTML with NOPARSE bits
1882 function armorLinks( $text ) {
1883 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1884 "{$this->mUniqPrefix}NOPARSE$1", $text );
1888 * Return true if subpage links should be expanded on this page.
1891 function areSubpagesAllowed() {
1892 # Some namespaces don't allow subpages
1893 global $wgNamespacesWithSubpages;
1894 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1898 * Handle link to subpage if necessary
1899 * @param string $target the source of the link
1900 * @param string &$text the link text, modified as necessary
1901 * @return string the full name of the link
1904 function maybeDoSubpageLink($target, &$text) {
1907 # :Foobar -- override special treatment of prefix (images, language links)
1908 # /Foobar -- convert to CurrentPage/Foobar
1909 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1910 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1911 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1913 $fname = 'Parser::maybeDoSubpageLink';
1914 wfProfileIn( $fname );
1915 $ret = $target; # default return value is no change
1918 $target = trim( $target );
1920 # Some namespaces don't allow subpages,
1921 # so only perform processing if subpages are allowed
1922 if( $this->areSubpagesAllowed() ) {
1923 # Look at the first character
1924 if( $target != '' && $target{0} == '/' ) {
1925 # / at end means we don't want the slash to be shown
1926 if( substr( $target, -1, 1 ) == '/' ) {
1927 $target = substr( $target, 1, -1 );
1930 $noslash = substr( $target, 1 );
1933 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1934 if( '' === $text ) {
1936 } # this might be changed for ugliness reasons
1938 # check for .. subpage backlinks
1940 $nodotdot = $target;
1941 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1943 $nodotdot = substr( $nodotdot, 3 );
1945 if($dotdotcount > 0) {
1946 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1947 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1948 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1949 # / at the end means don't show full path
1950 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1951 $nodotdot = substr( $nodotdot, 0, -1 );
1952 if( '' === $text ) {
1956 $nodotdot = trim( $nodotdot );
1957 if( $nodotdot != '' ) {
1958 $ret .= '/' . $nodotdot;
1965 wfProfileOut( $fname );
1970 * Used by doBlockLevels()
1973 /* private */ function closeParagraph() {
1975 if ( '' != $this->mLastSection
) {
1976 $result = '</' . $this->mLastSection
. ">\n";
1978 $this->mInPre
= false;
1979 $this->mLastSection
= '';
1982 # getCommon() returns the length of the longest common substring
1983 # of both arguments, starting at the beginning of both.
1985 /* private */ function getCommon( $st1, $st2 ) {
1986 $fl = strlen( $st1 );
1987 $shorter = strlen( $st2 );
1988 if ( $fl < $shorter ) { $shorter = $fl; }
1990 for ( $i = 0; $i < $shorter; ++
$i ) {
1991 if ( $st1{$i} != $st2{$i} ) { break; }
1995 # These next three functions open, continue, and close the list
1996 # element appropriate to the prefix character passed into them.
1998 /* private */ function openList( $char ) {
1999 $result = $this->closeParagraph();
2001 if ( '*' == $char ) { $result .= '<ul><li>'; }
2002 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2003 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2004 else if ( ';' == $char ) {
2005 $result .= '<dl><dt>';
2006 $this->mDTopen
= true;
2008 else { $result = '<!-- ERR 1 -->'; }
2013 /* private */ function nextItem( $char ) {
2014 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2015 else if ( ':' == $char ||
';' == $char ) {
2017 if ( $this->mDTopen
) { $close = '</dt>'; }
2018 if ( ';' == $char ) {
2019 $this->mDTopen
= true;
2020 return $close . '<dt>';
2022 $this->mDTopen
= false;
2023 return $close . '<dd>';
2026 return '<!-- ERR 2 -->';
2029 /* private */ function closeList( $char ) {
2030 if ( '*' == $char ) { $text = '</li></ul>'; }
2031 else if ( '#' == $char ) { $text = '</li></ol>'; }
2032 else if ( ':' == $char ) {
2033 if ( $this->mDTopen
) {
2034 $this->mDTopen
= false;
2035 $text = '</dt></dl>';
2037 $text = '</dd></dl>';
2040 else { return '<!-- ERR 3 -->'; }
2046 * Make lists from lines starting with ':', '*', '#', etc.
2049 * @return string the lists rendered as HTML
2051 function doBlockLevels( $text, $linestart ) {
2052 $fname = 'Parser::doBlockLevels';
2053 wfProfileIn( $fname );
2055 # Parsing through the text line by line. The main thing
2056 # happening here is handling of block-level elements p, pre,
2057 # and making lists from lines starting with * # : etc.
2059 $textLines = explode( "\n", $text );
2061 $lastPrefix = $output = '';
2062 $this->mDTopen
= $inBlockElem = false;
2064 $paragraphStack = false;
2066 if ( !$linestart ) {
2067 $output .= array_shift( $textLines );
2069 foreach ( $textLines as $oLine ) {
2070 $lastPrefixLength = strlen( $lastPrefix );
2071 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2072 $preOpenMatch = preg_match('/<pre/i', $oLine );
2073 if ( !$this->mInPre
) {
2074 # Multiple prefixes may abut each other for nested lists.
2075 $prefixLength = strspn( $oLine, '*#:;' );
2076 $pref = substr( $oLine, 0, $prefixLength );
2079 $pref2 = str_replace( ';', ':', $pref );
2080 $t = substr( $oLine, $prefixLength );
2081 $this->mInPre
= !empty($preOpenMatch);
2083 # Don't interpret any other prefixes in preformatted text
2085 $pref = $pref2 = '';
2090 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2091 # Same as the last item, so no need to deal with nesting or opening stuff
2092 $output .= $this->nextItem( substr( $pref, -1 ) );
2093 $paragraphStack = false;
2095 if ( substr( $pref, -1 ) == ';') {
2096 # The one nasty exception: definition lists work like this:
2097 # ; title : definition text
2098 # So we check for : in the remainder text to split up the
2099 # title and definition, without b0rking links.
2101 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2103 $output .= $term . $this->nextItem( ':' );
2106 } elseif( $prefixLength ||
$lastPrefixLength ) {
2107 # Either open or close a level...
2108 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2109 $paragraphStack = false;
2111 while( $commonPrefixLength < $lastPrefixLength ) {
2112 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2113 --$lastPrefixLength;
2115 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2116 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2118 while ( $prefixLength > $commonPrefixLength ) {
2119 $char = substr( $pref, $commonPrefixLength, 1 );
2120 $output .= $this->openList( $char );
2122 if ( ';' == $char ) {
2123 # FIXME: This is dupe of code above
2124 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2126 $output .= $term . $this->nextItem( ':' );
2129 ++
$commonPrefixLength;
2131 $lastPrefix = $pref2;
2133 if( 0 == $prefixLength ) {
2134 wfProfileIn( "$fname-paragraph" );
2135 # No prefix (not in list)--go to paragraph mode
2136 // XXX: use a stack for nestable elements like span, table and div
2137 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2138 $closematch = preg_match(
2139 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2140 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2141 if ( $openmatch or $closematch ) {
2142 $paragraphStack = false;
2143 #Â TODO bug 5718: paragraph closed
2144 $output .= $this->closeParagraph();
2145 if ( $preOpenMatch and !$preCloseMatch ) {
2146 $this->mInPre
= true;
2148 if ( $closematch ) {
2149 $inBlockElem = false;
2151 $inBlockElem = true;
2153 } else if ( !$inBlockElem && !$this->mInPre
) {
2154 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2156 if ($this->mLastSection
!= 'pre') {
2157 $paragraphStack = false;
2158 $output .= $this->closeParagraph().'<pre>';
2159 $this->mLastSection
= 'pre';
2161 $t = substr( $t, 1 );
2164 if ( '' == trim($t) ) {
2165 if ( $paragraphStack ) {
2166 $output .= $paragraphStack.'<br />';
2167 $paragraphStack = false;
2168 $this->mLastSection
= 'p';
2170 if ($this->mLastSection
!= 'p' ) {
2171 $output .= $this->closeParagraph();
2172 $this->mLastSection
= '';
2173 $paragraphStack = '<p>';
2175 $paragraphStack = '</p><p>';
2179 if ( $paragraphStack ) {
2180 $output .= $paragraphStack;
2181 $paragraphStack = false;
2182 $this->mLastSection
= 'p';
2183 } else if ($this->mLastSection
!= 'p') {
2184 $output .= $this->closeParagraph().'<p>';
2185 $this->mLastSection
= 'p';
2190 wfProfileOut( "$fname-paragraph" );
2192 // somewhere above we forget to get out of pre block (bug 785)
2193 if($preCloseMatch && $this->mInPre
) {
2194 $this->mInPre
= false;
2196 if ($paragraphStack === false) {
2200 while ( $prefixLength ) {
2201 $output .= $this->closeList( $pref2{$prefixLength-1} );
2204 if ( '' != $this->mLastSection
) {
2205 $output .= '</' . $this->mLastSection
. '>';
2206 $this->mLastSection
= '';
2209 wfProfileOut( $fname );
2214 * Split up a string on ':', ignoring any occurences inside tags
2215 * to prevent illegal overlapping.
2216 * @param string $str the string to split
2217 * @param string &$before set to everything before the ':'
2218 * @param string &$after set to everything after the ':'
2219 * return string the position of the ':', or false if none found
2221 function findColonNoLinks($str, &$before, &$after) {
2222 $fname = 'Parser::findColonNoLinks';
2223 wfProfileIn( $fname );
2225 $pos = strpos( $str, ':' );
2226 if( $pos === false ) {
2228 wfProfileOut( $fname );
2232 $lt = strpos( $str, '<' );
2233 if( $lt === false ||
$lt > $pos ) {
2234 // Easy; no tag nesting to worry about
2235 $before = substr( $str, 0, $pos );
2236 $after = substr( $str, $pos+
1 );
2237 wfProfileOut( $fname );
2241 // Ugly state machine to walk through avoiding tags.
2242 $state = MW_COLON_STATE_TEXT
;
2244 $len = strlen( $str );
2245 for( $i = 0; $i < $len; $i++
) {
2249 // (Using the number is a performance hack for common cases)
2250 case 0: // MW_COLON_STATE_TEXT:
2253 // Could be either a <start> tag or an </end> tag
2254 $state = MW_COLON_STATE_TAGSTART
;
2259 $before = substr( $str, 0, $i );
2260 $after = substr( $str, $i +
1 );
2261 wfProfileOut( $fname );
2264 // Embedded in a tag; don't break it.
2267 // Skip ahead looking for something interesting
2268 $colon = strpos( $str, ':', $i );
2269 if( $colon === false ) {
2270 // Nothing else interesting
2271 wfProfileOut( $fname );
2274 $lt = strpos( $str, '<', $i );
2275 if( $stack === 0 ) {
2276 if( $lt === false ||
$colon < $lt ) {
2278 $before = substr( $str, 0, $colon );
2279 $after = substr( $str, $colon +
1 );
2280 wfProfileOut( $fname );
2284 if( $lt === false ) {
2285 // Nothing else interesting to find; abort!
2286 // We're nested, but there's no close tags left. Abort!
2289 // Skip ahead to next tag start
2291 $state = MW_COLON_STATE_TAGSTART
;
2294 case 1: // MW_COLON_STATE_TAG:
2299 $state = MW_COLON_STATE_TEXT
;
2302 // Slash may be followed by >?
2303 $state = MW_COLON_STATE_TAGSLASH
;
2309 case 2: // MW_COLON_STATE_TAGSTART:
2312 $state = MW_COLON_STATE_CLOSETAG
;
2315 $state = MW_COLON_STATE_COMMENT
;
2318 // Illegal early close? This shouldn't happen D:
2319 $state = MW_COLON_STATE_TEXT
;
2322 $state = MW_COLON_STATE_TAG
;
2325 case 3: // MW_COLON_STATE_CLOSETAG:
2330 wfDebug( "Invalid input in $fname; too many close tags\n" );
2331 wfProfileOut( $fname );
2334 $state = MW_COLON_STATE_TEXT
;
2337 case MW_COLON_STATE_TAGSLASH
:
2339 // Yes, a self-closed tag <blah/>
2340 $state = MW_COLON_STATE_TEXT
;
2342 // Probably we're jumping the gun, and this is an attribute
2343 $state = MW_COLON_STATE_TAG
;
2346 case 5: // MW_COLON_STATE_COMMENT:
2348 $state = MW_COLON_STATE_COMMENTDASH
;
2351 case MW_COLON_STATE_COMMENTDASH
:
2353 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2355 $state = MW_COLON_STATE_COMMENT
;
2358 case MW_COLON_STATE_COMMENTDASHDASH
:
2360 $state = MW_COLON_STATE_TEXT
;
2362 $state = MW_COLON_STATE_COMMENT
;
2366 throw new MWException( "State machine error in $fname" );
2370 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2373 wfProfileOut( $fname );
2378 * Return value of a magic variable (like PAGENAME)
2382 function getVariableValue( $index ) {
2383 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2386 * Some of these require message or data lookups and can be
2387 * expensive to check many times.
2389 static $varCache = array();
2390 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2391 if ( isset( $varCache[$index] ) ) {
2392 return $varCache[$index];
2397 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2400 global $wgLocaltimezone;
2401 if ( isset( $wgLocaltimezone ) ) {
2402 $oldtz = getenv( 'TZ' );
2403 putenv( 'TZ='.$wgLocaltimezone );
2405 $localTimestamp = date( 'YmdHis', $ts );
2406 $localMonth = date( 'm', $ts );
2407 $localMonthName = date( 'n', $ts );
2408 $localDay = date( 'j', $ts );
2409 $localDay2 = date( 'd', $ts );
2410 $localDayOfWeek = date( 'w', $ts );
2411 $localWeek = date( 'W', $ts );
2412 $localYear = date( 'Y', $ts );
2413 $localHour = date( 'H', $ts );
2414 if ( isset( $wgLocaltimezone ) ) {
2415 putenv( 'TZ='.$oldtz );
2419 case 'currentmonth':
2420 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2421 case 'currentmonthname':
2422 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2423 case 'currentmonthnamegen':
2424 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2425 case 'currentmonthabbrev':
2426 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2428 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2430 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2432 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2433 case 'localmonthname':
2434 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2435 case 'localmonthnamegen':
2436 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2437 case 'localmonthabbrev':
2438 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2440 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2442 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2444 return $this->mTitle
->getText();
2446 return $this->mTitle
->getPartialURL();
2447 case 'fullpagename':
2448 return $this->mTitle
->getPrefixedText();
2449 case 'fullpagenamee':
2450 return $this->mTitle
->getPrefixedURL();
2452 return $this->mTitle
->getSubpageText();
2453 case 'subpagenamee':
2454 return $this->mTitle
->getSubpageUrlForm();
2455 case 'basepagename':
2456 return $this->mTitle
->getBaseText();
2457 case 'basepagenamee':
2458 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2459 case 'talkpagename':
2460 if( $this->mTitle
->canTalk() ) {
2461 $talkPage = $this->mTitle
->getTalkPage();
2462 return $talkPage->getPrefixedText();
2466 case 'talkpagenamee':
2467 if( $this->mTitle
->canTalk() ) {
2468 $talkPage = $this->mTitle
->getTalkPage();
2469 return $talkPage->getPrefixedUrl();
2473 case 'subjectpagename':
2474 $subjPage = $this->mTitle
->getSubjectPage();
2475 return $subjPage->getPrefixedText();
2476 case 'subjectpagenamee':
2477 $subjPage = $this->mTitle
->getSubjectPage();
2478 return $subjPage->getPrefixedUrl();
2480 return $this->mRevisionId
;
2482 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2483 case 'revisionday2':
2484 return substr( $this->getRevisionTimestamp(), 6, 2 );
2485 case 'revisionmonth':
2486 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2487 case 'revisionyear':
2488 return substr( $this->getRevisionTimestamp(), 0, 4 );
2489 case 'revisiontimestamp':
2490 return $this->getRevisionTimestamp();
2492 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2494 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2496 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2498 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2499 case 'subjectspace':
2500 return $this->mTitle
->getSubjectNsText();
2501 case 'subjectspacee':
2502 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2503 case 'currentdayname':
2504 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2506 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2508 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2510 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2512 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2513 // int to remove the padding
2514 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2516 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2517 case 'localdayname':
2518 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2520 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2522 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2524 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2526 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2527 // int to remove the padding
2528 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2530 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2531 case 'numberofarticles':
2532 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2533 case 'numberoffiles':
2534 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2535 case 'numberofusers':
2536 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2537 case 'numberofpages':
2538 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2539 case 'numberofadmins':
2540 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2541 case 'currenttimestamp':
2542 return $varCache[$index] = wfTimestampNow();
2543 case 'localtimestamp':
2544 return $varCache[$index] = $localTimestamp;
2545 case 'currentversion':
2546 return $varCache[$index] = SpecialVersion
::getVersion();
2552 return $wgServerName;
2554 return $wgScriptPath;
2555 case 'directionmark':
2556 return $wgContLang->getDirMark();
2557 case 'contentlanguage':
2558 global $wgContLanguageCode;
2559 return $wgContLanguageCode;
2562 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2570 * initialise the magic variables (like CURRENTMONTHNAME)
2574 function initialiseVariables() {
2575 $fname = 'Parser::initialiseVariables';
2576 wfProfileIn( $fname );
2577 $variableIDs = MagicWord
::getVariableIDs();
2579 $this->mVariables
= array();
2580 foreach ( $variableIDs as $id ) {
2581 $mw =& MagicWord
::get( $id );
2582 $mw->addToArray( $this->mVariables
, $id );
2584 wfProfileOut( $fname );
2588 * parse any parentheses in format ((title|part|part))
2589 * and call callbacks to get a replacement text for any found piece
2591 * @param string $text The text to parse
2592 * @param array $callbacks rules in form:
2593 * '{' => array( # opening parentheses
2594 * 'end' => '}', # closing parentheses
2595 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2596 * 3 => callback # replacement callback to call if {{{..}}} is found
2599 * 'min' => 2, # Minimum parenthesis count in cb
2600 * 'max' => 3, # Maximum parenthesis count in cb
2603 function replace_callback ($text, $callbacks) {
2604 wfProfileIn( __METHOD__
);
2605 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2606 $lastOpeningBrace = -1; # last not closed parentheses
2608 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2611 while ( $i < strlen( $text ) ) {
2612 # Find next opening brace, closing brace or pipe
2613 if ( $lastOpeningBrace == -1 ) {
2614 $currentClosing = '';
2615 $search = $validOpeningBraces;
2617 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2618 $search = $validOpeningBraces . '|' . $currentClosing;
2621 $i +
= strcspn( $text, $search, $i );
2622 if ( $i < strlen( $text ) ) {
2623 if ( $text[$i] == '|' ) {
2625 } elseif ( $text[$i] == $currentClosing ) {
2627 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2629 $rule = $callbacks[$text[$i]];
2631 # Some versions of PHP have a strcspn which stops on null characters
2632 # Ignore and continue
2641 if ( $found == 'open' ) {
2642 # found opening brace, let's add it to parentheses stack
2643 $piece = array('brace' => $text[$i],
2644 'braceEnd' => $rule['end'],
2648 # count opening brace characters
2649 $piece['count'] = strspn( $text, $piece['brace'], $i );
2650 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2651 $i +
= $piece['count'];
2653 # we need to add to stack only if opening brace count is enough for one of the rules
2654 if ( $piece['count'] >= $rule['min'] ) {
2655 $lastOpeningBrace ++
;
2656 $openingBraceStack[$lastOpeningBrace] = $piece;
2658 } elseif ( $found == 'close' ) {
2659 # lets check if it is enough characters for closing brace
2660 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2661 $count = strspn( $text, $text[$i], $i, $maxCount );
2663 # check for maximum matching characters (if there are 5 closing
2664 # characters, we will probably need only 3 - depending on the rules)
2666 $matchingCallback = null;
2667 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2668 if ( $count > $cbType['max'] ) {
2669 # The specified maximum exists in the callback array, unless the caller
2671 $matchingCount = $cbType['max'];
2673 # Count is less than the maximum
2674 # Skip any gaps in the callback array to find the true largest match
2675 # Need to use array_key_exists not isset because the callback can be null
2676 $matchingCount = $count;
2677 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2682 if ($matchingCount <= 0) {
2686 $matchingCallback = $cbType['cb'][$matchingCount];
2688 # let's set a title or last part (if '|' was found)
2689 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2690 $openingBraceStack[$lastOpeningBrace]['title'] =
2691 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2692 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2694 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2695 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2696 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2699 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2700 $pieceEnd = $i +
$matchingCount;
2702 if( is_callable( $matchingCallback ) ) {
2704 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2705 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2706 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2707 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2709 # finally we can call a user callback and replace piece of text
2710 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2711 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2712 $i = $pieceStart +
strlen($replaceWith);
2714 # null value for callback means that parentheses should be parsed, but not replaced
2715 $i +
= $matchingCount;
2718 # reset last opening parentheses, but keep it in case there are unused characters
2719 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2720 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2721 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2724 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2725 $openingBraceStack[$lastOpeningBrace--] = null;
2727 if ($matchingCount < $piece['count']) {
2728 $piece['count'] -= $matchingCount;
2729 $piece['startAt'] -= $matchingCount;
2730 $piece['partStart'] = $piece['startAt'];
2731 # do we still qualify for any callback with remaining count?
2732 $currentCbList = $callbacks[$piece['brace']]['cb'];
2733 while ( $piece['count'] ) {
2734 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2735 $lastOpeningBrace++
;
2736 $openingBraceStack[$lastOpeningBrace] = $piece;
2742 } elseif ( $found == 'pipe' ) {
2743 # lets set a title if it is a first separator, or next part otherwise
2744 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2745 $openingBraceStack[$lastOpeningBrace]['title'] =
2746 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2747 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2748 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2750 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2751 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2752 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2754 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2758 wfProfileOut( __METHOD__
);
2763 * Replace magic variables, templates, and template arguments
2764 * with the appropriate text. Templates are substituted recursively,
2765 * taking care to avoid infinite loops.
2767 * Note that the substitution depends on value of $mOutputType:
2768 * OT_WIKI: only {{subst:}} templates
2769 * OT_MSG: only magic variables
2770 * OT_HTML: all templates and magic variables
2772 * @param string $tex The text to transform
2773 * @param array $args Key-value pairs representing template parameters to substitute
2774 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2777 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2778 # Prevent too big inclusions
2779 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2783 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2784 wfProfileIn( $fname );
2786 # This function is called recursively. To keep track of arguments we need a stack:
2787 array_push( $this->mArgStack
, $args );
2789 $braceCallbacks = array();
2791 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2793 if ( $this->mOutputType
!= OT_MSG
) {
2794 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2796 if ( $braceCallbacks ) {
2800 'cb' => $braceCallbacks,
2801 'min' => $argsOnly ?
3 : 2,
2802 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2806 'cb' => array(2=>null),
2811 $text = $this->replace_callback ($text, $callbacks);
2813 array_pop( $this->mArgStack
);
2815 wfProfileOut( $fname );
2820 * Replace magic variables
2823 function variableSubstitution( $matches ) {
2825 $fname = 'Parser::variableSubstitution';
2826 $varname = $wgContLang->lc($matches[1]);
2827 wfProfileIn( $fname );
2829 if ( $this->mOutputType
== OT_WIKI
) {
2830 # Do only magic variables prefixed by SUBST
2831 $mwSubst =& MagicWord
::get( 'subst' );
2832 if (!$mwSubst->matchStartAndRemove( $varname ))
2834 # Note that if we don't substitute the variable below,
2835 # we don't remove the {{subst:}} magic word, in case
2836 # it is a template rather than a magic variable.
2838 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2839 $id = $this->mVariables
[$varname];
2840 # Now check if we did really match, case sensitive or not
2841 $mw =& MagicWord
::get( $id );
2842 if ($mw->match($matches[1])) {
2843 $text = $this->getVariableValue( $id );
2844 $this->mOutput
->mContainsOldMagic
= true;
2846 $text = $matches[0];
2849 $text = $matches[0];
2851 wfProfileOut( $fname );
2856 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2857 static function createAssocArgs( $args ) {
2858 $assocArgs = array();
2860 foreach( $args as $arg ) {
2861 $eqpos = strpos( $arg, '=' );
2862 if ( $eqpos === false ) {
2863 $assocArgs[$index++
] = $arg;
2865 $name = trim( substr( $arg, 0, $eqpos ) );
2866 $value = trim( substr( $arg, $eqpos+
1 ) );
2867 if ( $value === false ) {
2870 if ( $name !== false ) {
2871 $assocArgs[$name] = $value;
2880 * Return the text of a template, after recursively
2881 * replacing any variables or templates within the template.
2883 * @param array $piece The parts of the template
2884 * $piece['text']: matched text
2885 * $piece['title']: the title, i.e. the part before the |
2886 * $piece['parts']: the parameter array
2887 * @return string the text of the template
2890 function braceSubstitution( $piece ) {
2891 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2892 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2893 wfProfileIn( $fname );
2894 wfProfileIn( __METHOD__
.'-setup' );
2897 $found = false; # $text has been filled
2898 $nowiki = false; # wiki markup in $text should be escaped
2899 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2900 $noargs = false; # Don't replace triple-brace arguments in $text
2901 $replaceHeadings = false; # Make the edit section links go to the template not the article
2902 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2903 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2904 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2906 # Title object, where $text came from
2912 # $part1 is the bit before the first |, and must contain only title characters
2913 # $args is a list of arguments, starting from index 0, not including $part1
2915 $titleText = $part1 = $piece['title'];
2916 # If the third subpattern matched anything, it will start with |
2918 if (null == $piece['parts']) {
2919 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2920 if ($replaceWith != $piece['text']) {
2921 $text = $replaceWith;
2928 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2929 wfProfileOut( __METHOD__
.'-setup' );
2932 wfProfileIn( __METHOD__
.'-modifiers' );
2934 $mwSubst =& MagicWord
::get( 'subst' );
2935 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2936 # One of two possibilities is true:
2937 # 1) Found SUBST but not in the PST phase
2938 # 2) Didn't find SUBST and in the PST phase
2939 # In either case, return without further processing
2940 $text = $piece['text'];
2947 # MSG, MSGNW and RAW
2950 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2951 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2954 # Remove obsolete MSG:
2955 $mwMsg =& MagicWord
::get( 'msg' );
2956 $mwMsg->matchStartAndRemove( $part1 );
2960 $mwRaw =& MagicWord
::get( 'raw' );
2961 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2962 $forceRawInterwiki = true;
2965 wfProfileOut( __METHOD__
.'-modifiers' );
2967 //save path level before recursing into functions & templates.
2968 $lastPathLevel = $this->mTemplatePath
;
2972 wfProfileIn( __METHOD__
. '-pfunc' );
2974 $colonPos = strpos( $part1, ':' );
2975 if ( $colonPos !== false ) {
2976 # Case sensitive functions
2977 $function = substr( $part1, 0, $colonPos );
2978 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2979 $function = $this->mFunctionSynonyms
[1][$function];
2981 # Case insensitive functions
2982 $function = strtolower( $function );
2983 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2984 $function = $this->mFunctionSynonyms
[0][$function];
2990 $funcArgs = array_map( 'trim', $args );
2991 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2992 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2995 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2999 if ( is_array( $result ) ) {
3000 if ( isset( $result[0] ) ) {
3001 $text = $linestart . $result[0];
3002 unset( $result[0] );
3005 // Extract flags into the local scope
3006 // This allows callers to set flags such as nowiki, noparse, found, etc.
3009 $text = $linestart . $result;
3013 wfProfileOut( __METHOD__
. '-pfunc' );
3016 # Template table test
3018 # Did we encounter this template already? If yes, it is in the cache
3019 # and we need to check for loops.
3020 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3023 # Infinite loop test
3024 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3028 $text = $linestart .
3029 "[[$part1]]<!-- WARNING: template loop detected -->";
3030 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3032 # set $text to cached message.
3033 $text = $linestart . $this->mTemplates
[$piece['title']];
3037 # Load from database
3039 wfProfileIn( __METHOD__
. '-loadtpl' );
3041 # declaring $subpage directly in the function call
3042 # does not work correctly with references and breaks
3043 # {{/subpage}}-style inclusions
3045 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3046 if ($subpage !== '') {
3047 $ns = $this->mTitle
->getNamespace();
3049 $title = Title
::newFromText( $part1, $ns );
3052 if ( !is_null( $title ) ) {
3053 $titleText = $title->getPrefixedText();
3054 # Check for language variants if the template is not found
3055 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3056 $wgContLang->findVariantLink($part1, $title);
3059 if ( !$title->isExternal() ) {
3060 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3061 $text = SpecialPage
::capturePath( $title );
3062 if ( is_string( $text ) ) {
3067 $this->disableCache();
3070 $articleContent = $this->fetchTemplate( $title );
3071 if ( $articleContent !== false ) {
3073 $text = $articleContent;
3074 $replaceHeadings = true;
3078 # If the title is valid but undisplayable, make a link to it
3079 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3080 $text = "[[:$titleText]]";
3083 } elseif ( $title->isTrans() ) {
3084 // Interwiki transclusion
3085 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3086 $text = $this->interwikiTransclude( $title, 'render' );
3090 $text = $this->interwikiTransclude( $title, 'raw' );
3091 $replaceHeadings = true;
3096 # Template cache array insertion
3097 # Use the original $piece['title'] not the mangled $part1, so that
3098 # modifiers such as RAW: produce separate cache entries
3101 // A special page; don't store it in the template cache.
3103 $this->mTemplates
[$piece['title']] = $text;
3105 $text = $linestart . $text;
3108 wfProfileOut( __METHOD__
. '-loadtpl' );
3111 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3112 # Error, oversize inclusion
3113 $text = $linestart .
3114 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3119 # Recursive parsing, escaping and link table handling
3120 # Only for HTML output
3121 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3122 $text = wfEscapeWikiText( $text );
3123 } elseif ( !$this->ot
['msg'] && $found ) {
3125 $assocArgs = array();
3127 # Clean up argument array
3128 $assocArgs = self
::createAssocArgs($args);
3129 # Add a new element to the templace recursion path
3130 $this->mTemplatePath
[$part1] = 1;
3134 # If there are any <onlyinclude> tags, only include them
3135 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3136 $replacer = new OnlyIncludeReplacer
;
3137 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3138 array( &$replacer, 'replace' ), $text );
3139 $text = $replacer->output
;
3141 # Remove <noinclude> sections and <includeonly> tags
3142 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3143 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3145 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3146 # Strip <nowiki>, <pre>, etc.
3147 $text = $this->strip( $text, $this->mStripState
);
3148 if ( $this->ot
['html'] ) {
3149 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3150 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3151 $text = Sanitizer
::removeHTMLcomments( $text );
3154 $text = $this->replaceVariables( $text, $assocArgs );
3156 # If the template begins with a table or block-level
3157 # element, it should be treated as beginning a new line.
3158 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3159 $text = "\n" . $text;
3161 } elseif ( !$noargs ) {
3162 # $noparse and !$noargs
3163 # Just replace the arguments, not any double-brace items
3164 # This is used for rendered interwiki transclusion
3165 $text = $this->replaceVariables( $text, $assocArgs, true );
3168 # Prune lower levels off the recursion check path
3169 $this->mTemplatePath
= $lastPathLevel;
3171 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3172 # Error, oversize inclusion
3173 $text = $linestart .
3174 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3180 wfProfileOut( $fname );
3181 return $piece['text'];
3183 wfProfileIn( __METHOD__
. '-placeholders' );
3185 # Replace raw HTML by a placeholder
3186 # Add a blank line preceding, to prevent it from mucking up
3187 # immediately preceding headings
3188 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3190 # replace ==section headers==
3191 # XXX this needs to go away once we have a better parser.
3192 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3193 if( !is_null( $title ) )
3194 $encodedname = base64_encode($title->getPrefixedDBkey());
3196 $encodedname = base64_encode("");
3197 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3198 PREG_SPLIT_DELIM_CAPTURE
);
3200 $nsec = $headingOffset;
3201 for( $i = 0; $i < count($m); $i +
= 2 ) {
3203 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3205 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3210 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3211 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3212 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3218 wfProfileOut( __METHOD__
. '-placeholders' );
3221 # Prune lower levels off the recursion check path
3222 $this->mTemplatePath
= $lastPathLevel;
3225 wfProfileOut( $fname );
3226 return $piece['text'];
3228 wfProfileOut( $fname );
3234 * Fetch the unparsed text of a template and register a reference to it.
3236 function fetchTemplate( $title ) {
3238 // Loop to fetch the article, with up to 1 redirect
3239 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3240 $rev = Revision
::newFromTitle( $title );
3241 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3245 $text = $rev->getText();
3246 if ( $text === false ) {
3250 $title = Title
::newFromRedirect( $text );
3256 * Transclude an interwiki link.
3258 function interwikiTransclude( $title, $action ) {
3259 global $wgEnableScaryTranscluding;
3261 if (!$wgEnableScaryTranscluding)
3262 return wfMsg('scarytranscludedisabled');
3264 $url = $title->getFullUrl( "action=$action" );
3266 if (strlen($url) > 255)
3267 return wfMsg('scarytranscludetoolong');
3268 return $this->fetchScaryTemplateMaybeFromCache($url);
3271 function fetchScaryTemplateMaybeFromCache($url) {
3272 global $wgTranscludeCacheExpiry;
3273 $dbr =& wfGetDB(DB_SLAVE
);
3274 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3275 array('tc_url' => $url));
3277 $time = $obj->tc_time
;
3278 $text = $obj->tc_contents
;
3279 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3284 $text = Http
::get($url);
3286 return wfMsg('scarytranscludefailed', $url);
3288 $dbw =& wfGetDB(DB_MASTER
);
3289 $dbw->replace('transcache', array('tc_url'), array(
3291 'tc_time' => time(),
3292 'tc_contents' => $text));
3298 * Triple brace replacement -- used for template arguments
3301 function argSubstitution( $matches ) {
3302 $arg = trim( $matches['title'] );
3303 $text = $matches['text'];
3304 $inputArgs = end( $this->mArgStack
);
3306 if ( array_key_exists( $arg, $inputArgs ) ) {
3307 $text = $inputArgs[$arg];
3308 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3309 null != $matches['parts'] && count($matches['parts']) > 0) {
3310 $text = $matches['parts'][0];
3312 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3313 $text = $matches['text'] .
3314 '<!-- WARNING: argument omitted, expansion size too large -->';
3321 * Increment an include size counter
3323 * @param string $type The type of expansion
3324 * @param integer $size The size of the text
3325 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3327 function incrementIncludeSize( $type, $size ) {
3328 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3331 $this->mIncludeSizes
[$type] +
= $size;
3337 * Detect __NOGALLERY__ magic word and set a placeholder
3339 function stripNoGallery( &$text ) {
3340 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3342 $mw = MagicWord
::get( 'nogallery' );
3343 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3347 * Detect __TOC__ magic word and set a placeholder
3349 function stripToc( $text ) {
3350 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3352 $mw = MagicWord
::get( 'notoc' );
3353 if( $mw->matchAndRemove( $text ) ) {
3354 $this->mShowToc
= false;
3357 $mw = MagicWord
::get( 'toc' );
3358 if( $mw->match( $text ) ) {
3359 $this->mShowToc
= true;
3360 $this->mForceTocPosition
= true;
3362 // Set a placeholder. At the end we'll fill it in with the TOC.
3363 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3365 // Only keep the first one.
3366 $text = $mw->replace( '', $text );
3372 * This function accomplishes several tasks:
3373 * 1) Auto-number headings if that option is enabled
3374 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3375 * 3) Add a Table of contents on the top for users who have enabled the option
3376 * 4) Auto-anchor headings
3378 * It loops through all headlines, collects the necessary data, then splits up the
3379 * string and re-inserts the newly formatted headlines.
3381 * @param string $text
3382 * @param boolean $isMain
3385 function formatHeadings( $text, $isMain=true ) {
3386 global $wgMaxTocLevel, $wgContLang;
3388 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3389 if( !$this->mTitle
->userCanEdit() ) {
3392 $showEditLink = $this->mOptions
->getEditSection();
3395 # Inhibit editsection links if requested in the page
3396 $esw =& MagicWord
::get( 'noeditsection' );
3397 if( $esw->matchAndRemove( $text ) ) {
3401 # Get all headlines for numbering them and adding funky stuff like [edit]
3402 # links - this is for later, but we need the number of headlines right now
3404 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3406 # if there are fewer than 4 headlines in the article, do not show TOC
3407 # unless it's been explicitly enabled.
3408 $enoughToc = $this->mShowToc
&&
3409 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3411 # Allow user to stipulate that a page should have a "new section"
3412 # link added via __NEWSECTIONLINK__
3413 $mw =& MagicWord
::get( 'newsectionlink' );
3414 if( $mw->matchAndRemove( $text ) )
3415 $this->mOutput
->setNewSection( true );
3417 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3418 # override above conditions and always show TOC above first header
3419 $mw =& MagicWord
::get( 'forcetoc' );
3420 if ($mw->matchAndRemove( $text ) ) {
3421 $this->mShowToc
= true;
3425 # Never ever show TOC if no headers
3426 if( $numMatches < 1 ) {
3430 # We need this to perform operations on the HTML
3431 $sk =& $this->mOptions
->getSkin();
3435 $sectionCount = 0; # headlineCount excluding template sections
3437 # Ugh .. the TOC should have neat indentation levels which can be
3438 # passed to the skin functions. These are determined here
3442 $sublevelCount = array();
3443 $levelCount = array();
3450 foreach( $matches[3] as $headline ) {
3452 $templatetitle = '';
3453 $templatesection = 0;
3456 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3458 $templatetitle = base64_decode($mat[1]);
3459 $templatesection = 1 +
(int)base64_decode($mat[2]);
3460 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3464 $prevlevel = $level;
3465 $prevtoclevel = $toclevel;
3467 $level = $matches[1][$headlineCount];
3469 if( $doNumberHeadings ||
$enoughToc ) {
3471 if ( $level > $prevlevel ) {
3472 # Increase TOC level
3474 $sublevelCount[$toclevel] = 0;
3475 if( $toclevel<$wgMaxTocLevel ) {
3476 $toc .= $sk->tocIndent();
3479 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3480 # Decrease TOC level, find level to jump to
3482 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3483 # Can only go down to level 1
3486 for ($i = $toclevel; $i > 0; $i--) {
3487 if ( $levelCount[$i] == $level ) {
3488 # Found last matching level
3492 elseif ( $levelCount[$i] < $level ) {
3493 # Found first matching level below current level
3499 if( $toclevel<$wgMaxTocLevel ) {
3500 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3504 # No change in level, end TOC line
3505 if( $toclevel<$wgMaxTocLevel ) {
3506 $toc .= $sk->tocLineEnd();
3510 $levelCount[$toclevel] = $level;
3512 # count number of headlines for each level
3513 @$sublevelCount[$toclevel]++
;
3515 for( $i = 1; $i <= $toclevel; $i++
) {
3516 if( !empty( $sublevelCount[$i] ) ) {
3520 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3526 # The canonized header is a version of the header text safe to use for links
3527 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3528 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3530 # Remove link placeholders by the link text.
3531 # <!--LINK number-->
3533 # link text with suffix
3534 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3535 "\$this->mLinkHolders['texts'][\$1]",
3536 $canonized_headline );
3537 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3538 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3539 $canonized_headline );
3542 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3543 $tocline = trim( $canonized_headline );
3544 # Save headline for section edit hint before it's escaped
3545 $headline_hint = trim( $canonized_headline );
3546 $canonized_headline = Sanitizer
::escapeId( $tocline );
3547 $refers[$headlineCount] = $canonized_headline;
3549 # count how many in assoc. array so we can track dupes in anchors
3550 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3551 $refcount[$headlineCount]=$refers[$canonized_headline];
3553 # Don't number the heading if it is the only one (looks silly)
3554 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3555 # the two are different if the line contains a link
3556 $headline=$numbering . ' ' . $headline;
3559 # Create the anchor for linking from the TOC to the section
3560 $anchor = $canonized_headline;
3561 if($refcount[$headlineCount] > 1 ) {
3562 $anchor .= '_' . $refcount[$headlineCount];
3564 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3565 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3567 # give headline the correct <h#> tag
3568 $head[$headlineCount] = "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3570 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3571 if ( empty( $head[$headlineCount] ) ) {
3572 $head[$headlineCount] = '';
3575 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3577 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3579 // Yes, the headline logically goes before the edit section. Why isn't it there
3580 // in source? Ask the CSS people. The float gets screwed up if you do that.
3581 // This might be moved to before the editsection at some point so that it will
3582 // display a bit more prettily without CSS, so please don't rely on the order.
3583 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3591 if( $toclevel<$wgMaxTocLevel ) {
3592 $toc .= $sk->tocUnindent( $toclevel - 1 );
3594 $toc = $sk->tocList( $toc );
3597 # split up and insert constructed headlines
3599 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3602 foreach( $blocks as $block ) {
3603 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3604 # This is the [edit] link that appears for the top block of text when
3605 # section editing is enabled
3607 # Disabled because it broke block formatting
3608 # For example, a bullet point in the top line
3609 # $full .= $sk->editSectionLink(0);
3612 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3613 # Top anchor now in skin
3617 if( !empty( $head[$i] ) ) {
3622 if( $this->mForceTocPosition
) {
3623 return str_replace( '<!--MWTOC-->', $toc, $full );
3630 * Transform wiki markup when saving a page by doing \r\n -> \n
3631 * conversion, substitting signatures, {{subst:}} templates, etc.
3633 * @param string $text the text to transform
3634 * @param Title &$title the Title object for the current article
3635 * @param User &$user the User object describing the current user
3636 * @param ParserOptions $options parsing options
3637 * @param bool $clearState whether to clear the parser state first
3638 * @return string the altered wiki markup
3641 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3642 $this->mOptions
= $options;
3643 $this->mTitle
=& $title;
3644 $this->setOutputType( OT_WIKI
);
3646 if ( $clearState ) {
3647 $this->clearState();
3650 $stripState = new StripState
;
3654 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3655 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3656 $text = $this->pstPass2( $text, $stripState, $user );
3657 $text = $stripState->unstripBoth( $text );
3662 * Pre-save transform helper function
3665 function pstPass2( $text, &$stripState, $user ) {
3666 global $wgContLang, $wgLocaltimezone;
3668 /* Note: This is the timestamp saved as hardcoded wikitext to
3669 * the database, we use $wgContLang here in order to give
3670 * everyone the same signature and use the default one rather
3671 * than the one selected in each user's preferences.
3673 if ( isset( $wgLocaltimezone ) ) {
3674 $oldtz = getenv( 'TZ' );
3675 putenv( 'TZ='.$wgLocaltimezone );
3677 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3678 ' (' . date( 'T' ) . ')';
3679 if ( isset( $wgLocaltimezone ) ) {
3680 putenv( 'TZ='.$oldtz );
3683 # Variable replacement
3684 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3685 $text = $this->replaceVariables( $text );
3687 # Strip out <nowiki> etc. added via replaceVariables
3688 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3691 $sigText = $this->getUserSig( $user );
3692 $text = strtr( $text, array(
3694 '~~~~' => "$sigText $d",
3698 # Context links: [[|name]] and [[name (context)|]]
3700 global $wgLegalTitleChars;
3701 $tc = "[$wgLegalTitleChars]";
3702 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3704 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3705 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3706 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3708 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3709 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3710 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3712 $t = $this->mTitle
->getText();
3714 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3715 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3716 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3717 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3719 # if there's no context, don't bother duplicating the title
3720 $text = preg_replace( $p2, '[[\\1]]', $text );
3723 # Trim trailing whitespace
3724 # __END__ tag allows for trailing
3725 # whitespace to be deliberately included
3726 $text = rtrim( $text );
3727 $mw =& MagicWord
::get( 'end' );
3728 $mw->matchAndRemove( $text );
3734 * Fetch the user's signature text, if any, and normalize to
3735 * validated, ready-to-insert wikitext.
3741 function getUserSig( &$user ) {
3742 $username = $user->getName();
3743 $nickname = $user->getOption( 'nickname' );
3744 $nickname = $nickname === '' ?
$username : $nickname;
3746 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3747 # Sig. might contain markup; validate this
3748 if( $this->validateSig( $nickname ) !== false ) {
3749 # Validated; clean up (if needed) and return it
3750 return $this->cleanSig( $nickname, true );
3752 # Failed to validate; fall back to the default
3753 $nickname = $username;
3754 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3758 // Make sure nickname doesnt get a sig in a sig
3759 $nickname = $this->cleanSigInSig( $nickname );
3761 # If we're still here, make it a link to the user page
3762 $userpage = $user->getUserPage();
3763 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3767 * Check that the user's signature contains no bad XML
3769 * @param string $text
3770 * @return mixed An expanded string, or false if invalid.
3772 function validateSig( $text ) {
3773 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3777 * Clean up signature text
3779 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3780 * 2) Substitute all transclusions
3782 * @param string $text
3783 * @param $parsing Whether we're cleaning (preferences save) or parsing
3784 * @return string Signature text
3786 function cleanSig( $text, $parsing = false ) {
3788 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3790 $substWord = MagicWord
::get( 'subst' );
3791 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3792 $substText = '{{' . $substWord->getSynonym( 0 );
3794 $text = preg_replace( $substRegex, $substText, $text );
3795 $text = $this->cleanSigInSig( $text );
3796 $text = $this->replaceVariables( $text );
3798 $this->clearState();
3803 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3804 * @param string $text
3805 * @return string Signature text with /~{3,5}/ removed
3807 function cleanSigInSig( $text ) {
3808 $text = preg_replace( '/~{3,5}/', '', $text );
3813 * Set up some variables which are usually set up in parse()
3814 * so that an external function can call some class members with confidence
3817 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3818 $this->mTitle
=& $title;
3819 $this->mOptions
= $options;
3820 $this->setOutputType( $outputType );
3821 if ( $clearState ) {
3822 $this->clearState();
3827 * Transform a MediaWiki message by replacing magic variables.
3829 * @param string $text the text to transform
3830 * @param ParserOptions $options options
3831 * @return string the text with variables substituted
3834 function transformMsg( $text, $options ) {
3836 static $executing = false;
3838 $fname = "Parser::transformMsg";
3840 # Guard against infinite recursion
3846 wfProfileIn($fname);
3849 $this->mTitle
= $wgTitle;
3851 $this->mTitle
= Title
::newFromText('msg');
3853 $this->mOptions
= $options;
3854 $this->setOutputType( OT_MSG
);
3855 $this->clearState();
3856 $text = $this->replaceVariables( $text );
3859 wfProfileOut($fname);
3864 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3865 * The callback should have the following form:
3866 * function myParserHook( $text, $params, &$parser ) { ... }
3868 * Transform and return $text. Use $parser for any required context, e.g. use
3869 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3873 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3874 * @param mixed $callback The callback function (and object) to use for the tag
3876 * @return The old value of the mTagHooks array associated with the hook
3878 function setHook( $tag, $callback ) {
3879 $tag = strtolower( $tag );
3880 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3881 $this->mTagHooks
[$tag] = $callback;
3887 * Create a function, e.g. {{sum:1|2|3}}
3888 * The callback function should have the form:
3889 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3891 * The callback may either return the text result of the function, or an array with the text
3892 * in element 0, and a number of flags in the other elements. The names of the flags are
3893 * specified in the keys. Valid flags are:
3894 * found The text returned is valid, stop processing the template. This
3896 * nowiki Wiki markup in the return value should be escaped
3897 * noparse Unsafe HTML tags should not be stripped, etc.
3898 * noargs Don't replace triple-brace arguments in the return value
3899 * isHTML The returned text is HTML, armour it against wikitext transformation
3903 * @param string $id The magic word ID
3904 * @param mixed $callback The callback function (and object) to use
3905 * @param integer $flags a combination of the following flags:
3906 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3908 * @return The old callback function for this name, if any
3910 function setFunctionHook( $id, $callback, $flags = 0 ) {
3911 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3912 $this->mFunctionHooks
[$id] = $callback;
3914 # Add to function cache
3915 $mw = MagicWord
::get( $id );
3917 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3919 $synonyms = $mw->getSynonyms();
3920 $sensitive = intval( $mw->isCaseSensitive() );
3922 foreach ( $synonyms as $syn ) {
3924 if ( !$sensitive ) {
3925 $syn = strtolower( $syn );
3928 if ( !( $flags & SFH_NO_HASH
) ) {
3931 # Remove trailing colon
3932 if ( substr( $syn, -1, 1 ) == ':' ) {
3933 $syn = substr( $syn, 0, -1 );
3935 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3941 * Get all registered function hook identifiers
3945 function getFunctionHooks() {
3946 return array_keys( $this->mFunctionHooks
);
3950 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3951 * Placeholders created in Skin::makeLinkObj()
3952 * Returns an array of links found, indexed by PDBK:
3956 * $options is a bit field, RLH_FOR_UPDATE to select for update
3958 function replaceLinkHolders( &$text, $options = 0 ) {
3962 $fname = 'Parser::replaceLinkHolders';
3963 wfProfileIn( $fname );
3967 $sk =& $this->mOptions
->getSkin();
3968 $linkCache =& LinkCache
::singleton();
3970 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3971 wfProfileIn( $fname.'-check' );
3972 $dbr =& wfGetDB( DB_SLAVE
);
3973 $page = $dbr->tableName( 'page' );
3974 $threshold = $wgUser->getOption('stubthreshold');
3977 asort( $this->mLinkHolders
['namespaces'] );
3982 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3984 $title = $this->mLinkHolders
['titles'][$key];
3986 # Skip invalid entries.
3987 # Result will be ugly, but prevents crash.
3988 if ( is_null( $title ) ) {
3991 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3993 # Check if it's a static known link, e.g. interwiki
3994 if ( $title->isAlwaysKnown() ) {
3995 $colours[$pdbk] = 1;
3996 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3997 $colours[$pdbk] = 1;
3998 $this->mOutput
->addLink( $title, $id );
3999 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4000 $colours[$pdbk] = 0;
4002 # Not in the link cache, add it to the query
4003 if ( !isset( $current ) ) {
4005 $query = "SELECT page_id, page_namespace, page_title";
4006 if ( $threshold > 0 ) {
4007 $query .= ', page_len, page_is_redirect';
4009 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4010 } elseif ( $current != $ns ) {
4012 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4017 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4022 if ( $options & RLH_FOR_UPDATE
) {
4023 $query .= ' FOR UPDATE';
4026 $res = $dbr->query( $query, $fname );
4028 # Fetch data and form into an associative array
4029 # non-existent = broken
4032 while ( $s = $dbr->fetchObject($res) ) {
4033 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4034 $pdbk = $title->getPrefixedDBkey();
4035 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4036 $this->mOutput
->addLink( $title, $s->page_id
);
4038 if ( $threshold > 0 ) {
4039 $size = $s->page_len
;
4040 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4041 $colours[$pdbk] = 1;
4043 $colours[$pdbk] = 2;
4046 $colours[$pdbk] = 1;
4050 wfProfileOut( $fname.'-check' );
4052 # Do a second query for different language variants of links and categories
4053 if($wgContLang->hasVariants()){
4054 $linkBatch = new LinkBatch();
4055 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4056 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4057 $varCategories = array(); // category replacements oldDBkey => newDBkey
4059 $categories = $this->mOutput
->getCategoryLinks();
4061 // Add variants of links to link batch
4062 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4063 $title = $this->mLinkHolders
['titles'][$key];
4064 if ( is_null( $title ) )
4067 $pdbk = $title->getPrefixedDBkey();
4068 $titleText = $title->getText();
4070 // generate all variants of the link title text
4071 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4073 // if link was not found (in first query), add all variants to query
4074 if ( !isset($colours[$pdbk]) ){
4075 foreach($allTextVariants as $textVariant){
4076 if($textVariant != $titleText){
4077 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4078 if(is_null($variantTitle)) continue;
4079 $linkBatch->addObj( $variantTitle );
4080 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4086 // process categories, check if a category exists in some variant
4087 foreach( $categories as $category){
4088 $variants = $wgContLang->convertLinkToAllVariants($category);
4089 foreach($variants as $variant){
4090 if($variant != $category){
4091 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4092 if(is_null($variantTitle)) continue;
4093 $linkBatch->addObj( $variantTitle );
4094 $categoryMap[$variant] = $category;
4100 if(!$linkBatch->isEmpty()){
4102 $titleClause = $linkBatch->constructSet('page', $dbr);
4104 $variantQuery = "SELECT page_id, page_namespace, page_title";
4105 if ( $threshold > 0 ) {
4106 $variantQuery .= ', page_len, page_is_redirect';
4109 $variantQuery .= " FROM $page WHERE $titleClause";
4110 if ( $options & RLH_FOR_UPDATE
) {
4111 $variantQuery .= ' FOR UPDATE';
4114 $varRes = $dbr->query( $variantQuery, $fname );
4116 // for each found variants, figure out link holders and replace
4117 while ( $s = $dbr->fetchObject($varRes) ) {
4119 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4120 $varPdbk = $variantTitle->getPrefixedDBkey();
4121 $vardbk = $variantTitle->getDBkey();
4123 $holderKeys = array();
4124 if(isset($variantMap[$varPdbk])){
4125 $holderKeys = $variantMap[$varPdbk];
4126 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4127 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4130 // loop over link holders
4131 foreach($holderKeys as $key){
4132 $title = $this->mLinkHolders
['titles'][$key];
4133 if ( is_null( $title ) ) continue;
4135 $pdbk = $title->getPrefixedDBkey();
4137 if(!isset($colours[$pdbk])){
4138 // found link in some of the variants, replace the link holder data
4139 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4140 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4142 // set pdbk and colour
4143 $pdbks[$key] = $varPdbk;
4144 if ( $threshold > 0 ) {
4145 $size = $s->page_len
;
4146 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4147 $colours[$varPdbk] = 1;
4149 $colours[$varPdbk] = 2;
4153 $colours[$varPdbk] = 1;
4158 // check if the object is a variant of a category
4159 if(isset($categoryMap[$vardbk])){
4160 $oldkey = $categoryMap[$vardbk];
4161 if($oldkey != $vardbk)
4162 $varCategories[$oldkey]=$vardbk;
4166 // rebuild the categories in original order (if there are replacements)
4167 if(count($varCategories)>0){
4169 $originalCats = $this->mOutput
->getCategories();
4170 foreach($originalCats as $cat => $sortkey){
4171 // make the replacement
4172 if( array_key_exists($cat,$varCategories) )
4173 $newCats[$varCategories[$cat]] = $sortkey;
4174 else $newCats[$cat] = $sortkey;
4176 $this->mOutput
->setCategoryLinks($newCats);
4181 # Construct search and replace arrays
4182 wfProfileIn( $fname.'-construct' );
4183 $replacePairs = array();
4184 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4185 $pdbk = $pdbks[$key];
4186 $searchkey = "<!--LINK $key-->";
4187 $title = $this->mLinkHolders
['titles'][$key];
4188 if ( empty( $colours[$pdbk] ) ) {
4189 $linkCache->addBadLinkObj( $title );
4190 $colours[$pdbk] = 0;
4191 $this->mOutput
->addLink( $title, 0 );
4192 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4193 $this->mLinkHolders
['texts'][$key],
4194 $this->mLinkHolders
['queries'][$key] );
4195 } elseif ( $colours[$pdbk] == 1 ) {
4196 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4197 $this->mLinkHolders
['texts'][$key],
4198 $this->mLinkHolders
['queries'][$key] );
4199 } elseif ( $colours[$pdbk] == 2 ) {
4200 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4201 $this->mLinkHolders
['texts'][$key],
4202 $this->mLinkHolders
['queries'][$key] );
4205 $replacer = new HashtableReplacer( $replacePairs, 1 );
4206 wfProfileOut( $fname.'-construct' );
4209 wfProfileIn( $fname.'-replace' );
4210 $text = preg_replace_callback(
4211 '/(<!--LINK .*?-->)/',
4215 wfProfileOut( $fname.'-replace' );
4218 # Now process interwiki link holders
4219 # This is quite a bit simpler than internal links
4220 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4221 wfProfileIn( $fname.'-interwiki' );
4222 # Make interwiki link HTML
4223 $replacePairs = array();
4224 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4225 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4226 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4228 $replacer = new HashtableReplacer( $replacePairs, 1 );
4230 $text = preg_replace_callback(
4231 '/<!--IWLINK (.*?)-->/',
4234 wfProfileOut( $fname.'-interwiki' );
4237 wfProfileOut( $fname );
4242 * Replace <!--LINK--> link placeholders with plain text of links
4243 * (not HTML-formatted).
4244 * @param string $text
4247 function replaceLinkHoldersText( $text ) {
4248 $fname = 'Parser::replaceLinkHoldersText';
4249 wfProfileIn( $fname );
4251 $text = preg_replace_callback(
4252 '/<!--(LINK|IWLINK) (.*?)-->/',
4253 array( &$this, 'replaceLinkHoldersTextCallback' ),
4256 wfProfileOut( $fname );
4261 * @param array $matches
4265 function replaceLinkHoldersTextCallback( $matches ) {
4266 $type = $matches[1];
4268 if( $type == 'LINK' ) {
4269 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4270 return $this->mLinkHolders
['texts'][$key];
4272 } elseif( $type == 'IWLINK' ) {
4273 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4274 return $this->mInterwikiLinkHolders
['texts'][$key];
4281 * Tag hook handler for 'pre'.
4283 function renderPreTag( $text, $attribs ) {
4284 // Backwards-compatibility hack
4285 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4287 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4288 return wfOpenElement( 'pre', $attribs ) .
4289 Xml
::escapeTagsOnly( $content ) .
4294 * Renders an image gallery from a text with one line per image.
4295 * text labels may be given by using |-style alternative text. E.g.
4296 * Image:one.jpg|The number "1"
4297 * Image:tree.jpg|A tree
4298 * given as text will return the HTML of a gallery with two images,
4299 * labeled 'The number "1"' and
4302 function renderImageGallery( $text, $params ) {
4303 $ig = new ImageGallery();
4304 $ig->setShowBytes( false );
4305 $ig->setShowFilename( false );
4307 $ig->useSkin( $this->mOptions
->getSkin() );
4309 if( isset( $params['caption'] ) ) {
4310 $caption = $params['caption'];
4311 $caption = htmlspecialchars( $caption );
4312 $caption = $this->replaceInternalLinks( $caption );
4313 $ig->setCaptionHtml( $caption );
4316 $lines = explode( "\n", $text );
4317 foreach ( $lines as $line ) {
4318 # match lines like these:
4319 # Image:someimage.jpg|This is some image
4321 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4323 if ( count( $matches ) == 0 ) {
4326 $tp = Title
::newFromText( $matches[1] );
4328 if( is_null( $nt ) ) {
4329 # Bogus title. Ignore these so we don't bomb out later.
4332 if ( isset( $matches[3] ) ) {
4333 $label = $matches[3];
4338 $pout = $this->parse( $label,
4341 false, // Strip whitespace...?
4342 false // Don't clear state!
4344 $html = $pout->getText();
4346 $ig->add( new Image( $nt ), $html );
4348 # Only add real images (bug #5586)
4349 if ( $nt->getNamespace() == NS_IMAGE
) {
4350 $this->mOutput
->addImage( $nt->getDBkey() );
4353 return $ig->toHTML();
4357 * Parse image options text and use it to make an image
4359 function makeImage( $nt, $options ) {
4360 global $wgUseImageResize, $wgDjvuRenderer;
4364 # Check if the options text is of the form "options|alt text"
4366 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4367 # * left no resizing, just left align. label is used for alt= only
4368 # * right same, but right aligned
4369 # * none same, but not aligned
4370 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4371 # * center center the image
4372 # * framed Keep original image size, no magnify-button.
4374 $part = explode( '|', $options);
4376 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4377 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4378 $mwLeft =& MagicWord
::get( 'img_left' );
4379 $mwRight =& MagicWord
::get( 'img_right' );
4380 $mwNone =& MagicWord
::get( 'img_none' );
4381 $mwWidth =& MagicWord
::get( 'img_width' );
4382 $mwCenter =& MagicWord
::get( 'img_center' );
4383 $mwFramed =& MagicWord
::get( 'img_framed' );
4384 $mwPage =& MagicWord
::get( 'img_page' );
4387 $width = $height = $framed = $thumb = false;
4389 $manual_thumb = '' ;
4391 foreach( $part as $val ) {
4392 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4394 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4395 # use manually specified thumbnail
4397 $manual_thumb = $match;
4398 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4399 # remember to set an alignment, don't render immediately
4401 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4402 # remember to set an alignment, don't render immediately
4404 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4405 # remember to set an alignment, don't render immediately
4407 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4408 # remember to set an alignment, don't render immediately
4410 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4411 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4412 # Select a page in a multipage document
4414 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4415 wfDebug( "img_width match: $match\n" );
4416 # $match is the image width in pixels
4418 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4419 $width = intval( $m[1] );
4420 $height = intval( $m[2] );
4422 $width = intval($match);
4424 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4430 # Strip bad stuff out of the alt text
4431 $alt = $this->replaceLinkHoldersText( $caption );
4433 # make sure there are no placeholders in thumbnail attributes
4434 # that are later expanded to html- so expand them now and
4436 $alt = $this->mStripState
->unstripBoth( $alt );
4437 $alt = Sanitizer
::stripAllTags( $alt );
4439 # Linker does the rest
4440 $sk =& $this->mOptions
->getSkin();
4441 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4445 * Set a flag in the output object indicating that the content is dynamic and
4446 * shouldn't be cached.
4448 function disableCache() {
4449 wfDebug( "Parser output marked as uncacheable.\n" );
4450 $this->mOutput
->mCacheTime
= -1;
4454 * Callback from the Sanitizer for expanding items found in HTML attribute
4455 * values, so they can be safely tested and escaped.
4456 * @param string $text
4457 * @param array $args
4461 function attributeStripCallback( &$text, $args ) {
4462 $text = $this->replaceVariables( $text, $args );
4463 $text = $this->mStripState
->unstripBoth( $text );
4472 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4473 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4474 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4480 function getTags() { return array_keys( $this->mTagHooks
); }
4485 * Break wikitext input into sections, and either pull or replace
4486 * some particular section's text.
4488 * External callers should use the getSection and replaceSection methods.
4490 * @param $text Page wikitext
4491 * @param $section Numbered section. 0 pulls the text before the first
4492 * heading; other numbers will pull the given section
4493 * along with its lower-level subsections.
4494 * @param $mode One of "get" or "replace"
4495 * @param $newtext Replacement text for section data.
4496 * @return string for "get", the extracted section text.
4497 * for "replace", the whole page with the section replaced.
4499 private function extractSections( $text, $section, $mode, $newtext='' ) {
4500 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4501 # comments to be stripped as well)
4502 $stripState = new StripState
;
4504 $oldOutputType = $this->mOutputType
;
4505 $oldOptions = $this->mOptions
;
4506 $this->mOptions
= new ParserOptions();
4507 $this->setOutputType( OT_WIKI
);
4509 $striptext = $this->strip( $text, $stripState, true );
4511 $this->setOutputType( $oldOutputType );
4512 $this->mOptions
= $oldOptions;
4514 # now that we can be sure that no pseudo-sections are in the source,
4515 # split it up by section
4516 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4517 $comment = "(?:$uniq-!--.*?QINU)";
4522 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4524 (=+) # Should this be limited to 6?
4525 .+? # Section title...
4526 \\2 # Ending = count must match start
4533 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4540 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4541 (=+) # Should this be limited to 6?
4542 .+? # Section title...
4543 \\2 # Ending = count must match start
4544 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4553 PREG_SPLIT_DELIM_CAPTURE
);
4555 if( $mode == "get" ) {
4556 if( $section == 0 ) {
4557 // "Section 0" returns the content before any other section.
4562 } elseif( $mode == "replace" ) {
4563 if( $section == 0 ) {
4564 $rv = $newtext . "\n\n";
4573 for( $index = 1; $index < count( $secs ); ) {
4574 $headerLine = $secs[$index++
];
4575 if( $secs[$index] ) {
4577 $headerLevel = strlen( $secs[$index++
] );
4581 $headerLevel = intval( $secs[$index++
] );
4583 $content = $secs[$index++
];
4586 if( $mode == "get" ) {
4587 if( $count == $section ) {
4588 $rv = $headerLine . $content;
4589 $sectionLevel = $headerLevel;
4590 } elseif( $count > $section ) {
4591 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4592 $rv .= $headerLine . $content;
4594 // Broke out to a higher-level section
4598 } elseif( $mode == "replace" ) {
4599 if( $count < $section ) {
4600 $rv .= $headerLine . $content;
4601 } elseif( $count == $section ) {
4602 $rv .= $newtext . "\n\n";
4603 $sectionLevel = $headerLevel;
4604 } elseif( $count > $section ) {
4605 if( $headerLevel <= $sectionLevel ) {
4606 // Passed the section's sub-parts.
4610 $rv .= $headerLine . $content;
4615 # reinsert stripped tags
4616 $rv = trim( $stripState->unstripBoth( $rv ) );
4621 * This function returns the text of a section, specified by a number ($section).
4622 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4623 * the first section before any such heading (section 0).
4625 * If a section contains subsections, these are also returned.
4627 * @param $text String: text to look in
4628 * @param $section Integer: section number
4629 * @return string text of the requested section
4631 function getSection( $text, $section ) {
4632 return $this->extractSections( $text, $section, "get" );
4635 function replaceSection( $oldtext, $section, $text ) {
4636 return $this->extractSections( $oldtext, $section, "replace", $text );
4640 * Get the timestamp associated with the current revision, adjusted for
4641 * the default server-local timestamp
4643 function getRevisionTimestamp() {
4644 if ( is_null( $this->mRevisionTimestamp
) ) {
4645 wfProfileIn( __METHOD__
);
4647 $dbr =& wfGetDB( DB_SLAVE
);
4648 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4649 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4651 // Normalize timestamp to internal MW format for timezone processing.
4652 // This has the added side-effect of replacing a null value with
4653 // the current time, which gives us more sensible behavior for
4655 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4657 // The cryptic '' timezone parameter tells to use the site-default
4658 // timezone offset instead of the user settings.
4660 // Since this value will be saved into the parser cache, served
4661 // to other users, and potentially even used inside links and such,
4662 // it needs to be consistent for all visitors.
4663 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4665 wfProfileOut( __METHOD__
);
4667 return $this->mRevisionTimestamp
;
4671 * Mutator for $mDefaultSort
4673 * @param $sort New value
4675 public function setDefaultSort( $sort ) {
4676 $this->mDefaultSort
= $sort;
4680 * Accessor for $mDefaultSort
4681 * Will use the title/prefixed title if none is set
4685 public function getDefaultSort() {
4686 if( $this->mDefaultSort
!== false ) {
4687 return $this->mDefaultSort
;
4689 return $this->mTitle
->getNamespace() == NS_CATEGORY
4690 ?
$this->mTitle
->getText()
4691 : $this->mTitle
->getPrefixedText();
4699 * @package MediaWiki
4703 var $mText, # The output text
4704 $mLanguageLinks, # List of the full text of language links, in the order they appear
4705 $mCategories, # Map of category names to sort keys
4706 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4707 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4708 $mVersion, # Compatibility check
4709 $mTitleText, # title text of the chosen language variant
4710 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4711 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4712 $mImages, # DB keys of the images used, in the array key only
4713 $mExternalLinks, # External link URLs, in the key only
4714 $mHTMLtitle, # Display HTML title
4715 $mSubtitle, # Additional subtitle
4716 $mNewSection, # Show a new section link?
4717 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4719 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4720 $containsOldMagic = false, $titletext = '' )
4722 $this->mText
= $text;
4723 $this->mLanguageLinks
= $languageLinks;
4724 $this->mCategories
= $categoryLinks;
4725 $this->mContainsOldMagic
= $containsOldMagic;
4726 $this->mCacheTime
= '';
4727 $this->mVersion
= MW_PARSER_VERSION
;
4728 $this->mTitleText
= $titletext;
4729 $this->mLinks
= array();
4730 $this->mTemplates
= array();
4731 $this->mImages
= array();
4732 $this->mExternalLinks
= array();
4733 $this->mHTMLtitle
= "" ;
4734 $this->mSubtitle
= "" ;
4735 $this->mNewSection
= false;
4736 $this->mNoGallery
= false;
4739 function getText() { return $this->mText
; }
4740 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4741 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4742 function &getCategories() { return $this->mCategories
; }
4743 function getCacheTime() { return $this->mCacheTime
; }
4744 function getTitleText() { return $this->mTitleText
; }
4745 function &getLinks() { return $this->mLinks
; }
4746 function &getTemplates() { return $this->mTemplates
; }
4747 function &getImages() { return $this->mImages
; }
4748 function &getExternalLinks() { return $this->mExternalLinks
; }
4749 function getNoGallery() { return $this->mNoGallery
; }
4750 function getSubtitle() { return $this->mSubtitle
; }
4752 function containsOldMagic() { return $this->mContainsOldMagic
; }
4753 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4754 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4755 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4756 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4757 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4758 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4759 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4761 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4762 function addImage( $name ) { $this->mImages
[$name] = 1; }
4763 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4764 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4766 function setNewSection( $value ) {
4767 $this->mNewSection
= (bool)$value;
4769 function getNewSection() {
4770 return (bool)$this->mNewSection
;
4773 function addLink( $title, $id = null ) {
4774 $ns = $title->getNamespace();
4775 $dbk = $title->getDBkey();
4776 if ( !isset( $this->mLinks
[$ns] ) ) {
4777 $this->mLinks
[$ns] = array();
4779 if ( is_null( $id ) ) {
4780 $id = $title->getArticleID();
4782 $this->mLinks
[$ns][$dbk] = $id;
4785 function addTemplate( $title, $id ) {
4786 $ns = $title->getNamespace();
4787 $dbk = $title->getDBkey();
4788 if ( !isset( $this->mTemplates
[$ns] ) ) {
4789 $this->mTemplates
[$ns] = array();
4791 $this->mTemplates
[$ns][$dbk] = $id;
4795 * Return true if this cached output object predates the global or
4796 * per-article cache invalidation timestamps, or if it comes from
4797 * an incompatible older version.
4799 * @param string $touched the affected article's last touched timestamp
4803 function expired( $touched ) {
4804 global $wgCacheEpoch;
4805 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4806 $this->getCacheTime() < $touched ||
4807 $this->getCacheTime() <= $wgCacheEpoch ||
4808 !isset( $this->mVersion
) ||
4809 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4814 * Set options of the Parser
4816 * @package MediaWiki
4820 # All variables are supposed to be private in theory, although in practise this is not the case.
4821 var $mUseTeX; # Use texvc to expand <math> tags
4822 var $mUseDynamicDates; # Use DateFormatter to format dates
4823 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4824 var $mAllowExternalImages; # Allow external images inline
4825 var $mAllowExternalImagesFrom; # If not, any exception?
4826 var $mSkin; # Reference to the preferred skin
4827 var $mDateFormat; # Date format index
4828 var $mEditSection; # Create "edit section" links
4829 var $mNumberHeadings; # Automatically number headings
4830 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4831 var $mTidy; # Ask for tidy cleanup
4832 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4833 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4834 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4836 var $mUser; # Stored user object, just used to initialise the skin
4838 function getUseTeX() { return $this->mUseTeX
; }
4839 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4840 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4841 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4842 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4843 function getEditSection() { return $this->mEditSection
; }
4844 function getNumberHeadings() { return $this->mNumberHeadings
; }
4845 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4846 function getTidy() { return $this->mTidy
; }
4847 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4848 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4849 function getRemoveComments() { return $this->mRemoveComments
; }
4851 function &getSkin() {
4852 if ( !isset( $this->mSkin
) ) {
4853 $this->mSkin
= $this->mUser
->getSkin();
4855 return $this->mSkin
;
4858 function getDateFormat() {
4859 if ( !isset( $this->mDateFormat
) ) {
4860 $this->mDateFormat
= $this->mUser
->getDatePreference();
4862 return $this->mDateFormat
;
4865 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4866 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4867 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4868 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4869 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4870 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4871 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4872 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4873 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4874 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4875 function setSkin( $x ) { $this->mSkin
= $x; }
4876 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4877 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4878 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4880 function ParserOptions( $user = null ) {
4881 $this->initialiseFromUser( $user );
4885 * Get parser options
4888 static function newFromUser( $user ) {
4889 return new ParserOptions( $user );
4892 /** Get user options */
4893 function initialiseFromUser( $userInput ) {
4894 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4895 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4896 $fname = 'ParserOptions::initialiseFromUser';
4897 wfProfileIn( $fname );
4898 if ( !$userInput ) {
4900 if ( isset( $wgUser ) ) {
4906 $user =& $userInput;
4909 $this->mUser
= $user;
4911 $this->mUseTeX
= $wgUseTeX;
4912 $this->mUseDynamicDates
= $wgUseDynamicDates;
4913 $this->mInterwikiMagic
= $wgInterwikiMagic;
4914 $this->mAllowExternalImages
= $wgAllowExternalImages;
4915 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4916 $this->mSkin
= null; # Deferred
4917 $this->mDateFormat
= null; # Deferred
4918 $this->mEditSection
= true;
4919 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4920 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4921 $this->mTidy
= false;
4922 $this->mInterfaceMessage
= false;
4923 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4924 $this->mRemoveComments
= true;
4925 wfProfileOut( $fname );
4929 class OnlyIncludeReplacer
{
4932 function replace( $matches ) {
4933 if ( substr( $matches[1], -1 ) == "\n" ) {
4934 $this->output
.= substr( $matches[1], 0, -1 );
4936 $this->output
.= $matches[1];
4942 var $general, $nowiki;
4944 function __construct() {
4945 $this->general
= new ReplacementArray
;
4946 $this->nowiki
= new ReplacementArray
;
4949 function unstripGeneral( $text ) {
4950 wfProfileIn( __METHOD__
);
4951 $text = $this->general
->replace( $text );
4952 wfProfileOut( __METHOD__
);
4956 function unstripNoWiki( $text ) {
4957 wfProfileIn( __METHOD__
);
4958 $text = $this->nowiki
->replace( $text );
4959 wfProfileOut( __METHOD__
);
4963 function unstripBoth( $text ) {
4964 wfProfileIn( __METHOD__
);
4965 $text = $this->general
->replace( $text );
4966 $text = $this->nowiki
->replace( $text );
4967 wfProfileOut( __METHOD__
);