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 = array();
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId; // ID to display in {{REVISIONID}} tags
125 $this->mTagHooks
= array();
126 $this->mFunctionHooks
= array();
127 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
128 $this->mFirstCall
= true;
132 * Do various kinds of initialisation on the first call of the parser
134 function firstCallInit() {
135 if ( !$this->mFirstCall
) {
139 wfProfileIn( __METHOD__
);
140 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
142 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
144 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
169 if ( $wgAllowDisplayTitle ) {
170 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
172 if ( $wgAllowSlowParserFunctions ) {
173 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
176 $this->initialiseVariables();
178 $this->mFirstCall
= false;
179 wfProfileOut( __METHOD__
);
187 function clearState() {
188 wfProfileIn( __METHOD__
);
189 if ( $this->mFirstCall
) {
190 $this->firstCallInit();
192 $this->mOutput
= new ParserOutput
;
193 $this->mAutonumber
= 0;
194 $this->mLastSection
= '';
195 $this->mDTopen
= false;
196 $this->mIncludeCount
= array();
197 $this->mStripState
= array();
198 $this->mArgStack
= array();
199 $this->mInPre
= false;
200 $this->mInterwikiLinkHolders
= array(
204 $this->mLinkHolders
= array(
205 'namespaces' => array(),
207 'queries' => array(),
211 $this->mRevisionId
= null;
214 * Prefix for temporary replacement strings for the multipass parser.
215 * \x07 should never appear in input as it's disallowed in XML.
216 * Using it at the front also gives us a little extra robustness
217 * since it shouldn't match when butted up against identifier-like
220 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
222 # Clear these on every parse, bug 4549
223 $this->mTemplates
= array();
224 $this->mTemplatePath
= array();
226 $this->mShowToc
= true;
227 $this->mForceTocPosition
= false;
228 $this->mIncludeSizes
= array(
234 wfRunHooks( 'ParserClearState', array( &$this ) );
235 wfProfileOut( __METHOD__
);
238 function setOutputType( $ot ) {
239 $this->mOutputType
= $ot;
242 'html' => $ot == OT_HTML
,
243 'wiki' => $ot == OT_WIKI
,
244 'msg' => $ot == OT_MSG
,
245 'pre' => $ot == OT_PREPROCESS
,
250 * Accessor for mUniqPrefix.
254 function uniqPrefix() {
255 return $this->mUniqPrefix
;
259 * Convert wikitext to HTML
260 * Do not call this function recursively.
263 * @param string $text Text we want to parse
264 * @param Title &$title A title object
265 * @param array $options
266 * @param boolean $linestart
267 * @param boolean $clearState
268 * @param int $revid number to pass in {{REVISIONID}}
269 * @return ParserOutput a ParserOutput
271 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
273 * First pass--just handle <nowiki> sections, pass the rest off
274 * to internalParse() which does all the real work.
277 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
278 $fname = 'Parser::parse-' . wfGetCaller();
279 wfProfileIn( $fname );
285 $this->mOptions
= $options;
286 $this->mTitle
=& $title;
287 $oldRevisionId = $this->mRevisionId
;
288 if( $revid !== null ) {
289 $this->mRevisionId
= $revid;
291 $this->setOutputType( OT_HTML
);
293 //$text = $this->strip( $text, $this->mStripState );
294 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
295 $x =& $this->mStripState
;
297 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
298 $text = $this->strip( $text, $x );
299 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
301 $text = $this->internalParse( $text );
303 $text = $this->unstrip( $text, $this->mStripState
);
305 # Clean up special characters, only run once, next-to-last before doBlockLevels
307 # french spaces, last one Guillemet-left
308 # only if there is something before the space
309 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
310 # french spaces, Guillemet-right
311 '/(\\302\\253) /' => '\\1 ',
313 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
316 $text = $this->doBlockLevels( $text, $linestart );
318 $this->replaceLinkHolders( $text );
320 # the position of the parserConvert() call should not be changed. it
321 # assumes that the links are all replaced and the only thing left
322 # is the <nowiki> mark.
323 # Side-effects: this calls $this->mOutput->setTitleText()
324 $text = $wgContLang->parserConvert( $text, $this );
326 $text = $this->unstripNoWiki( $text, $this->mStripState
);
328 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
330 $text = Sanitizer
::normalizeCharReferences( $text );
332 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
333 $text = Parser
::tidy($text);
335 # attempt to sanitize at least some nesting problems
336 # (bug #2702 and quite a few others)
338 # ''Something [http://www.cool.com cool''] -->
339 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
340 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
341 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
342 # fix up an anchor inside another anchor, only
343 # at least for a single single nested link (bug 3695)
344 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
345 '\\1\\2</a>\\3</a>\\1\\4</a>',
346 # fix div inside inline elements- doBlockLevels won't wrap a line which
347 # contains a div, so fix it up here; replace
348 # div with escaped text
349 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
350 '\\1\\3<div\\5>\\6</div>\\8\\9',
351 # remove empty italic or bold tag pairs, some
352 # introduced by rules above
353 '/<([bi])><\/\\1>/' => '',
356 $text = preg_replace(
357 array_keys( $tidyregs ),
358 array_values( $tidyregs ),
362 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
364 # Information on include size limits, for the benefit of users who try to skirt them
365 if ( max( $this->mIncludeSizes
) > 1000 ) {
366 $max = $this->mOptions
->getMaxIncludeSize();
368 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
369 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
370 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
371 "Maximum: $max bytes\n" .
374 $this->mOutput
->setText( $text );
375 $this->mRevisionId
= $oldRevisionId;
376 wfProfileOut( $fname );
378 return $this->mOutput
;
382 * Recursive parser entry point that can be called from an extension tag
385 function recursiveTagParse( $text ) {
386 wfProfileIn( __METHOD__
);
387 $x =& $this->mStripState
;
388 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
389 $text = $this->strip( $text, $x );
390 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
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 $x =& $this->mStripState
;
407 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
408 $text = $this->strip( $text, $x );
409 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
410 if ( $this->mOptions
->getRemoveComments() ) {
411 $text = Sanitizer
::removeHTMLcomments( $text );
413 $text = $this->replaceVariables( $text );
414 $text = $this->unstrip( $text, $x );
415 $text = $this->unstripNowiki( $text, $x );
416 wfProfileOut( __METHOD__
);
421 * Get a random string
426 function getRandomString() {
427 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
430 function &getTitle() { return $this->mTitle
; }
431 function getOptions() { return $this->mOptions
; }
433 function getFunctionLang() {
434 global $wgLang, $wgContLang;
435 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
439 * Replaces all occurrences of HTML-style comments and the given tags
440 * in the text with a random marker and returns teh next text. The output
441 * parameter $matches will be an associative array filled with data in
443 * 'UNIQ-xxxxx' => array(
446 * array( 'param' => 'x' ),
447 * '<element param="x">tag content</element>' ) )
449 * @param $elements list of element names. Comments are always extracted.
450 * @param $text Source text string.
451 * @param $uniq_prefix
456 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
461 $taglist = implode( '|', $elements );
462 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
464 while ( '' != $text ) {
465 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
467 if( count( $p ) < 5 ) {
470 if( count( $p ) > 5 ) {
484 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
485 $stripped .= $marker;
487 if ( $close === '/>' ) {
488 // Empty element tag, <tag />
493 if( $element == '!--' ) {
496 $end = "/(<\\/$element\\s*>)/i";
498 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
500 if( count( $q ) < 3 ) {
501 # No end tag -- let it run out to the end of the text.
510 $matches[$marker] = array( $element,
512 Sanitizer
::decodeTagAttributes( $attributes ),
513 "<$element$attributes$close$content$tail" );
519 * Strips and renders nowiki, pre, math, hiero
520 * If $render is set, performs necessary rendering operations on plugins
521 * Returns the text, and fills an array with data needed in unstrip()
522 * If the $state is already a valid strip state, it adds to the state
524 * @param bool $stripcomments when set, HTML comments <!-- like this -->
525 * will be stripped in addition to other tags. This is important
526 * for section editing, where these comments cause confusion when
527 * counting the sections in the wikisource
529 * @param array dontstrip contains tags which should not be stripped;
530 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
534 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
535 wfProfileIn( __METHOD__
);
536 $render = ($this->mOutputType
== OT_HTML
);
538 $uniq_prefix = $this->mUniqPrefix
;
539 $commentState = array();
541 $elements = array_merge(
542 array( 'nowiki', 'gallery' ),
543 array_keys( $this->mTagHooks
) );
546 $elements[] = 'html';
548 if( $this->mOptions
->getUseTeX() ) {
549 $elements[] = 'math';
552 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
553 foreach ( $elements AS $k => $v ) {
554 if ( !in_array ( $v , $dontstrip ) ) continue;
555 unset ( $elements[$k] );
559 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
561 foreach( $matches as $marker => $data ) {
562 list( $element, $content, $params, $tag ) = $data;
564 $tagName = strtolower( $element );
565 wfProfileIn( __METHOD__
."-render-$tagName" );
569 if( substr( $tag, -3 ) == '-->' ) {
572 // Unclosed comment in input.
573 // Close it so later stripping can remove it
582 // Shouldn't happen otherwise. :)
584 $output = wfEscapeHTMLTagsOnly( $content );
587 $output = MathRenderer
::renderMath( $content );
590 $output = $this->renderImageGallery( $content, $params );
593 if( isset( $this->mTagHooks
[$tagName] ) ) {
594 $output = call_user_func_array( $this->mTagHooks
[$tagName],
595 array( $content, $params, $this ) );
597 throw new MWException( "Invalid call hook $element" );
600 wfProfileOut( __METHOD__
."-render-$tagName" );
602 // Just stripping tags; keep the source
606 // Unstrip the output, because unstrip() is no longer recursive so
607 // it won't do it itself
608 $output = $this->unstrip( $output, $state );
610 if( !$stripcomments && $element == '!--' ) {
611 $commentState[$marker] = $output;
612 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
613 $state['nowiki'][$marker] = $output;
615 $state['general'][$marker] = $output;
619 # Unstrip comments unless explicitly told otherwise.
620 # (The comments are always stripped prior to this point, so as to
621 # not invoke any extension tags / parser hooks contained within
623 if ( !$stripcomments ) {
624 // Put them all back and forget them
625 $text = strtr( $text, $commentState );
628 wfProfileOut( __METHOD__
);
633 * Restores pre, math, and other extensions removed by strip()
635 * always call unstripNoWiki() after this one
638 function unstrip( $text, $state ) {
639 if ( !isset( $state['general'] ) ) {
643 wfProfileIn( __METHOD__
);
644 # TODO: good candidate for FSS
645 $text = strtr( $text, $state['general'] );
646 wfProfileOut( __METHOD__
);
651 * Always call this after unstrip() to preserve the order
655 function unstripNoWiki( $text, $state ) {
656 if ( !isset( $state['nowiki'] ) ) {
660 wfProfileIn( __METHOD__
);
661 # TODO: good candidate for FSS
662 $text = strtr( $text, $state['nowiki'] );
663 wfProfileOut( __METHOD__
);
669 * Add an item to the strip state
670 * Returns the unique tag which must be inserted into the stripped text
671 * The tag will be replaced with the original text in unstrip()
675 function insertStripItem( $text, &$state ) {
676 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
680 $state['general'][$rnd] = $text;
685 * Interface with html tidy, used if $wgUseTidy = true.
686 * If tidy isn't able to correct the markup, the original will be
687 * returned in all its glory with a warning comment appended.
689 * Either the external tidy program or the in-process tidy extension
690 * will be used depending on availability. Override the default
691 * $wgTidyInternal setting to disable the internal if it's not working.
693 * @param string $text Hideous HTML input
694 * @return string Corrected HTML output
698 function tidy( $text ) {
699 global $wgTidyInternal;
700 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
701 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
702 '<head><title>test</title></head><body>'.$text.'</body></html>';
703 if( $wgTidyInternal ) {
704 $correctedtext = Parser
::internalTidy( $wrappedtext );
706 $correctedtext = Parser
::externalTidy( $wrappedtext );
708 if( is_null( $correctedtext ) ) {
709 wfDebug( "Tidy error detected!\n" );
710 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
712 return $correctedtext;
716 * Spawn an external HTML tidy process and get corrected markup back from it.
721 function externalTidy( $text ) {
722 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
723 $fname = 'Parser::externalTidy';
724 wfProfileIn( $fname );
729 $descriptorspec = array(
730 0 => array('pipe', 'r'),
731 1 => array('pipe', 'w'),
732 2 => array('file', '/dev/null', 'a')
735 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
736 if (is_resource($process)) {
737 // Theoretically, this style of communication could cause a deadlock
738 // here. If the stdout buffer fills up, then writes to stdin could
739 // block. This doesn't appear to happen with tidy, because tidy only
740 // writes to stdout after it's finished reading from stdin. Search
741 // for tidyParseStdin and tidySaveStdout in console/tidy.c
742 fwrite($pipes[0], $text);
744 while (!feof($pipes[1])) {
745 $cleansource .= fgets($pipes[1], 1024);
748 proc_close($process);
751 wfProfileOut( $fname );
753 if( $cleansource == '' && $text != '') {
754 // Some kind of error happened, so we couldn't get the corrected text.
755 // Just give up; we'll use the source text and append a warning.
763 * Use the HTML tidy PECL extension to use the tidy library in-process,
764 * saving the overhead of spawning a new process. Currently written to
765 * the PHP 4.3.x version of the extension, may not work on PHP 5.
767 * 'pear install tidy' should be able to compile the extension module.
772 function internalTidy( $text ) {
774 $fname = 'Parser::internalTidy';
775 wfProfileIn( $fname );
777 tidy_load_config( $wgTidyConf );
778 tidy_set_encoding( 'utf8' );
779 tidy_parse_string( $text );
781 if( tidy_get_status() == 2 ) {
782 // 2 is magic number for fatal error
783 // http://www.php.net/manual/en/function.tidy-get-status.php
786 $cleansource = tidy_get_output();
788 wfProfileOut( $fname );
793 * parse the wiki syntax used to render tables
797 function doTableStuff ( $t ) {
798 $fname = 'Parser::doTableStuff';
799 wfProfileIn( $fname );
801 $t = explode ( "\n" , $t ) ;
802 $td = array () ; # Is currently a td tag open?
803 $ltd = array () ; # Was it TD or TH?
804 $tr = array () ; # Is currently a tr tag open?
805 $ltr = array () ; # tr attributes
806 $has_opened_tr = array(); # Did this table open a <tr> element?
807 $indent_level = 0; # indent level of the table
808 foreach ( $t AS $k => $x )
811 $fc = substr ( $x , 0 , 1 ) ;
813 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
814 $indent_level = strlen( $matches[1] );
816 $attributes = $this->unstripForHTML( $matches[2] );
818 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
819 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
820 array_push ( $td , false ) ;
821 array_push ( $ltd , '' ) ;
822 array_push ( $tr , false ) ;
823 array_push ( $ltr , '' ) ;
824 array_push ( $has_opened_tr, false );
826 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
827 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
828 $z = "</table>" . substr ( $x , 2);
829 $l = array_pop ( $ltd ) ;
830 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
831 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
832 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
834 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
836 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
837 $x = substr ( $x , 1 ) ;
838 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
840 $l = array_pop ( $ltd ) ;
841 array_pop ( $has_opened_tr );
842 array_push ( $has_opened_tr , true ) ;
843 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
844 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
847 array_push ( $tr , false ) ;
848 array_push ( $td , false ) ;
849 array_push ( $ltd , '' ) ;
850 $attributes = $this->unstripForHTML( $x );
851 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
853 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
855 if ( '|+' == substr ( $x , 0 , 2 ) ) {
857 $x = substr ( $x , 1 ) ;
859 $after = substr ( $x , 1 ) ;
860 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
862 // Split up multiple cells on the same line.
863 // FIXME: This can result in improper nesting of tags processed
864 // by earlier parser steps, but should avoid splitting up eg
865 // attribute values containing literal "||".
866 $after = wfExplodeMarkup( '||', $after );
870 # Loop through each table cell
871 foreach ( $after AS $theline )
876 $tra = array_pop ( $ltr ) ;
877 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
878 array_push ( $tr , true ) ;
879 array_push ( $ltr , '' ) ;
880 array_pop ( $has_opened_tr );
881 array_push ( $has_opened_tr , true ) ;
884 $l = array_pop ( $ltd ) ;
885 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
888 } else if ( $fc == '!' ) {
890 } else if ( $fc == '+' ) {
895 array_push ( $ltd , $l ) ;
898 $y = explode ( '|' , $theline , 2 ) ;
899 # Note that a '|' inside an invalid link should not
900 # be mistaken as delimiting cell parameters
901 if ( strpos( $y[0], '[[' ) !== false ) {
902 $y = array ($theline);
904 if ( count ( $y ) == 1 )
905 $y = "{$z}<{$l}>{$y[0]}" ;
907 $attributes = $this->unstripForHTML( $y[0] );
908 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
911 array_push ( $td , true ) ;
916 # Closing open td, tr && table
917 while ( count ( $td ) > 0 )
919 $l = array_pop ( $ltd ) ;
920 if ( array_pop ( $td ) ) $t[] = '</td>' ;
921 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
922 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
926 $t = implode ( "\n" , $t ) ;
927 # special case: don't return empty table
928 if($t == "<table>\n<tr><td></td></tr>\n</table>")
930 wfProfileOut( $fname );
935 * Helper function for parse() that transforms wiki markup into
936 * HTML. Only called for $mOutputType == OT_HTML.
940 function internalParse( $text ) {
943 $fname = 'Parser::internalParse';
944 wfProfileIn( $fname );
946 # Hook to suspend the parser in this state
947 $x =& $this->mStripState
; // FIXME: Please check that this initialization is correct.
948 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
949 wfProfileOut( $fname );
953 # Remove <noinclude> tags and <includeonly> sections
954 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
955 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
956 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
958 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
960 $text = $this->replaceVariables( $text, $args );
962 // Tables need to come after variable replacement for things to work
963 // properly; putting them before other transformations should keep
964 // exciting things like link expansions from showing up in surprising
966 $text = $this->doTableStuff( $text );
968 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
970 $text = $this->stripToc( $text );
971 $this->stripNoGallery( $text );
972 $text = $this->doHeadings( $text );
973 if($this->mOptions
->getUseDynamicDates()) {
974 $df =& DateFormatter
::getInstance();
975 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
977 $text = $this->doAllQuotes( $text );
978 $text = $this->replaceInternalLinks( $text );
979 $text = $this->replaceExternalLinks( $text );
981 # replaceInternalLinks may sometimes leave behind
982 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
983 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
985 $text = $this->doMagicLinks( $text );
986 $text = $this->formatHeadings( $text, $isMain );
988 wfProfileOut( $fname );
993 * Replace special strings like "ISBN xxx" and "RFC xxx" with
994 * magic external links.
998 function &doMagicLinks( &$text ) {
999 wfProfileIn( __METHOD__
);
1000 $text = preg_replace_callback(
1002 <a.*?</a> | # Skip link text
1003 <.*?> | # Skip stuff inside HTML elements
1004 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1005 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
1006 )!x', array( &$this, 'magicLinkCallback' ), $text );
1007 wfProfileOut( __METHOD__
);
1011 function magicLinkCallback( $m ) {
1012 if ( substr( $m[0], 0, 1 ) == '<' ) {
1015 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1017 $num = strtr( $isbn, array(
1022 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1023 $text = '<a href="' .
1024 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1025 "\" class=\"internal\">ISBN $isbn</a>";
1027 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1031 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1033 $urlmsg = 'pubmedurl';
1036 throw new MWException( __METHOD__
.': unrecognised match type "' .
1037 substr($m[0], 0, 20 ) . '"' );
1040 $url = wfMsg( $urlmsg, $id);
1041 $sk =& $this->mOptions
->getSkin();
1042 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1043 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1049 * Parse headers and return html
1053 function doHeadings( $text ) {
1054 $fname = 'Parser::doHeadings';
1055 wfProfileIn( $fname );
1056 for ( $i = 6; $i >= 1; --$i ) {
1057 $h = str_repeat( '=', $i );
1058 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1059 "<h{$i}>\\1</h{$i}>\\2", $text );
1061 wfProfileOut( $fname );
1066 * Replace single quotes with HTML markup
1068 * @return string the altered text
1070 function doAllQuotes( $text ) {
1071 $fname = 'Parser::doAllQuotes';
1072 wfProfileIn( $fname );
1074 $lines = explode( "\n", $text );
1075 foreach ( $lines as $line ) {
1076 $outtext .= $this->doQuotes ( $line ) . "\n";
1078 $outtext = substr($outtext, 0,-1);
1079 wfProfileOut( $fname );
1084 * Helper function for doAllQuotes()
1087 function doQuotes( $text ) {
1088 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1089 if ( count( $arr ) == 1 )
1093 # First, do some preliminary work. This may shift some apostrophes from
1094 # being mark-up to being text. It also counts the number of occurrences
1095 # of bold and italics mark-ups.
1099 foreach ( $arr as $r )
1101 if ( ( $i %
2 ) == 1 )
1103 # If there are ever four apostrophes, assume the first is supposed to
1104 # be text, and the remaining three constitute mark-up for bold text.
1105 if ( strlen( $arr[$i] ) == 4 )
1110 # If there are more than 5 apostrophes in a row, assume they're all
1111 # text except for the last 5.
1112 else if ( strlen( $arr[$i] ) > 5 )
1114 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1117 # Count the number of occurrences of bold and italics mark-ups.
1118 # We are not counting sequences of five apostrophes.
1119 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1120 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1121 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1126 # If there is an odd number of both bold and italics, it is likely
1127 # that one of the bold ones was meant to be an apostrophe followed
1128 # by italics. Which one we cannot know for certain, but it is more
1129 # likely to be one that has a single-letter word before it.
1130 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1133 $firstsingleletterword = -1;
1134 $firstmultiletterword = -1;
1136 foreach ( $arr as $r )
1138 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1140 $x1 = substr ($arr[$i-1], -1);
1141 $x2 = substr ($arr[$i-1], -2, 1);
1143 if ($firstspace == -1) $firstspace = $i;
1144 } else if ($x2 == ' ') {
1145 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1147 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1153 # If there is a single-letter word, use it!
1154 if ($firstsingleletterword > -1)
1156 $arr [ $firstsingleletterword ] = "''";
1157 $arr [ $firstsingleletterword-1 ] .= "'";
1159 # If not, but there's a multi-letter word, use that one.
1160 else if ($firstmultiletterword > -1)
1162 $arr [ $firstmultiletterword ] = "''";
1163 $arr [ $firstmultiletterword-1 ] .= "'";
1165 # ... otherwise use the first one that has neither.
1166 # (notice that it is possible for all three to be -1 if, for example,
1167 # there is only one pentuple-apostrophe in the line)
1168 else if ($firstspace > -1)
1170 $arr [ $firstspace ] = "''";
1171 $arr [ $firstspace-1 ] .= "'";
1175 # Now let's actually convert our apostrophic mush to HTML!
1180 foreach ($arr as $r)
1184 if ($state == 'both')
1191 if (strlen ($r) == 2)
1194 { $output .= '</i>'; $state = ''; }
1195 else if ($state == 'bi')
1196 { $output .= '</i>'; $state = 'b'; }
1197 else if ($state == 'ib')
1198 { $output .= '</b></i><b>'; $state = 'b'; }
1199 else if ($state == 'both')
1200 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1201 else # $state can be 'b' or ''
1202 { $output .= '<i>'; $state .= 'i'; }
1204 else if (strlen ($r) == 3)
1207 { $output .= '</b>'; $state = ''; }
1208 else if ($state == 'bi')
1209 { $output .= '</i></b><i>'; $state = 'i'; }
1210 else if ($state == 'ib')
1211 { $output .= '</b>'; $state = 'i'; }
1212 else if ($state == 'both')
1213 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1214 else # $state can be 'i' or ''
1215 { $output .= '<b>'; $state .= 'b'; }
1217 else if (strlen ($r) == 5)
1220 { $output .= '</b><i>'; $state = 'i'; }
1221 else if ($state == 'i')
1222 { $output .= '</i><b>'; $state = 'b'; }
1223 else if ($state == 'bi')
1224 { $output .= '</i></b>'; $state = ''; }
1225 else if ($state == 'ib')
1226 { $output .= '</b></i>'; $state = ''; }
1227 else if ($state == 'both')
1228 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1229 else # ($state == '')
1230 { $buffer = ''; $state = 'both'; }
1235 # Now close all remaining tags. Notice that the order is important.
1236 if ($state == 'b' ||
$state == 'ib')
1238 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1242 if ($state == 'both')
1243 $output .= '<b><i>'.$buffer.'</i></b>';
1249 * Replace external links
1251 * Note: this is all very hackish and the order of execution matters a lot.
1252 * Make sure to run maintenance/parserTests.php if you change this code.
1256 function replaceExternalLinks( $text ) {
1258 $fname = 'Parser::replaceExternalLinks';
1259 wfProfileIn( $fname );
1261 $sk =& $this->mOptions
->getSkin();
1263 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1265 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1268 while ( $i<count( $bits ) ) {
1270 $protocol = $bits[$i++
];
1271 $text = $bits[$i++
];
1272 $trail = $bits[$i++
];
1274 # The characters '<' and '>' (which were escaped by
1275 # removeHTMLtags()) should not be included in
1276 # URLs, per RFC 2396.
1278 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1279 $text = substr($url, $m2[0][1]) . ' ' . $text;
1280 $url = substr($url, 0, $m2[0][1]);
1283 # If the link text is an image URL, replace it with an <img> tag
1284 # This happened by accident in the original parser, but some people used it extensively
1285 $img = $this->maybeMakeExternalImage( $text );
1286 if ( $img !== false ) {
1292 # Set linktype for CSS - if URL==text, link is essentially free
1293 $linktype = ($text == $url) ?
'free' : 'text';
1295 # No link text, e.g. [http://domain.tld/some.link]
1296 if ( $text == '' ) {
1297 # Autonumber if allowed. See bug #5918
1298 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1299 $text = '[' . ++
$this->mAutonumber
. ']';
1300 $linktype = 'autonumber';
1302 # Otherwise just use the URL
1303 $text = htmlspecialchars( $url );
1307 # Have link text, e.g. [http://domain.tld/some.link text]s
1309 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1312 $text = $wgContLang->markNoConversion($text);
1314 $url = Sanitizer
::cleanUrl( $url );
1316 # Process the trail (i.e. everything after this link up until start of the next link),
1317 # replacing any non-bracketed links
1318 $trail = $this->replaceFreeExternalLinks( $trail );
1320 # Use the encoded URL
1321 # This means that users can paste URLs directly into the text
1322 # Funny characters like ö aren't valid in URLs anyway
1323 # This was changed in August 2004
1324 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1326 # Register link in the output object.
1327 # Replace unnecessary URL escape codes with the referenced character
1328 # This prevents spammers from hiding links from the filters
1329 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1330 $this->mOutput
->addExternalLink( $pasteurized );
1333 wfProfileOut( $fname );
1338 * Replace anything that looks like a URL with a link
1341 function replaceFreeExternalLinks( $text ) {
1343 $fname = 'Parser::replaceFreeExternalLinks';
1344 wfProfileIn( $fname );
1346 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1347 $s = array_shift( $bits );
1350 $sk =& $this->mOptions
->getSkin();
1352 while ( $i < count( $bits ) ){
1353 $protocol = $bits[$i++
];
1354 $remainder = $bits[$i++
];
1357 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1358 # Found some characters after the protocol that look promising
1359 $url = $protocol . $m[1];
1362 # special case: handle urls as url args:
1363 # http://www.example.com/foo?=http://www.example.com/bar
1364 if(strlen($trail) == 0 &&
1366 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1367 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1370 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1375 # The characters '<' and '>' (which were escaped by
1376 # removeHTMLtags()) should not be included in
1377 # URLs, per RFC 2396.
1379 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1380 $trail = substr($url, $m2[0][1]) . $trail;
1381 $url = substr($url, 0, $m2[0][1]);
1384 # Move trailing punctuation to $trail
1386 # If there is no left bracket, then consider right brackets fair game too
1387 if ( strpos( $url, '(' ) === false ) {
1391 $numSepChars = strspn( strrev( $url ), $sep );
1392 if ( $numSepChars ) {
1393 $trail = substr( $url, -$numSepChars ) . $trail;
1394 $url = substr( $url, 0, -$numSepChars );
1397 $url = Sanitizer
::cleanUrl( $url );
1399 # Is this an external image?
1400 $text = $this->maybeMakeExternalImage( $url );
1401 if ( $text === false ) {
1402 # Not an image, make a link
1403 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1404 # Register it in the output object...
1405 # Replace unnecessary URL escape codes with their equivalent characters
1406 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1407 $this->mOutput
->addExternalLink( $pasteurized );
1409 $s .= $text . $trail;
1411 $s .= $protocol . $remainder;
1414 wfProfileOut( $fname );
1419 * Replace unusual URL escape codes with their equivalent characters
1423 * @fixme This can merge genuinely required bits in the path or query string,
1424 * breaking legit URLs. A proper fix would treat the various parts of
1425 * the URL differently; as a workaround, just use the output for
1426 * statistical records, not for actual linking/output.
1428 static function replaceUnusualEscapes( $url ) {
1429 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1430 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1434 * Callback function used in replaceUnusualEscapes().
1435 * Replaces unusual URL escape codes with their equivalent character
1439 private static function replaceUnusualEscapesCallback( $matches ) {
1440 $char = urldecode( $matches[0] );
1441 $ord = ord( $char );
1442 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1443 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1444 // No, shouldn't be escaped
1447 // Yes, leave it escaped
1453 * make an image if it's allowed, either through the global
1454 * option or through the exception
1457 function maybeMakeExternalImage( $url ) {
1458 $sk =& $this->mOptions
->getSkin();
1459 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1460 $imagesexception = !empty($imagesfrom);
1462 if ( $this->mOptions
->getAllowExternalImages()
1463 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1464 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1466 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1473 * Process [[ ]] wikilinks
1477 function replaceInternalLinks( $s ) {
1479 static $fname = 'Parser::replaceInternalLinks' ;
1481 wfProfileIn( $fname );
1483 wfProfileIn( $fname.'-setup' );
1485 # the % is needed to support urlencoded titles as well
1486 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1488 $sk =& $this->mOptions
->getSkin();
1490 #split the entire text string on occurences of [[
1491 $a = explode( '[[', ' ' . $s );
1492 #get the first element (all text up to first [[), and remove the space we added
1493 $s = array_shift( $a );
1494 $s = substr( $s, 1 );
1496 # Match a link having the form [[namespace:link|alternate]]trail
1498 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1499 # Match cases where there is no "]]", which might still be images
1500 static $e1_img = FALSE;
1501 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1502 # Match the end of a line for a word that's not followed by whitespace,
1503 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1504 $e2 = wfMsgForContent( 'linkprefix' );
1506 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1508 if( is_null( $this->mTitle
) ) {
1509 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1511 $nottalk = !$this->mTitle
->isTalkPage();
1513 if ( $useLinkPrefixExtension ) {
1515 if ( preg_match( $e2, $s, $m ) ) {
1516 $first_prefix = $m[2];
1518 $first_prefix = false;
1524 $selflink = $this->mTitle
->getPrefixedText();
1525 $useSubpages = $this->areSubpagesAllowed();
1526 wfProfileOut( $fname.'-setup' );
1528 # Loop for each link
1529 for ($k = 0; isset( $a[$k] ); $k++
) {
1531 if ( $useLinkPrefixExtension ) {
1532 wfProfileIn( $fname.'-prefixhandling' );
1533 if ( preg_match( $e2, $s, $m ) ) {
1541 $prefix = $first_prefix;
1542 $first_prefix = false;
1544 wfProfileOut( $fname.'-prefixhandling' );
1547 $might_be_img = false;
1549 wfProfileIn( "$fname-e1" );
1550 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1552 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1553 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1554 # the real problem is with the $e1 regex
1557 # Still some problems for cases where the ] is meant to be outside punctuation,
1558 # and no image is in sight. See bug 2095.
1561 substr( $m[3], 0, 1 ) === ']' &&
1562 strpos($text, '[') !== false
1565 $text .= ']'; # so that replaceExternalLinks($text) works later
1566 $m[3] = substr( $m[3], 1 );
1568 # fix up urlencoded title texts
1569 if( strpos( $m[1], '%' ) !== false ) {
1570 # Should anchors '#' also be rejected?
1571 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1574 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1575 $might_be_img = true;
1577 if ( strpos( $m[1], '%' ) !== false ) {
1578 $m[1] = urldecode($m[1]);
1581 } else { # Invalid form; output directly
1582 $s .= $prefix . '[[' . $line ;
1583 wfProfileOut( "$fname-e1" );
1586 wfProfileOut( "$fname-e1" );
1587 wfProfileIn( "$fname-misc" );
1589 # Don't allow internal links to pages containing
1590 # PROTO: where PROTO is a valid URL protocol; these
1591 # should be external links.
1592 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1593 $s .= $prefix . '[[' . $line ;
1597 # Make subpage if necessary
1598 if( $useSubpages ) {
1599 $link = $this->maybeDoSubpageLink( $m[1], $text );
1604 $noforce = (substr($m[1], 0, 1) != ':');
1606 # Strip off leading ':'
1607 $link = substr($link, 1);
1610 wfProfileOut( "$fname-misc" );
1611 wfProfileIn( "$fname-title" );
1612 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1614 $s .= $prefix . '[[' . $line;
1615 wfProfileOut( "$fname-title" );
1619 $ns = $nt->getNamespace();
1620 $iw = $nt->getInterWiki();
1621 wfProfileOut( "$fname-title" );
1623 if ($might_be_img) { # if this is actually an invalid link
1624 wfProfileIn( "$fname-might_be_img" );
1625 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1627 while (isset ($a[$k+
1]) ) {
1628 #look at the next 'line' to see if we can close it there
1629 $spliced = array_splice( $a, $k +
1, 1 );
1630 $next_line = array_shift( $spliced );
1631 $m = explode( ']]', $next_line, 3 );
1632 if ( count( $m ) == 3 ) {
1633 # the first ]] closes the inner link, the second the image
1635 $text .= "[[{$m[0]}]]{$m[1]}";
1638 } elseif ( count( $m ) == 2 ) {
1639 #if there's exactly one ]] that's fine, we'll keep looking
1640 $text .= "[[{$m[0]}]]{$m[1]}";
1642 #if $next_line is invalid too, we need look no further
1643 $text .= '[[' . $next_line;
1648 # we couldn't find the end of this imageLink, so output it raw
1649 #but don't ignore what might be perfectly normal links in the text we've examined
1650 $text = $this->replaceInternalLinks($text);
1651 $s .= "{$prefix}[[$link|$text";
1652 # note: no $trail, because without an end, there *is* no trail
1653 wfProfileOut( "$fname-might_be_img" );
1656 } else { #it's not an image, so output it raw
1657 $s .= "{$prefix}[[$link|$text";
1658 # note: no $trail, because without an end, there *is* no trail
1659 wfProfileOut( "$fname-might_be_img" );
1662 wfProfileOut( "$fname-might_be_img" );
1665 $wasblank = ( '' == $text );
1666 if( $wasblank ) $text = $link;
1668 # Link not escaped by : , create the various objects
1672 wfProfileIn( "$fname-interwiki" );
1673 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1674 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1675 $s = rtrim($s . "\n");
1676 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1677 wfProfileOut( "$fname-interwiki" );
1680 wfProfileOut( "$fname-interwiki" );
1682 if ( $ns == NS_IMAGE
) {
1683 wfProfileIn( "$fname-image" );
1684 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1685 # recursively parse links inside the image caption
1686 # actually, this will parse them in any other parameters, too,
1687 # but it might be hard to fix that, and it doesn't matter ATM
1688 $text = $this->replaceExternalLinks($text);
1689 $text = $this->replaceInternalLinks($text);
1691 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1692 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1693 $this->mOutput
->addImage( $nt->getDBkey() );
1695 wfProfileOut( "$fname-image" );
1698 # We still need to record the image's presence on the page
1699 $this->mOutput
->addImage( $nt->getDBkey() );
1701 wfProfileOut( "$fname-image" );
1705 if ( $ns == NS_CATEGORY
) {
1706 wfProfileIn( "$fname-category" );
1707 $s = rtrim($s . "\n"); # bug 87
1710 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1711 $sortkey = $this->mTitle
->getText();
1713 $sortkey = $this->mTitle
->getPrefixedText();
1718 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1719 $sortkey = str_replace( "\n", '', $sortkey );
1720 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1721 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1724 * Strip the whitespace Category links produce, see bug 87
1725 * @todo We might want to use trim($tmp, "\n") here.
1727 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1729 wfProfileOut( "$fname-category" );
1734 if( ( $nt->getPrefixedText() === $selflink ) &&
1735 ( $nt->getFragment() === '' ) ) {
1736 # Self-links are handled specially; generally de-link and change to bold.
1737 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1741 # Special and Media are pseudo-namespaces; no pages actually exist in them
1742 if( $ns == NS_MEDIA
) {
1743 $link = $sk->makeMediaLinkObj( $nt, $text );
1744 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1745 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1746 $this->mOutput
->addImage( $nt->getDBkey() );
1748 } elseif( $ns == NS_SPECIAL
) {
1749 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1751 } elseif( $ns == NS_IMAGE
) {
1752 $img = new Image( $nt );
1753 if( $img->exists() ) {
1754 // Force a blue link if the file exists; may be a remote
1755 // upload on the shared repository, and we want to see its
1756 // auto-generated page.
1757 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1758 $this->mOutput
->addLink( $nt );
1762 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1764 wfProfileOut( $fname );
1769 * Make a link placeholder. The text returned can be later resolved to a real link with
1770 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1771 * parsing of interwiki links, and secondly to allow all existence checks and
1772 * article length checks (for stub links) to be bundled into a single query.
1775 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1776 wfProfileIn( __METHOD__
);
1777 if ( ! is_object($nt) ) {
1779 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1781 # Separate the link trail from the rest of the link
1782 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1784 if ( $nt->isExternal() ) {
1785 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1786 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1787 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1789 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1790 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1791 $this->mLinkHolders
['queries'][] = $query;
1792 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1793 $this->mLinkHolders
['titles'][] = $nt;
1795 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1798 wfProfileOut( __METHOD__
);
1803 * Render a forced-blue link inline; protect against double expansion of
1804 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1805 * Since this little disaster has to split off the trail text to avoid
1806 * breaking URLs in the following text without breaking trails on the
1807 * wiki links, it's been made into a horrible function.
1810 * @param string $text
1811 * @param string $query
1812 * @param string $trail
1813 * @param string $prefix
1814 * @return string HTML-wikitext mix oh yuck
1816 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1817 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1818 $sk =& $this->mOptions
->getSkin();
1819 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1820 return $this->armorLinks( $link ) . $trail;
1824 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1825 * going to go through further parsing steps before inline URL expansion.
1827 * In particular this is important when using action=render, which causes
1828 * full URLs to be included.
1830 * Oh man I hate our multi-layer parser!
1832 * @param string more-or-less HTML
1833 * @return string less-or-more HTML with NOPARSE bits
1835 function armorLinks( $text ) {
1836 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1837 "{$this->mUniqPrefix}NOPARSE$1", $text );
1841 * Return true if subpage links should be expanded on this page.
1844 function areSubpagesAllowed() {
1845 # Some namespaces don't allow subpages
1846 global $wgNamespacesWithSubpages;
1847 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1851 * Handle link to subpage if necessary
1852 * @param string $target the source of the link
1853 * @param string &$text the link text, modified as necessary
1854 * @return string the full name of the link
1857 function maybeDoSubpageLink($target, &$text) {
1860 # :Foobar -- override special treatment of prefix (images, language links)
1861 # /Foobar -- convert to CurrentPage/Foobar
1862 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1863 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1864 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1866 $fname = 'Parser::maybeDoSubpageLink';
1867 wfProfileIn( $fname );
1868 $ret = $target; # default return value is no change
1871 $target = trim( $target );
1873 # Some namespaces don't allow subpages,
1874 # so only perform processing if subpages are allowed
1875 if( $this->areSubpagesAllowed() ) {
1876 # Look at the first character
1877 if( $target != '' && $target{0} == '/' ) {
1878 # / at end means we don't want the slash to be shown
1879 if( substr( $target, -1, 1 ) == '/' ) {
1880 $target = substr( $target, 1, -1 );
1883 $noslash = substr( $target, 1 );
1886 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1887 if( '' === $text ) {
1889 } # this might be changed for ugliness reasons
1891 # check for .. subpage backlinks
1893 $nodotdot = $target;
1894 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1896 $nodotdot = substr( $nodotdot, 3 );
1898 if($dotdotcount > 0) {
1899 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1900 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1901 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1902 # / at the end means don't show full path
1903 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1904 $nodotdot = substr( $nodotdot, 0, -1 );
1905 if( '' === $text ) {
1909 $nodotdot = trim( $nodotdot );
1910 if( $nodotdot != '' ) {
1911 $ret .= '/' . $nodotdot;
1918 wfProfileOut( $fname );
1923 * Used by doBlockLevels()
1926 /* private */ function closeParagraph() {
1928 if ( '' != $this->mLastSection
) {
1929 $result = '</' . $this->mLastSection
. ">\n";
1931 $this->mInPre
= false;
1932 $this->mLastSection
= '';
1935 # getCommon() returns the length of the longest common substring
1936 # of both arguments, starting at the beginning of both.
1938 /* private */ function getCommon( $st1, $st2 ) {
1939 $fl = strlen( $st1 );
1940 $shorter = strlen( $st2 );
1941 if ( $fl < $shorter ) { $shorter = $fl; }
1943 for ( $i = 0; $i < $shorter; ++
$i ) {
1944 if ( $st1{$i} != $st2{$i} ) { break; }
1948 # These next three functions open, continue, and close the list
1949 # element appropriate to the prefix character passed into them.
1951 /* private */ function openList( $char ) {
1952 $result = $this->closeParagraph();
1954 if ( '*' == $char ) { $result .= '<ul><li>'; }
1955 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1956 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1957 else if ( ';' == $char ) {
1958 $result .= '<dl><dt>';
1959 $this->mDTopen
= true;
1961 else { $result = '<!-- ERR 1 -->'; }
1966 /* private */ function nextItem( $char ) {
1967 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1968 else if ( ':' == $char ||
';' == $char ) {
1970 if ( $this->mDTopen
) { $close = '</dt>'; }
1971 if ( ';' == $char ) {
1972 $this->mDTopen
= true;
1973 return $close . '<dt>';
1975 $this->mDTopen
= false;
1976 return $close . '<dd>';
1979 return '<!-- ERR 2 -->';
1982 /* private */ function closeList( $char ) {
1983 if ( '*' == $char ) { $text = '</li></ul>'; }
1984 else if ( '#' == $char ) { $text = '</li></ol>'; }
1985 else if ( ':' == $char ) {
1986 if ( $this->mDTopen
) {
1987 $this->mDTopen
= false;
1988 $text = '</dt></dl>';
1990 $text = '</dd></dl>';
1993 else { return '<!-- ERR 3 -->'; }
1999 * Make lists from lines starting with ':', '*', '#', etc.
2002 * @return string the lists rendered as HTML
2004 function doBlockLevels( $text, $linestart ) {
2005 $fname = 'Parser::doBlockLevels';
2006 wfProfileIn( $fname );
2008 # Parsing through the text line by line. The main thing
2009 # happening here is handling of block-level elements p, pre,
2010 # and making lists from lines starting with * # : etc.
2012 $textLines = explode( "\n", $text );
2014 $lastPrefix = $output = '';
2015 $this->mDTopen
= $inBlockElem = false;
2017 $paragraphStack = false;
2019 if ( !$linestart ) {
2020 $output .= array_shift( $textLines );
2022 foreach ( $textLines as $oLine ) {
2023 $lastPrefixLength = strlen( $lastPrefix );
2024 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2025 $preOpenMatch = preg_match('/<pre/i', $oLine );
2026 if ( !$this->mInPre
) {
2027 # Multiple prefixes may abut each other for nested lists.
2028 $prefixLength = strspn( $oLine, '*#:;' );
2029 $pref = substr( $oLine, 0, $prefixLength );
2032 $pref2 = str_replace( ';', ':', $pref );
2033 $t = substr( $oLine, $prefixLength );
2034 $this->mInPre
= !empty($preOpenMatch);
2036 # Don't interpret any other prefixes in preformatted text
2038 $pref = $pref2 = '';
2043 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2044 # Same as the last item, so no need to deal with nesting or opening stuff
2045 $output .= $this->nextItem( substr( $pref, -1 ) );
2046 $paragraphStack = false;
2048 if ( substr( $pref, -1 ) == ';') {
2049 # The one nasty exception: definition lists work like this:
2050 # ; title : definition text
2051 # So we check for : in the remainder text to split up the
2052 # title and definition, without b0rking links.
2054 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2056 $output .= $term . $this->nextItem( ':' );
2059 } elseif( $prefixLength ||
$lastPrefixLength ) {
2060 # Either open or close a level...
2061 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2062 $paragraphStack = false;
2064 while( $commonPrefixLength < $lastPrefixLength ) {
2065 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2066 --$lastPrefixLength;
2068 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2069 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2071 while ( $prefixLength > $commonPrefixLength ) {
2072 $char = substr( $pref, $commonPrefixLength, 1 );
2073 $output .= $this->openList( $char );
2075 if ( ';' == $char ) {
2076 # FIXME: This is dupe of code above
2077 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2079 $output .= $term . $this->nextItem( ':' );
2082 ++
$commonPrefixLength;
2084 $lastPrefix = $pref2;
2086 if( 0 == $prefixLength ) {
2087 wfProfileIn( "$fname-paragraph" );
2088 # No prefix (not in list)--go to paragraph mode
2089 // XXX: use a stack for nestable elements like span, table and div
2090 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2091 $closematch = preg_match(
2092 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2093 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2094 if ( $openmatch or $closematch ) {
2095 $paragraphStack = false;
2096 #Â TODO bug 5718: paragraph closed
2097 $output .= $this->closeParagraph();
2098 if ( $preOpenMatch and !$preCloseMatch ) {
2099 $this->mInPre
= true;
2101 if ( $closematch ) {
2102 $inBlockElem = false;
2104 $inBlockElem = true;
2106 } else if ( !$inBlockElem && !$this->mInPre
) {
2107 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2109 if ($this->mLastSection
!= 'pre') {
2110 $paragraphStack = false;
2111 $output .= $this->closeParagraph().'<pre>';
2112 $this->mLastSection
= 'pre';
2114 $t = substr( $t, 1 );
2117 if ( '' == trim($t) ) {
2118 if ( $paragraphStack ) {
2119 $output .= $paragraphStack.'<br />';
2120 $paragraphStack = false;
2121 $this->mLastSection
= 'p';
2123 if ($this->mLastSection
!= 'p' ) {
2124 $output .= $this->closeParagraph();
2125 $this->mLastSection
= '';
2126 $paragraphStack = '<p>';
2128 $paragraphStack = '</p><p>';
2132 if ( $paragraphStack ) {
2133 $output .= $paragraphStack;
2134 $paragraphStack = false;
2135 $this->mLastSection
= 'p';
2136 } else if ($this->mLastSection
!= 'p') {
2137 $output .= $this->closeParagraph().'<p>';
2138 $this->mLastSection
= 'p';
2143 wfProfileOut( "$fname-paragraph" );
2145 // somewhere above we forget to get out of pre block (bug 785)
2146 if($preCloseMatch && $this->mInPre
) {
2147 $this->mInPre
= false;
2149 if ($paragraphStack === false) {
2153 while ( $prefixLength ) {
2154 $output .= $this->closeList( $pref2{$prefixLength-1} );
2157 if ( '' != $this->mLastSection
) {
2158 $output .= '</' . $this->mLastSection
. '>';
2159 $this->mLastSection
= '';
2162 wfProfileOut( $fname );
2167 * Split up a string on ':', ignoring any occurences inside tags
2168 * to prevent illegal overlapping.
2169 * @param string $str the string to split
2170 * @param string &$before set to everything before the ':'
2171 * @param string &$after set to everything after the ':'
2172 * return string the position of the ':', or false if none found
2174 function findColonNoLinks($str, &$before, &$after) {
2175 $fname = 'Parser::findColonNoLinks';
2176 wfProfileIn( $fname );
2178 $pos = strpos( $str, ':' );
2179 if( $pos === false ) {
2181 wfProfileOut( $fname );
2185 $lt = strpos( $str, '<' );
2186 if( $lt === false ||
$lt > $pos ) {
2187 // Easy; no tag nesting to worry about
2188 $before = substr( $str, 0, $pos );
2189 $after = substr( $str, $pos+
1 );
2190 wfProfileOut( $fname );
2194 // Ugly state machine to walk through avoiding tags.
2195 $state = MW_COLON_STATE_TEXT
;
2197 $len = strlen( $str );
2198 for( $i = 0; $i < $len; $i++
) {
2202 // (Using the number is a performance hack for common cases)
2203 case 0: // MW_COLON_STATE_TEXT:
2206 // Could be either a <start> tag or an </end> tag
2207 $state = MW_COLON_STATE_TAGSTART
;
2212 $before = substr( $str, 0, $i );
2213 $after = substr( $str, $i +
1 );
2214 wfProfileOut( $fname );
2217 // Embedded in a tag; don't break it.
2220 // Skip ahead looking for something interesting
2221 $colon = strpos( $str, ':', $i );
2222 if( $colon === false ) {
2223 // Nothing else interesting
2224 wfProfileOut( $fname );
2227 $lt = strpos( $str, '<', $i );
2228 if( $stack === 0 ) {
2229 if( $lt === false ||
$colon < $lt ) {
2231 $before = substr( $str, 0, $colon );
2232 $after = substr( $str, $colon +
1 );
2233 wfProfileOut( $fname );
2237 if( $lt === false ) {
2238 // Nothing else interesting to find; abort!
2239 // We're nested, but there's no close tags left. Abort!
2242 // Skip ahead to next tag start
2244 $state = MW_COLON_STATE_TAGSTART
;
2247 case 1: // MW_COLON_STATE_TAG:
2252 $state = MW_COLON_STATE_TEXT
;
2255 // Slash may be followed by >?
2256 $state = MW_COLON_STATE_TAGSLASH
;
2262 case 2: // MW_COLON_STATE_TAGSTART:
2265 $state = MW_COLON_STATE_CLOSETAG
;
2268 $state = MW_COLON_STATE_COMMENT
;
2271 // Illegal early close? This shouldn't happen D:
2272 $state = MW_COLON_STATE_TEXT
;
2275 $state = MW_COLON_STATE_TAG
;
2278 case 3: // MW_COLON_STATE_CLOSETAG:
2283 wfDebug( "Invalid input in $fname; too many close tags\n" );
2284 wfProfileOut( $fname );
2287 $state = MW_COLON_STATE_TEXT
;
2290 case MW_COLON_STATE_TAGSLASH
:
2292 // Yes, a self-closed tag <blah/>
2293 $state = MW_COLON_STATE_TEXT
;
2295 // Probably we're jumping the gun, and this is an attribute
2296 $state = MW_COLON_STATE_TAG
;
2299 case 5: // MW_COLON_STATE_COMMENT:
2301 $state = MW_COLON_STATE_COMMENTDASH
;
2304 case MW_COLON_STATE_COMMENTDASH
:
2306 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2308 $state = MW_COLON_STATE_COMMENT
;
2311 case MW_COLON_STATE_COMMENTDASHDASH
:
2313 $state = MW_COLON_STATE_TEXT
;
2315 $state = MW_COLON_STATE_COMMENT
;
2319 throw new MWException( "State machine error in $fname" );
2323 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2326 wfProfileOut( $fname );
2331 * Return value of a magic variable (like PAGENAME)
2335 function getVariableValue( $index ) {
2336 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2339 * Some of these require message or data lookups and can be
2340 * expensive to check many times.
2342 static $varCache = array();
2343 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2344 if ( isset( $varCache[$index] ) ) {
2345 return $varCache[$index];
2350 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2353 global $wgLocaltimezone;
2354 if ( isset( $wgLocaltimezone ) ) {
2355 $oldtz = getenv( 'TZ' );
2356 putenv( 'TZ='.$wgLocaltimezone );
2358 $localTimestamp = date( 'YmdHis', $ts );
2359 $localMonth = date( 'm', $ts );
2360 $localMonthName = date( 'n', $ts );
2361 $localDay = date( 'j', $ts );
2362 $localDay2 = date( 'd', $ts );
2363 $localDayOfWeek = date( 'w', $ts );
2364 $localWeek = date( 'W', $ts );
2365 $localYear = date( 'Y', $ts );
2366 $localHour = date( 'H', $ts );
2367 if ( isset( $wgLocaltimezone ) ) {
2368 putenv( 'TZ='.$oldtz );
2372 case 'currentmonth':
2373 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2374 case 'currentmonthname':
2375 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2376 case 'currentmonthnamegen':
2377 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2378 case 'currentmonthabbrev':
2379 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2381 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2383 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2385 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2386 case 'localmonthname':
2387 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2388 case 'localmonthnamegen':
2389 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2390 case 'localmonthabbrev':
2391 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2393 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2395 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2397 return $this->mTitle
->getText();
2399 return $this->mTitle
->getPartialURL();
2400 case 'fullpagename':
2401 return $this->mTitle
->getPrefixedText();
2402 case 'fullpagenamee':
2403 return $this->mTitle
->getPrefixedURL();
2405 return $this->mTitle
->getSubpageText();
2406 case 'subpagenamee':
2407 return $this->mTitle
->getSubpageUrlForm();
2408 case 'basepagename':
2409 return $this->mTitle
->getBaseText();
2410 case 'basepagenamee':
2411 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2412 case 'talkpagename':
2413 if( $this->mTitle
->canTalk() ) {
2414 $talkPage = $this->mTitle
->getTalkPage();
2415 return $talkPage->getPrefixedText();
2419 case 'talkpagenamee':
2420 if( $this->mTitle
->canTalk() ) {
2421 $talkPage = $this->mTitle
->getTalkPage();
2422 return $talkPage->getPrefixedUrl();
2426 case 'subjectpagename':
2427 $subjPage = $this->mTitle
->getSubjectPage();
2428 return $subjPage->getPrefixedText();
2429 case 'subjectpagenamee':
2430 $subjPage = $this->mTitle
->getSubjectPage();
2431 return $subjPage->getPrefixedUrl();
2433 return $this->mRevisionId
;
2435 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 ) );
2436 case 'revisionday2':
2437 return substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 );
2438 case 'revisionmonth':
2439 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 4, 2 ) );
2440 case 'revisionyear':
2441 return substr( wfRevisionTimestamp( $this->mRevisionId
), 0, 4 );
2442 case 'revisiontimestamp':
2443 return wfRevisionTimestamp( $this->mRevisionId
);
2445 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2447 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2449 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2451 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2452 case 'subjectspace':
2453 return $this->mTitle
->getSubjectNsText();
2454 case 'subjectspacee':
2455 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2456 case 'currentdayname':
2457 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2459 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2461 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2463 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2465 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2466 // int to remove the padding
2467 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2469 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2470 case 'localdayname':
2471 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2473 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2475 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2477 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2479 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2480 // int to remove the padding
2481 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2483 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2484 case 'numberofarticles':
2485 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2486 case 'numberoffiles':
2487 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2488 case 'numberofusers':
2489 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2490 case 'numberofpages':
2491 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2492 case 'numberofadmins':
2493 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2494 case 'currenttimestamp':
2495 return $varCache[$index] = wfTimestampNow();
2496 case 'localtimestamp':
2497 return $varCache[$index] = $localTimestamp;
2498 case 'currentversion':
2499 return $varCache[$index] = SpecialVersion
::getVersion();
2505 return $wgServerName;
2507 return $wgScriptPath;
2508 case 'directionmark':
2509 return $wgContLang->getDirMark();
2510 case 'contentlanguage':
2511 global $wgContLanguageCode;
2512 return $wgContLanguageCode;
2515 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2523 * initialise the magic variables (like CURRENTMONTHNAME)
2527 function initialiseVariables() {
2528 $fname = 'Parser::initialiseVariables';
2529 wfProfileIn( $fname );
2530 $variableIDs = MagicWord
::getVariableIDs();
2532 $this->mVariables
= array();
2533 foreach ( $variableIDs as $id ) {
2534 $mw =& MagicWord
::get( $id );
2535 $mw->addToArray( $this->mVariables
, $id );
2537 wfProfileOut( $fname );
2541 * parse any parentheses in format ((title|part|part))
2542 * and call callbacks to get a replacement text for any found piece
2544 * @param string $text The text to parse
2545 * @param array $callbacks rules in form:
2546 * '{' => array( # opening parentheses
2547 * 'end' => '}', # closing parentheses
2548 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2549 * 3 => callback # replacement callback to call if {{{..}}} is found
2552 * 'min' => 2, # Minimum parenthesis count in cb
2553 * 'max' => 3, # Maximum parenthesis count in cb
2556 function replace_callback ($text, $callbacks) {
2557 wfProfileIn( __METHOD__
);
2558 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2559 $lastOpeningBrace = -1; # last not closed parentheses
2561 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2564 while ( $i < strlen( $text ) ) {
2565 # Find next opening brace, closing brace or pipe
2566 if ( $lastOpeningBrace == -1 ) {
2567 $currentClosing = '';
2568 $search = $validOpeningBraces;
2570 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2571 $search = $validOpeningBraces . '|' . $currentClosing;
2574 $i +
= strcspn( $text, $search, $i );
2575 if ( $i < strlen( $text ) ) {
2576 if ( $text[$i] == '|' ) {
2578 } elseif ( $text[$i] == $currentClosing ) {
2580 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2582 $rule = $callbacks[$text[$i]];
2584 # Some versions of PHP have a strcspn which stops on null characters
2585 # Ignore and continue
2594 if ( $found == 'open' ) {
2595 # found opening brace, let's add it to parentheses stack
2596 $piece = array('brace' => $text[$i],
2597 'braceEnd' => $rule['end'],
2601 # count opening brace characters
2602 $piece['count'] = strspn( $text, $piece['brace'], $i );
2603 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2604 $i +
= $piece['count'];
2606 # we need to add to stack only if opening brace count is enough for one of the rules
2607 if ( $piece['count'] >= $rule['min'] ) {
2608 $lastOpeningBrace ++
;
2609 $openingBraceStack[$lastOpeningBrace] = $piece;
2611 } elseif ( $found == 'close' ) {
2612 # lets check if it is enough characters for closing brace
2613 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2614 $count = strspn( $text, $text[$i], $i, $maxCount );
2616 # check for maximum matching characters (if there are 5 closing
2617 # characters, we will probably need only 3 - depending on the rules)
2619 $matchingCallback = null;
2620 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2621 if ( $count > $cbType['max'] ) {
2622 # The specified maximum exists in the callback array, unless the caller
2624 $matchingCount = $cbType['max'];
2626 # Count is less than the maximum
2627 # Skip any gaps in the callback array to find the true largest match
2628 # Need to use array_key_exists not isset because the callback can be null
2629 $matchingCount = $count;
2630 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2635 if ($matchingCount <= 0) {
2639 $matchingCallback = $cbType['cb'][$matchingCount];
2641 # let's set a title or last part (if '|' was found)
2642 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2643 $openingBraceStack[$lastOpeningBrace]['title'] =
2644 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2645 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2647 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2648 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2649 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2652 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2653 $pieceEnd = $i +
$matchingCount;
2655 if( is_callable( $matchingCallback ) ) {
2657 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2658 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2659 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2660 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2662 # finally we can call a user callback and replace piece of text
2663 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2664 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2665 $i = $pieceStart +
strlen($replaceWith);
2667 # null value for callback means that parentheses should be parsed, but not replaced
2668 $i +
= $matchingCount;
2671 # reset last opening parentheses, but keep it in case there are unused characters
2672 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2673 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2674 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2677 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2678 $openingBraceStack[$lastOpeningBrace--] = null;
2680 if ($matchingCount < $piece['count']) {
2681 $piece['count'] -= $matchingCount;
2682 $piece['startAt'] -= $matchingCount;
2683 $piece['partStart'] = $piece['startAt'];
2684 # do we still qualify for any callback with remaining count?
2685 $currentCbList = $callbacks[$piece['brace']]['cb'];
2686 while ( $piece['count'] ) {
2687 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2688 $lastOpeningBrace++
;
2689 $openingBraceStack[$lastOpeningBrace] = $piece;
2695 } elseif ( $found == 'pipe' ) {
2696 # lets set a title if it is a first separator, or next part otherwise
2697 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2698 $openingBraceStack[$lastOpeningBrace]['title'] =
2699 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2700 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2701 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2703 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2704 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2705 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2707 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2711 wfProfileOut( __METHOD__
);
2716 * Replace magic variables, templates, and template arguments
2717 * with the appropriate text. Templates are substituted recursively,
2718 * taking care to avoid infinite loops.
2720 * Note that the substitution depends on value of $mOutputType:
2721 * OT_WIKI: only {{subst:}} templates
2722 * OT_MSG: only magic variables
2723 * OT_HTML: all templates and magic variables
2725 * @param string $tex The text to transform
2726 * @param array $args Key-value pairs representing template parameters to substitute
2727 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2730 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2731 # Prevent too big inclusions
2732 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2736 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2737 wfProfileIn( $fname );
2739 # This function is called recursively. To keep track of arguments we need a stack:
2740 array_push( $this->mArgStack
, $args );
2742 $braceCallbacks = array();
2744 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2746 if ( $this->mOutputType
!= OT_MSG
) {
2747 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2749 if ( $braceCallbacks ) {
2753 'cb' => $braceCallbacks,
2754 'min' => $argsOnly ?
3 : 2,
2755 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2759 'cb' => array(2=>null),
2764 $text = $this->replace_callback ($text, $callbacks);
2766 array_pop( $this->mArgStack
);
2768 wfProfileOut( $fname );
2773 * Replace magic variables
2776 function variableSubstitution( $matches ) {
2778 $fname = 'Parser::variableSubstitution';
2779 $varname = $wgContLang->lc($matches[1]);
2780 wfProfileIn( $fname );
2782 if ( $this->mOutputType
== OT_WIKI
) {
2783 # Do only magic variables prefixed by SUBST
2784 $mwSubst =& MagicWord
::get( 'subst' );
2785 if (!$mwSubst->matchStartAndRemove( $varname ))
2787 # Note that if we don't substitute the variable below,
2788 # we don't remove the {{subst:}} magic word, in case
2789 # it is a template rather than a magic variable.
2791 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2792 $id = $this->mVariables
[$varname];
2793 # Now check if we did really match, case sensitive or not
2794 $mw =& MagicWord
::get( $id );
2795 if ($mw->match($matches[1])) {
2796 $text = $this->getVariableValue( $id );
2797 $this->mOutput
->mContainsOldMagic
= true;
2799 $text = $matches[0];
2802 $text = $matches[0];
2804 wfProfileOut( $fname );
2809 * Return the text of a template, after recursively
2810 * replacing any variables or templates within the template.
2812 * @param array $piece The parts of the template
2813 * $piece['text']: matched text
2814 * $piece['title']: the title, i.e. the part before the |
2815 * $piece['parts']: the parameter array
2816 * @return string the text of the template
2819 function braceSubstitution( $piece ) {
2820 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2821 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2822 wfProfileIn( $fname );
2823 wfProfileIn( __METHOD__
.'-setup' );
2826 $found = false; # $text has been filled
2827 $nowiki = false; # wiki markup in $text should be escaped
2828 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2829 $noargs = false; # Don't replace triple-brace arguments in $text
2830 $replaceHeadings = false; # Make the edit section links go to the template not the article
2831 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2832 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2834 # Title object, where $text came from
2840 # $part1 is the bit before the first |, and must contain only title characters
2841 # $args is a list of arguments, starting from index 0, not including $part1
2843 $titleText = $part1 = $piece['title'];
2844 # If the third subpattern matched anything, it will start with |
2846 if (null == $piece['parts']) {
2847 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2848 if ($replaceWith != $piece['text']) {
2849 $text = $replaceWith;
2856 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2857 wfProfileOut( __METHOD__
.'-setup' );
2860 wfProfileIn( __METHOD__
.'-modifiers' );
2862 $mwSubst =& MagicWord
::get( 'subst' );
2863 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2864 # One of two possibilities is true:
2865 # 1) Found SUBST but not in the PST phase
2866 # 2) Didn't find SUBST and in the PST phase
2867 # In either case, return without further processing
2868 $text = $piece['text'];
2875 # MSG, MSGNW and RAW
2878 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2879 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2882 # Remove obsolete MSG:
2883 $mwMsg =& MagicWord
::get( 'msg' );
2884 $mwMsg->matchStartAndRemove( $part1 );
2888 $mwRaw =& MagicWord
::get( 'raw' );
2889 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2890 $forceRawInterwiki = true;
2893 wfProfileOut( __METHOD__
.'-modifiers' );
2897 wfProfileIn( __METHOD__
. '-pfunc' );
2899 $colonPos = strpos( $part1, ':' );
2900 if ( $colonPos !== false ) {
2901 # Case sensitive functions
2902 $function = substr( $part1, 0, $colonPos );
2903 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2904 $function = $this->mFunctionSynonyms
[1][$function];
2906 # Case insensitive functions
2907 $function = strtolower( $function );
2908 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2909 $function = $this->mFunctionSynonyms
[0][$function];
2915 $funcArgs = array_map( 'trim', $args );
2916 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2917 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2920 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2924 if ( is_array( $result ) ) {
2925 if ( isset( $result[0] ) ) {
2926 $text = $linestart . $result[0];
2927 unset( $result[0] );
2930 // Extract flags into the local scope
2931 // This allows callers to set flags such as nowiki, noparse, found, etc.
2934 $text = $linestart . $result;
2938 wfProfileOut( __METHOD__
. '-pfunc' );
2941 # Template table test
2943 # Did we encounter this template already? If yes, it is in the cache
2944 # and we need to check for loops.
2945 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2948 # Infinite loop test
2949 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2953 $text = $linestart .
2954 "[[$part1]]<!-- WARNING: template loop detected -->";
2955 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2957 # set $text to cached message.
2958 $text = $linestart . $this->mTemplates
[$piece['title']];
2962 # Load from database
2963 $lastPathLevel = $this->mTemplatePath
;
2965 wfProfileIn( __METHOD__
. '-loadtpl' );
2967 # declaring $subpage directly in the function call
2968 # does not work correctly with references and breaks
2969 # {{/subpage}}-style inclusions
2971 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2972 if ($subpage !== '') {
2973 $ns = $this->mTitle
->getNamespace();
2975 $title = Title
::newFromText( $part1, $ns );
2978 if ( !is_null( $title ) ) {
2979 $titleText = $title->getPrefixedText();
2980 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2981 # Check for language variants if the template is not found
2982 if($checkVariantLink && $title->getArticleID() == 0){
2983 $wgContLang->findVariantLink($part1, $title);
2986 if ( !$title->isExternal() ) {
2987 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2988 $text = SpecialPage
::capturePath( $title );
2989 if ( is_string( $text ) ) {
2994 $this->disableCache();
2997 $articleContent = $this->fetchTemplate( $title );
2998 if ( $articleContent !== false ) {
3000 $text = $articleContent;
3001 $replaceHeadings = true;
3005 # If the title is valid but undisplayable, make a link to it
3006 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3007 $text = "[[:$titleText]]";
3010 } elseif ( $title->isTrans() ) {
3011 // Interwiki transclusion
3012 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3013 $text = $this->interwikiTransclude( $title, 'render' );
3017 $text = $this->interwikiTransclude( $title, 'raw' );
3018 $replaceHeadings = true;
3023 # Template cache array insertion
3024 # Use the original $piece['title'] not the mangled $part1, so that
3025 # modifiers such as RAW: produce separate cache entries
3028 // A special page; don't store it in the template cache.
3030 $this->mTemplates
[$piece['title']] = $text;
3032 $text = $linestart . $text;
3035 wfProfileOut( __METHOD__
. '-loadtpl' );
3038 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3039 # Error, oversize inclusion
3040 $text = $linestart .
3041 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3046 # Recursive parsing, escaping and link table handling
3047 # Only for HTML output
3048 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3049 $text = wfEscapeWikiText( $text );
3050 } elseif ( !$this->ot
['msg'] && $found ) {
3052 $assocArgs = array();
3054 # Clean up argument array
3055 $assocArgs = array();
3057 foreach( $args as $arg ) {
3058 $eqpos = strpos( $arg, '=' );
3059 if ( $eqpos === false ) {
3060 $assocArgs[$index++
] = $arg;
3062 $name = trim( substr( $arg, 0, $eqpos ) );
3063 $value = trim( substr( $arg, $eqpos+
1 ) );
3064 if ( $value === false ) {
3067 if ( $name !== false ) {
3068 $assocArgs[$name] = $value;
3073 # Add a new element to the templace recursion path
3074 $this->mTemplatePath
[$part1] = 1;
3078 # If there are any <onlyinclude> tags, only include them
3079 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3081 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3083 foreach ($m[1] as $piece)
3086 # Remove <noinclude> sections and <includeonly> tags
3087 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3088 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3090 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3091 # Strip <nowiki>, <pre>, etc.
3092 $text = $this->strip( $text, $this->mStripState
);
3093 if ( $this->ot
['html'] ) {
3094 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3095 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3096 $text = Sanitizer
::removeHTMLcomments( $text );
3099 $text = $this->replaceVariables( $text, $assocArgs );
3101 # If the template begins with a table or block-level
3102 # element, it should be treated as beginning a new line.
3103 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3104 $text = "\n" . $text;
3106 } elseif ( !$noargs ) {
3107 # $noparse and !$noargs
3108 # Just replace the arguments, not any double-brace items
3109 # This is used for rendered interwiki transclusion
3110 $text = $this->replaceVariables( $text, $assocArgs, true );
3113 # Prune lower levels off the recursion check path
3114 $this->mTemplatePath
= $lastPathLevel;
3116 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3117 # Error, oversize inclusion
3118 $text = $linestart .
3119 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3125 wfProfileOut( $fname );
3126 return $piece['text'];
3128 wfProfileIn( __METHOD__
. '-placeholders' );
3130 # Replace raw HTML by a placeholder
3131 # Add a blank line preceding, to prevent it from mucking up
3132 # immediately preceding headings
3133 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3135 # replace ==section headers==
3136 # XXX this needs to go away once we have a better parser.
3137 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3138 if( !is_null( $title ) )
3139 $encodedname = base64_encode($title->getPrefixedDBkey());
3141 $encodedname = base64_encode("");
3142 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3143 PREG_SPLIT_DELIM_CAPTURE
);
3146 for( $i = 0; $i < count($m); $i +
= 2 ) {
3148 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3150 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3155 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3156 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3157 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3163 wfProfileOut( __METHOD__
. '-placeholders' );
3166 # Prune lower levels off the recursion check path
3167 $this->mTemplatePath
= $lastPathLevel;
3170 wfProfileOut( $fname );
3171 return $piece['text'];
3173 wfProfileOut( $fname );
3179 * Fetch the unparsed text of a template and register a reference to it.
3181 function fetchTemplate( $title ) {
3183 // Loop to fetch the article, with up to 1 redirect
3184 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3185 $rev = Revision
::newFromTitle( $title );
3186 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3190 $text = $rev->getText();
3191 if ( $text === false ) {
3195 $title = Title
::newFromRedirect( $text );
3201 * Transclude an interwiki link.
3203 function interwikiTransclude( $title, $action ) {
3204 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3206 if (!$wgEnableScaryTranscluding)
3207 return wfMsg('scarytranscludedisabled');
3209 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3210 // But we'll handle it generally anyway
3211 if ( $title->getNamespace() ) {
3212 // Use the canonical namespace, which should work anywhere
3213 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3215 $articleName = $title->getDBkey();
3218 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3219 $url .= "?action=$action";
3220 if (strlen($url) > 255)
3221 return wfMsg('scarytranscludetoolong');
3222 return $this->fetchScaryTemplateMaybeFromCache($url);
3225 function fetchScaryTemplateMaybeFromCache($url) {
3226 global $wgTranscludeCacheExpiry;
3227 $dbr =& wfGetDB(DB_SLAVE
);
3228 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3229 array('tc_url' => $url));
3231 $time = $obj->tc_time
;
3232 $text = $obj->tc_contents
;
3233 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3238 $text = Http
::get($url);
3240 return wfMsg('scarytranscludefailed', $url);
3242 $dbw =& wfGetDB(DB_MASTER
);
3243 $dbw->replace('transcache', array('tc_url'), array(
3245 'tc_time' => time(),
3246 'tc_contents' => $text));
3252 * Triple brace replacement -- used for template arguments
3255 function argSubstitution( $matches ) {
3256 $arg = trim( $matches['title'] );
3257 $text = $matches['text'];
3258 $inputArgs = end( $this->mArgStack
);
3260 if ( array_key_exists( $arg, $inputArgs ) ) {
3261 $text = $inputArgs[$arg];
3262 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3263 null != $matches['parts'] && count($matches['parts']) > 0) {
3264 $text = $matches['parts'][0];
3266 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3267 $text = $matches['text'] .
3268 '<!-- WARNING: argument omitted, expansion size too large -->';
3275 * Increment an include size counter
3277 * @param string $type The type of expansion
3278 * @param integer $size The size of the text
3279 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3281 function incrementIncludeSize( $type, $size ) {
3282 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3285 $this->mIncludeSizes
[$type] +
= $size;
3291 * Detect __NOGALLERY__ magic word and set a placeholder
3293 function stripNoGallery( &$text ) {
3294 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3296 $mw = MagicWord
::get( 'nogallery' );
3297 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3301 * Detect __TOC__ magic word and set a placeholder
3303 function stripToc( $text ) {
3304 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3306 $mw = MagicWord
::get( 'notoc' );
3307 if( $mw->matchAndRemove( $text ) ) {
3308 $this->mShowToc
= false;
3311 $mw = MagicWord
::get( 'toc' );
3312 if( $mw->match( $text ) ) {
3313 $this->mShowToc
= true;
3314 $this->mForceTocPosition
= true;
3316 // Set a placeholder. At the end we'll fill it in with the TOC.
3317 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3319 // Only keep the first one.
3320 $text = $mw->replace( '', $text );
3326 * This function accomplishes several tasks:
3327 * 1) Auto-number headings if that option is enabled
3328 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3329 * 3) Add a Table of contents on the top for users who have enabled the option
3330 * 4) Auto-anchor headings
3332 * It loops through all headlines, collects the necessary data, then splits up the
3333 * string and re-inserts the newly formatted headlines.
3335 * @param string $text
3336 * @param boolean $isMain
3339 function formatHeadings( $text, $isMain=true ) {
3340 global $wgMaxTocLevel, $wgContLang;
3342 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3343 if( !$this->mTitle
->userCanEdit() ) {
3346 $showEditLink = $this->mOptions
->getEditSection();
3349 # Inhibit editsection links if requested in the page
3350 $esw =& MagicWord
::get( 'noeditsection' );
3351 if( $esw->matchAndRemove( $text ) ) {
3355 # Get all headlines for numbering them and adding funky stuff like [edit]
3356 # links - this is for later, but we need the number of headlines right now
3358 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3360 # if there are fewer than 4 headlines in the article, do not show TOC
3361 # unless it's been explicitly enabled.
3362 $enoughToc = $this->mShowToc
&&
3363 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3365 # Allow user to stipulate that a page should have a "new section"
3366 # link added via __NEWSECTIONLINK__
3367 $mw =& MagicWord
::get( 'newsectionlink' );
3368 if( $mw->matchAndRemove( $text ) )
3369 $this->mOutput
->setNewSection( true );
3371 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3372 # override above conditions and always show TOC above first header
3373 $mw =& MagicWord
::get( 'forcetoc' );
3374 if ($mw->matchAndRemove( $text ) ) {
3375 $this->mShowToc
= true;
3379 # Never ever show TOC if no headers
3380 if( $numMatches < 1 ) {
3384 # We need this to perform operations on the HTML
3385 $sk =& $this->mOptions
->getSkin();
3389 $sectionCount = 0; # headlineCount excluding template sections
3391 # Ugh .. the TOC should have neat indentation levels which can be
3392 # passed to the skin functions. These are determined here
3396 $sublevelCount = array();
3397 $levelCount = array();
3404 foreach( $matches[3] as $headline ) {
3406 $templatetitle = '';
3407 $templatesection = 0;
3410 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3412 $templatetitle = base64_decode($mat[1]);
3413 $templatesection = 1 +
(int)base64_decode($mat[2]);
3414 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3418 $prevlevel = $level;
3419 $prevtoclevel = $toclevel;
3421 $level = $matches[1][$headlineCount];
3423 if( $doNumberHeadings ||
$enoughToc ) {
3425 if ( $level > $prevlevel ) {
3426 # Increase TOC level
3428 $sublevelCount[$toclevel] = 0;
3429 if( $toclevel<$wgMaxTocLevel ) {
3430 $toc .= $sk->tocIndent();
3433 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3434 # Decrease TOC level, find level to jump to
3436 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3437 # Can only go down to level 1
3440 for ($i = $toclevel; $i > 0; $i--) {
3441 if ( $levelCount[$i] == $level ) {
3442 # Found last matching level
3446 elseif ( $levelCount[$i] < $level ) {
3447 # Found first matching level below current level
3453 if( $toclevel<$wgMaxTocLevel ) {
3454 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3458 # No change in level, end TOC line
3459 if( $toclevel<$wgMaxTocLevel ) {
3460 $toc .= $sk->tocLineEnd();
3464 $levelCount[$toclevel] = $level;
3466 # count number of headlines for each level
3467 @$sublevelCount[$toclevel]++
;
3469 for( $i = 1; $i <= $toclevel; $i++
) {
3470 if( !empty( $sublevelCount[$i] ) ) {
3474 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3480 # The canonized header is a version of the header text safe to use for links
3481 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3482 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3483 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3485 # Remove link placeholders by the link text.
3486 # <!--LINK number-->
3488 # link text with suffix
3489 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3490 "\$this->mLinkHolders['texts'][\$1]",
3491 $canonized_headline );
3492 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3493 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3494 $canonized_headline );
3497 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3498 $tocline = trim( $canonized_headline );
3499 # Save headline for section edit hint before it's escaped
3500 $headline_hint = trim( $canonized_headline );
3501 $canonized_headline = Sanitizer
::escapeId( $tocline );
3502 $refers[$headlineCount] = $canonized_headline;
3504 # count how many in assoc. array so we can track dupes in anchors
3505 @$refers[$canonized_headline]++
;
3506 $refcount[$headlineCount]=$refers[$canonized_headline];
3508 # Don't number the heading if it is the only one (looks silly)
3509 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3510 # the two are different if the line contains a link
3511 $headline=$numbering . ' ' . $headline;
3514 # Create the anchor for linking from the TOC to the section
3515 $anchor = $canonized_headline;
3516 if($refcount[$headlineCount] > 1 ) {
3517 $anchor .= '_' . $refcount[$headlineCount];
3519 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3520 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3522 # give headline the correct <h#> tag
3523 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><div class=\"mw-h$level\">";
3525 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3526 if ( empty( $head[$headlineCount] ) ) {
3527 $head[$headlineCount] = '';
3530 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3532 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3534 // Yes, the headline logically goes before the edit section. It can't
3535 // be put there, however, because of bugs in IE's and Firefox's float
3536 // rendering. See <https://bugzilla.mozilla.org/show_bug.cgi?id=50630>.
3537 $head[$headlineCount] .= " <h$level{$matches[2][$headlineCount]}$headline</h$level></div>";
3545 if( $toclevel<$wgMaxTocLevel ) {
3546 $toc .= $sk->tocUnindent( $toclevel - 1 );
3548 $toc = $sk->tocList( $toc );
3551 # split up and insert constructed headlines
3553 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3556 foreach( $blocks as $block ) {
3557 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3558 # This is the [edit] link that appears for the top block of text when
3559 # section editing is enabled
3561 # Disabled because it broke block formatting
3562 # For example, a bullet point in the top line
3563 # $full .= $sk->editSectionLink(0);
3566 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3567 # Top anchor now in skin
3571 if( !empty( $head[$i] ) ) {
3576 if( $this->mForceTocPosition
) {
3577 return str_replace( '<!--MWTOC-->', $toc, $full );
3584 * Transform wiki markup when saving a page by doing \r\n -> \n
3585 * conversion, substitting signatures, {{subst:}} templates, etc.
3587 * @param string $text the text to transform
3588 * @param Title &$title the Title object for the current article
3589 * @param User &$user the User object describing the current user
3590 * @param ParserOptions $options parsing options
3591 * @param bool $clearState whether to clear the parser state first
3592 * @return string the altered wiki markup
3595 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3596 $this->mOptions
= $options;
3597 $this->mTitle
=& $title;
3598 $this->setOutputType( OT_WIKI
);
3600 if ( $clearState ) {
3601 $this->clearState();
3604 $stripState = false;
3608 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3609 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3610 $text = $this->pstPass2( $text, $stripState, $user );
3611 $text = $this->unstrip( $text, $stripState );
3612 $text = $this->unstripNoWiki( $text, $stripState );
3617 * Pre-save transform helper function
3620 function pstPass2( $text, &$stripState, $user ) {
3621 global $wgContLang, $wgLocaltimezone;
3623 /* Note: This is the timestamp saved as hardcoded wikitext to
3624 * the database, we use $wgContLang here in order to give
3625 * everyone the same signature and use the default one rather
3626 * than the one selected in each user's preferences.
3628 if ( isset( $wgLocaltimezone ) ) {
3629 $oldtz = getenv( 'TZ' );
3630 putenv( 'TZ='.$wgLocaltimezone );
3632 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3633 ' (' . date( 'T' ) . ')';
3634 if ( isset( $wgLocaltimezone ) ) {
3635 putenv( 'TZ='.$oldtz );
3638 # Variable replacement
3639 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3640 $text = $this->replaceVariables( $text );
3642 # Strip out <nowiki> etc. added via replaceVariables
3643 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3646 $sigText = $this->getUserSig( $user );
3647 $text = strtr( $text, array(
3649 '~~~~' => "$sigText $d",
3653 # Context links: [[|name]] and [[name (context)|]]
3655 global $wgLegalTitleChars;
3656 $tc = "[$wgLegalTitleChars]";
3657 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3659 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3660 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3661 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3663 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3664 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3665 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3667 $t = $this->mTitle
->getText();
3669 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3670 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3671 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3672 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3674 # if there's no context, don't bother duplicating the title
3675 $text = preg_replace( $p2, '[[\\1]]', $text );
3678 # Trim trailing whitespace
3679 # __END__ tag allows for trailing
3680 # whitespace to be deliberately included
3681 $text = rtrim( $text );
3682 $mw =& MagicWord
::get( 'end' );
3683 $mw->matchAndRemove( $text );
3689 * Fetch the user's signature text, if any, and normalize to
3690 * validated, ready-to-insert wikitext.
3696 function getUserSig( &$user ) {
3697 $username = $user->getName();
3698 $nickname = $user->getOption( 'nickname' );
3699 $nickname = $nickname === '' ?
$username : $nickname;
3701 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3702 # Sig. might contain markup; validate this
3703 if( $this->validateSig( $nickname ) !== false ) {
3704 # Validated; clean up (if needed) and return it
3705 return $this->cleanSig( $nickname, true );
3707 # Failed to validate; fall back to the default
3708 $nickname = $username;
3709 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3713 // Make sure nickname doesnt get a sig in a sig
3714 $nickname = $this->cleanSigInSig( $nickname );
3716 # If we're still here, make it a link to the user page
3717 $userpage = $user->getUserPage();
3718 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3722 * Check that the user's signature contains no bad XML
3724 * @param string $text
3725 * @return mixed An expanded string, or false if invalid.
3727 function validateSig( $text ) {
3728 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3732 * Clean up signature text
3734 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3735 * 2) Substitute all transclusions
3737 * @param string $text
3738 * @param $parsing Whether we're cleaning (preferences save) or parsing
3739 * @return string Signature text
3741 function cleanSig( $text, $parsing = false ) {
3743 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3745 $substWord = MagicWord
::get( 'subst' );
3746 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3747 $substText = '{{' . $substWord->getSynonym( 0 );
3749 $text = preg_replace( $substRegex, $substText, $text );
3750 $text = $this->cleanSigInSig( $text );
3751 $text = $this->replaceVariables( $text );
3753 $this->clearState();
3758 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3759 * @param string $text
3760 * @return string Signature text with /~{3,5}/ removed
3762 function cleanSigInSig( $text ) {
3763 $text = preg_replace( '/~{3,5}/', '', $text );
3768 * Set up some variables which are usually set up in parse()
3769 * so that an external function can call some class members with confidence
3772 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3773 $this->mTitle
=& $title;
3774 $this->mOptions
= $options;
3775 $this->setOutputType( $outputType );
3776 if ( $clearState ) {
3777 $this->clearState();
3782 * Transform a MediaWiki message by replacing magic variables.
3784 * @param string $text the text to transform
3785 * @param ParserOptions $options options
3786 * @return string the text with variables substituted
3789 function transformMsg( $text, $options ) {
3791 static $executing = false;
3793 $fname = "Parser::transformMsg";
3795 # Guard against infinite recursion
3801 wfProfileIn($fname);
3804 $this->mTitle
= $wgTitle;
3806 $this->mTitle
= Title
::newFromText('msg');
3808 $this->mOptions
= $options;
3809 $this->setOutputType( OT_MSG
);
3810 $this->clearState();
3811 $text = $this->replaceVariables( $text );
3814 wfProfileOut($fname);
3819 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3820 * The callback should have the following form:
3821 * function myParserHook( $text, $params, &$parser ) { ... }
3823 * Transform and return $text. Use $parser for any required context, e.g. use
3824 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3828 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3829 * @param mixed $callback The callback function (and object) to use for the tag
3831 * @return The old value of the mTagHooks array associated with the hook
3833 function setHook( $tag, $callback ) {
3834 $tag = strtolower( $tag );
3835 $oldVal = @$this->mTagHooks
[$tag];
3836 $this->mTagHooks
[$tag] = $callback;
3842 * Create a function, e.g. {{sum:1|2|3}}
3843 * The callback function should have the form:
3844 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3846 * The callback may either return the text result of the function, or an array with the text
3847 * in element 0, and a number of flags in the other elements. The names of the flags are
3848 * specified in the keys. Valid flags are:
3849 * found The text returned is valid, stop processing the template. This
3851 * nowiki Wiki markup in the return value should be escaped
3852 * noparse Unsafe HTML tags should not be stripped, etc.
3853 * noargs Don't replace triple-brace arguments in the return value
3854 * isHTML The returned text is HTML, armour it against wikitext transformation
3858 * @param string $id The magic word ID
3859 * @param mixed $callback The callback function (and object) to use
3860 * @param integer $flags a combination of the following flags:
3861 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3863 * @return The old callback function for this name, if any
3865 function setFunctionHook( $id, $callback, $flags = 0 ) {
3866 $oldVal = @$this->mFunctionHooks
[$id];
3867 $this->mFunctionHooks
[$id] = $callback;
3869 # Add to function cache
3870 $mw = MagicWord
::get( $id );
3872 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3874 $synonyms = $mw->getSynonyms();
3875 $sensitive = intval( $mw->isCaseSensitive() );
3877 foreach ( $synonyms as $syn ) {
3879 if ( !$sensitive ) {
3880 $syn = strtolower( $syn );
3883 if ( !( $flags & SFH_NO_HASH
) ) {
3886 # Remove trailing colon
3887 if ( substr( $syn, -1, 1 ) == ':' ) {
3888 $syn = substr( $syn, 0, -1 );
3890 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3896 * Get all registered function hook identifiers
3900 function getFunctionHooks() {
3901 return array_keys( $this->mFunctionHooks
);
3905 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3906 * Placeholders created in Skin::makeLinkObj()
3907 * Returns an array of links found, indexed by PDBK:
3911 * $options is a bit field, RLH_FOR_UPDATE to select for update
3913 function replaceLinkHolders( &$text, $options = 0 ) {
3915 global $wgOutputReplace;
3918 $fname = 'Parser::replaceLinkHolders';
3919 wfProfileIn( $fname );
3923 $sk =& $this->mOptions
->getSkin();
3924 $linkCache =& LinkCache
::singleton();
3926 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3927 wfProfileIn( $fname.'-check' );
3928 $dbr =& wfGetDB( DB_SLAVE
);
3929 $page = $dbr->tableName( 'page' );
3930 $threshold = $wgUser->getOption('stubthreshold');
3933 asort( $this->mLinkHolders
['namespaces'] );
3938 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3940 $title = $this->mLinkHolders
['titles'][$key];
3942 # Skip invalid entries.
3943 # Result will be ugly, but prevents crash.
3944 if ( is_null( $title ) ) {
3947 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3949 # Check if it's a static known link, e.g. interwiki
3950 if ( $title->isAlwaysKnown() ) {
3951 $colours[$pdbk] = 1;
3952 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3953 $colours[$pdbk] = 1;
3954 $this->mOutput
->addLink( $title, $id );
3955 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3956 $colours[$pdbk] = 0;
3958 # Not in the link cache, add it to the query
3959 if ( !isset( $current ) ) {
3961 $query = "SELECT page_id, page_namespace, page_title";
3962 if ( $threshold > 0 ) {
3963 $query .= ', page_len, page_is_redirect';
3965 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3966 } elseif ( $current != $ns ) {
3968 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3973 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3978 if ( $options & RLH_FOR_UPDATE
) {
3979 $query .= ' FOR UPDATE';
3982 $res = $dbr->query( $query, $fname );
3984 # Fetch data and form into an associative array
3985 # non-existent = broken
3988 while ( $s = $dbr->fetchObject($res) ) {
3989 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3990 $pdbk = $title->getPrefixedDBkey();
3991 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3992 $this->mOutput
->addLink( $title, $s->page_id
);
3994 if ( $threshold > 0 ) {
3995 $size = $s->page_len
;
3996 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3997 $colours[$pdbk] = 1;
3999 $colours[$pdbk] = 2;
4002 $colours[$pdbk] = 1;
4006 wfProfileOut( $fname.'-check' );
4008 # Do a second query for different language variants of links (if needed)
4009 if($wgContLang->hasVariants()){
4010 $linkBatch = new LinkBatch();
4011 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
4013 // Add variants of links to link batch
4014 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4015 $title = $this->mLinkHolders
['titles'][$key];
4016 if ( is_null( $title ) )
4019 $pdbk = $title->getPrefixedDBkey();
4021 // generate all variants of the link title text
4022 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4024 // if link was not found (in first query), add all variants to query
4025 if ( !isset($colours[$pdbk]) ){
4026 foreach($allTextVariants as $textVariant){
4027 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4028 if(is_null($variantTitle)) continue;
4029 $linkBatch->addObj( $variantTitle );
4030 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4036 if(!$linkBatch->isEmpty()){
4038 $titleClause = $linkBatch->constructSet('page', $dbr);
4040 $variantQuery = "SELECT page_id, page_namespace, page_title";
4041 if ( $threshold > 0 ) {
4042 $variantQuery .= ', page_len, page_is_redirect';
4045 $variantQuery .= " FROM $page WHERE $titleClause";
4046 if ( $options & RLH_FOR_UPDATE
) {
4047 $variantQuery .= ' FOR UPDATE';
4050 $varRes = $dbr->query( $variantQuery, $fname );
4052 // for each found variants, figure out link holders and replace
4053 while ( $s = $dbr->fetchObject($varRes) ) {
4055 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4056 $varPdbk = $variantTitle->getPrefixedDBkey();
4057 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4058 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4060 $holderKeys = $variantMap[$varPdbk];
4062 // loop over link holders
4063 foreach($holderKeys as $key){
4064 $title = $this->mLinkHolders
['titles'][$key];
4065 if ( is_null( $title ) ) continue;
4067 $pdbk = $title->getPrefixedDBkey();
4069 if(!isset($colours[$pdbk])){
4070 // found link in some of the variants, replace the link holder data
4071 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4072 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4074 // set pdbk and colour
4075 $pdbks[$key] = $varPdbk;
4076 if ( $threshold > 0 ) {
4077 $size = $s->page_len
;
4078 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4079 $colours[$varPdbk] = 1;
4081 $colours[$varPdbk] = 2;
4085 $colours[$varPdbk] = 1;
4093 # Construct search and replace arrays
4094 wfProfileIn( $fname.'-construct' );
4095 $wgOutputReplace = array();
4096 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4097 $pdbk = $pdbks[$key];
4098 $searchkey = "<!--LINK $key-->";
4099 $title = $this->mLinkHolders
['titles'][$key];
4100 if ( empty( $colours[$pdbk] ) ) {
4101 $linkCache->addBadLinkObj( $title );
4102 $colours[$pdbk] = 0;
4103 $this->mOutput
->addLink( $title, 0 );
4104 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4105 $this->mLinkHolders
['texts'][$key],
4106 $this->mLinkHolders
['queries'][$key] );
4107 } elseif ( $colours[$pdbk] == 1 ) {
4108 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4109 $this->mLinkHolders
['texts'][$key],
4110 $this->mLinkHolders
['queries'][$key] );
4111 } elseif ( $colours[$pdbk] == 2 ) {
4112 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4113 $this->mLinkHolders
['texts'][$key],
4114 $this->mLinkHolders
['queries'][$key] );
4117 wfProfileOut( $fname.'-construct' );
4120 wfProfileIn( $fname.'-replace' );
4122 $text = preg_replace_callback(
4123 '/(<!--LINK .*?-->)/',
4124 "wfOutputReplaceMatches",
4127 wfProfileOut( $fname.'-replace' );
4130 # Now process interwiki link holders
4131 # This is quite a bit simpler than internal links
4132 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4133 wfProfileIn( $fname.'-interwiki' );
4134 # Make interwiki link HTML
4135 $wgOutputReplace = array();
4136 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4137 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4138 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4141 $text = preg_replace_callback(
4142 '/<!--IWLINK (.*?)-->/',
4143 "wfOutputReplaceMatches",
4145 wfProfileOut( $fname.'-interwiki' );
4148 wfProfileOut( $fname );
4153 * Replace <!--LINK--> link placeholders with plain text of links
4154 * (not HTML-formatted).
4155 * @param string $text
4158 function replaceLinkHoldersText( $text ) {
4159 $fname = 'Parser::replaceLinkHoldersText';
4160 wfProfileIn( $fname );
4162 $text = preg_replace_callback(
4163 '/<!--(LINK|IWLINK) (.*?)-->/',
4164 array( &$this, 'replaceLinkHoldersTextCallback' ),
4167 wfProfileOut( $fname );
4172 * @param array $matches
4176 function replaceLinkHoldersTextCallback( $matches ) {
4177 $type = $matches[1];
4179 if( $type == 'LINK' ) {
4180 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4181 return $this->mLinkHolders
['texts'][$key];
4183 } elseif( $type == 'IWLINK' ) {
4184 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4185 return $this->mInterwikiLinkHolders
['texts'][$key];
4192 * Tag hook handler for 'pre'.
4194 function renderPreTag( $text, $attribs ) {
4195 // Backwards-compatibility hack
4196 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4198 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4199 return wfOpenElement( 'pre', $attribs ) .
4200 wfEscapeHTMLTagsOnly( $content ) .
4205 * Renders an image gallery from a text with one line per image.
4206 * text labels may be given by using |-style alternative text. E.g.
4207 * Image:one.jpg|The number "1"
4208 * Image:tree.jpg|A tree
4209 * given as text will return the HTML of a gallery with two images,
4210 * labeled 'The number "1"' and
4213 function renderImageGallery( $text, $params ) {
4214 $ig = new ImageGallery();
4215 $ig->setShowBytes( false );
4216 $ig->setShowFilename( false );
4218 $ig->useSkin( $this->mOptions
->getSkin() );
4220 if( isset( $params['caption'] ) )
4221 $ig->setCaption( $params['caption'] );
4223 $lines = explode( "\n", $text );
4224 foreach ( $lines as $line ) {
4225 # match lines like these:
4226 # Image:someimage.jpg|This is some image
4228 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4230 if ( count( $matches ) == 0 ) {
4233 $tp = Title
::newFromText( $matches[1] );
4235 if( is_null( $nt ) ) {
4236 # Bogus title. Ignore these so we don't bomb out later.
4239 if ( isset( $matches[3] ) ) {
4240 $label = $matches[3];
4245 $pout = $this->parse( $label,
4248 false, // Strip whitespace...?
4249 false // Don't clear state!
4251 $html = $pout->getText();
4253 $ig->add( new Image( $nt ), $html );
4255 # Only add real images (bug #5586)
4256 if ( $nt->getNamespace() == NS_IMAGE
) {
4257 $this->mOutput
->addImage( $nt->getDBkey() );
4260 return $ig->toHTML();
4264 * Parse image options text and use it to make an image
4266 function makeImage( $nt, $options ) {
4267 global $wgUseImageResize, $wgDjvuRenderer;
4271 # Check if the options text is of the form "options|alt text"
4273 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4274 # * left no resizing, just left align. label is used for alt= only
4275 # * right same, but right aligned
4276 # * none same, but not aligned
4277 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4278 # * center center the image
4279 # * framed Keep original image size, no magnify-button.
4281 $part = explode( '|', $options);
4283 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4284 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4285 $mwLeft =& MagicWord
::get( 'img_left' );
4286 $mwRight =& MagicWord
::get( 'img_right' );
4287 $mwNone =& MagicWord
::get( 'img_none' );
4288 $mwWidth =& MagicWord
::get( 'img_width' );
4289 $mwCenter =& MagicWord
::get( 'img_center' );
4290 $mwFramed =& MagicWord
::get( 'img_framed' );
4291 $mwPage =& MagicWord
::get( 'img_page' );
4294 $width = $height = $framed = $thumb = false;
4296 $manual_thumb = '' ;
4298 foreach( $part as $val ) {
4299 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4301 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4302 # use manually specified thumbnail
4304 $manual_thumb = $match;
4305 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4306 # remember to set an alignment, don't render immediately
4308 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4309 # remember to set an alignment, don't render immediately
4311 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4312 # remember to set an alignment, don't render immediately
4314 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4315 # remember to set an alignment, don't render immediately
4317 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4318 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4319 # Select a page in a multipage document
4321 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4322 wfDebug( "img_width match: $match\n" );
4323 # $match is the image width in pixels
4325 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4326 $width = intval( $m[1] );
4327 $height = intval( $m[2] );
4329 $width = intval($match);
4331 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4337 # Strip bad stuff out of the alt text
4338 $alt = $this->replaceLinkHoldersText( $caption );
4340 # make sure there are no placeholders in thumbnail attributes
4341 # that are later expanded to html- so expand them now and
4343 $alt = $this->unstrip($alt, $this->mStripState
);
4344 $alt = Sanitizer
::stripAllTags( $alt );
4346 # Linker does the rest
4347 $sk =& $this->mOptions
->getSkin();
4348 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4352 * Set a flag in the output object indicating that the content is dynamic and
4353 * shouldn't be cached.
4355 function disableCache() {
4356 wfDebug( "Parser output marked as uncacheable.\n" );
4357 $this->mOutput
->mCacheTime
= -1;
4361 * Callback from the Sanitizer for expanding items found in HTML attribute
4362 * values, so they can be safely tested and escaped.
4363 * @param string $text
4364 * @param array $args
4368 function attributeStripCallback( &$text, $args ) {
4369 $text = $this->replaceVariables( $text, $args );
4370 $text = $this->unstripForHTML( $text );
4374 function unstripForHTML( $text ) {
4375 $text = $this->unstrip( $text, $this->mStripState
);
4376 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4384 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4385 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4386 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4392 function getTags() { return array_keys( $this->mTagHooks
); }
4397 * Break wikitext input into sections, and either pull or replace
4398 * some particular section's text.
4400 * External callers should use the getSection and replaceSection methods.
4402 * @param $text Page wikitext
4403 * @param $section Numbered section. 0 pulls the text before the first
4404 * heading; other numbers will pull the given section
4405 * along with its lower-level subsections.
4406 * @param $mode One of "get" or "replace"
4407 * @param $newtext Replacement text for section data.
4408 * @return string for "get", the extracted section text.
4409 * for "replace", the whole page with the section replaced.
4411 private function extractSections( $text, $section, $mode, $newtext='' ) {
4412 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4413 # comments to be stripped as well)
4414 $striparray = array();
4416 $oldOutputType = $this->mOutputType
;
4417 $oldOptions = $this->mOptions
;
4418 $this->mOptions
= new ParserOptions();
4419 $this->setOutputType( OT_WIKI
);
4421 $striptext = $this->strip( $text, $striparray, true );
4423 $this->setOutputType( $oldOutputType );
4424 $this->mOptions
= $oldOptions;
4426 # now that we can be sure that no pseudo-sections are in the source,
4427 # split it up by section
4428 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4429 $comment = "(?:$uniq-!--.*?QINU)";
4434 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4436 (=+) # Should this be limited to 6?
4437 .+? # Section title...
4438 \\2 # Ending = count must match start
4445 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4452 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4453 (=+) # Should this be limited to 6?
4454 .+? # Section title...
4455 \\2 # Ending = count must match start
4456 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4465 PREG_SPLIT_DELIM_CAPTURE
);
4467 if( $mode == "get" ) {
4468 if( $section == 0 ) {
4469 // "Section 0" returns the content before any other section.
4474 } elseif( $mode == "replace" ) {
4475 if( $section == 0 ) {
4476 $rv = $newtext . "\n\n";
4485 for( $index = 1; $index < count( $secs ); ) {
4486 $headerLine = $secs[$index++
];
4487 if( $secs[$index] ) {
4489 $headerLevel = strlen( $secs[$index++
] );
4493 $headerLevel = intval( $secs[$index++
] );
4495 $content = $secs[$index++
];
4498 if( $mode == "get" ) {
4499 if( $count == $section ) {
4500 $rv = $headerLine . $content;
4501 $sectionLevel = $headerLevel;
4502 } elseif( $count > $section ) {
4503 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4504 $rv .= $headerLine . $content;
4506 // Broke out to a higher-level section
4510 } elseif( $mode == "replace" ) {
4511 if( $count < $section ) {
4512 $rv .= $headerLine . $content;
4513 } elseif( $count == $section ) {
4514 $rv .= $newtext . "\n\n";
4515 $sectionLevel = $headerLevel;
4516 } elseif( $count > $section ) {
4517 if( $headerLevel <= $sectionLevel ) {
4518 // Passed the section's sub-parts.
4522 $rv .= $headerLine . $content;
4527 # reinsert stripped tags
4528 $rv = $this->unstrip( $rv, $striparray );
4529 $rv = $this->unstripNoWiki( $rv, $striparray );
4535 * This function returns the text of a section, specified by a number ($section).
4536 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4537 * the first section before any such heading (section 0).
4539 * If a section contains subsections, these are also returned.
4541 * @param $text String: text to look in
4542 * @param $section Integer: section number
4543 * @return string text of the requested section
4545 function getSection( $text, $section ) {
4546 return $this->extractSections( $text, $section, "get" );
4549 function replaceSection( $oldtext, $section, $text ) {
4550 return $this->extractSections( $oldtext, $section, "replace", $text );
4557 * @package MediaWiki
4561 var $mText, # The output text
4562 $mLanguageLinks, # List of the full text of language links, in the order they appear
4563 $mCategories, # Map of category names to sort keys
4564 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4565 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4566 $mVersion, # Compatibility check
4567 $mTitleText, # title text of the chosen language variant
4568 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4569 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4570 $mImages, # DB keys of the images used, in the array key only
4571 $mExternalLinks, # External link URLs, in the key only
4572 $mHTMLtitle, # Display HTML title
4573 $mSubtitle, # Additional subtitle
4574 $mNewSection, # Show a new section link?
4575 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4577 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4578 $containsOldMagic = false, $titletext = '' )
4580 $this->mText
= $text;
4581 $this->mLanguageLinks
= $languageLinks;
4582 $this->mCategories
= $categoryLinks;
4583 $this->mContainsOldMagic
= $containsOldMagic;
4584 $this->mCacheTime
= '';
4585 $this->mVersion
= MW_PARSER_VERSION
;
4586 $this->mTitleText
= $titletext;
4587 $this->mLinks
= array();
4588 $this->mTemplates
= array();
4589 $this->mImages
= array();
4590 $this->mExternalLinks
= array();
4591 $this->mHTMLtitle
= "" ;
4592 $this->mSubtitle
= "" ;
4593 $this->mNewSection
= false;
4594 $this->mNoGallery
= false;
4597 function getText() { return $this->mText
; }
4598 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4599 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4600 function &getCategories() { return $this->mCategories
; }
4601 function getCacheTime() { return $this->mCacheTime
; }
4602 function getTitleText() { return $this->mTitleText
; }
4603 function &getLinks() { return $this->mLinks
; }
4604 function &getTemplates() { return $this->mTemplates
; }
4605 function &getImages() { return $this->mImages
; }
4606 function &getExternalLinks() { return $this->mExternalLinks
; }
4607 function getNoGallery() { return $this->mNoGallery
; }
4608 function getSubtitle() { return $this->mSubtitle
; }
4610 function containsOldMagic() { return $this->mContainsOldMagic
; }
4611 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4612 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4613 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4614 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4615 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4616 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4617 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4619 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4620 function addImage( $name ) { $this->mImages
[$name] = 1; }
4621 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4622 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4624 function setNewSection( $value ) {
4625 $this->mNewSection
= (bool)$value;
4627 function getNewSection() {
4628 return (bool)$this->mNewSection
;
4631 function addLink( $title, $id = null ) {
4632 $ns = $title->getNamespace();
4633 $dbk = $title->getDBkey();
4634 if ( !isset( $this->mLinks
[$ns] ) ) {
4635 $this->mLinks
[$ns] = array();
4637 if ( is_null( $id ) ) {
4638 $id = $title->getArticleID();
4640 $this->mLinks
[$ns][$dbk] = $id;
4643 function addTemplate( $title, $id ) {
4644 $ns = $title->getNamespace();
4645 $dbk = $title->getDBkey();
4646 if ( !isset( $this->mTemplates
[$ns] ) ) {
4647 $this->mTemplates
[$ns] = array();
4649 $this->mTemplates
[$ns][$dbk] = $id;
4653 * Return true if this cached output object predates the global or
4654 * per-article cache invalidation timestamps, or if it comes from
4655 * an incompatible older version.
4657 * @param string $touched the affected article's last touched timestamp
4661 function expired( $touched ) {
4662 global $wgCacheEpoch;
4663 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4664 $this->getCacheTime() < $touched ||
4665 $this->getCacheTime() <= $wgCacheEpoch ||
4666 !isset( $this->mVersion
) ||
4667 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4672 * Set options of the Parser
4674 * @package MediaWiki
4678 # All variables are supposed to be private in theory, although in practise this is not the case.
4679 var $mUseTeX; # Use texvc to expand <math> tags
4680 var $mUseDynamicDates; # Use DateFormatter to format dates
4681 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4682 var $mAllowExternalImages; # Allow external images inline
4683 var $mAllowExternalImagesFrom; # If not, any exception?
4684 var $mSkin; # Reference to the preferred skin
4685 var $mDateFormat; # Date format index
4686 var $mEditSection; # Create "edit section" links
4687 var $mNumberHeadings; # Automatically number headings
4688 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4689 var $mTidy; # Ask for tidy cleanup
4690 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4691 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4692 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4694 var $mUser; # Stored user object, just used to initialise the skin
4696 function getUseTeX() { return $this->mUseTeX
; }
4697 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4698 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4699 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4700 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4701 function getEditSection() { return $this->mEditSection
; }
4702 function getNumberHeadings() { return $this->mNumberHeadings
; }
4703 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4704 function getTidy() { return $this->mTidy
; }
4705 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4706 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4707 function getRemoveComments() { return $this->mRemoveComments
; }
4709 function &getSkin() {
4710 if ( !isset( $this->mSkin
) ) {
4711 $this->mSkin
= $this->mUser
->getSkin();
4713 return $this->mSkin
;
4716 function getDateFormat() {
4717 if ( !isset( $this->mDateFormat
) ) {
4718 $this->mDateFormat
= $this->mUser
->getDatePreference();
4720 return $this->mDateFormat
;
4723 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4724 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4725 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4726 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4727 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4728 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4729 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4730 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4731 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4732 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4733 function setSkin( $x ) { $this->mSkin
= $x; }
4734 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4735 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4736 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4738 function ParserOptions( $user = null ) {
4739 $this->initialiseFromUser( $user );
4743 * Get parser options
4746 static function newFromUser( $user ) {
4747 return new ParserOptions( $user );
4750 /** Get user options */
4751 function initialiseFromUser( $userInput ) {
4752 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4753 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4754 $fname = 'ParserOptions::initialiseFromUser';
4755 wfProfileIn( $fname );
4756 if ( !$userInput ) {
4758 if ( isset( $wgUser ) ) {
4764 $user =& $userInput;
4767 $this->mUser
= $user;
4769 $this->mUseTeX
= $wgUseTeX;
4770 $this->mUseDynamicDates
= $wgUseDynamicDates;
4771 $this->mInterwikiMagic
= $wgInterwikiMagic;
4772 $this->mAllowExternalImages
= $wgAllowExternalImages;
4773 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4774 $this->mSkin
= null; # Deferred
4775 $this->mDateFormat
= null; # Deferred
4776 $this->mEditSection
= true;
4777 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4778 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4779 $this->mTidy
= false;
4780 $this->mInterfaceMessage
= false;
4781 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4782 $this->mRemoveComments
= true;
4783 wfProfileOut( $fname );
4788 * Callback function used by Parser::replaceLinkHolders()
4789 * to substitute link placeholders.
4791 function &wfOutputReplaceMatches( $matches ) {
4792 global $wgOutputReplace;
4793 return $wgOutputReplace[$matches[1]];
4797 * Return the total number of articles
4799 function wfNumberOfArticles() {
4800 global $wgNumberOfArticles;
4803 return $wgNumberOfArticles;
4807 * Return the number of files
4809 function wfNumberOfFiles() {
4810 $fname = 'wfNumberOfFiles';
4812 wfProfileIn( $fname );
4813 $dbr =& wfGetDB( DB_SLAVE
);
4814 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4815 wfProfileOut( $fname );
4821 * Return the number of user accounts
4824 function wfNumberOfUsers() {
4825 wfProfileIn( 'wfNumberOfUsers' );
4826 $dbr =& wfGetDB( DB_SLAVE
);
4827 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4828 wfProfileOut( 'wfNumberOfUsers' );
4833 * Return the total number of pages
4836 function wfNumberOfPages() {
4837 wfProfileIn( 'wfNumberOfPages' );
4838 $dbr =& wfGetDB( DB_SLAVE
);
4839 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4840 wfProfileOut( 'wfNumberOfPages' );
4845 * Return the total number of admins
4849 function wfNumberOfAdmins() {
4850 static $admins = -1;
4851 wfProfileIn( 'wfNumberOfAdmins' );
4852 if( $admins == -1 ) {
4853 $dbr =& wfGetDB( DB_SLAVE
);
4854 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4856 wfProfileOut( 'wfNumberOfAdmins' );
4857 return (int)$admins;
4861 * Count the number of pages in a particular namespace
4863 * @param $ns Namespace
4866 function wfPagesInNs( $ns ) {
4867 static $pageCount = array();
4868 wfProfileIn( 'wfPagesInNs' );
4869 if( !isset( $pageCount[$ns] ) ) {
4870 $dbr =& wfGetDB( DB_SLAVE
);
4871 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4873 wfProfileOut( 'wfPagesInNs' );
4874 return (int)$pageCount[$ns];
4878 * Get various statistics from the database
4881 function wfLoadSiteStats() {
4882 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4883 $fname = 'wfLoadSiteStats';
4885 if ( -1 != $wgNumberOfArticles ) return;
4886 $dbr =& wfGetDB( DB_SLAVE
);
4887 $s = $dbr->selectRow( 'site_stats',
4888 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4889 array( 'ss_row_id' => 1 ), $fname
4892 if ( $s === false ) {
4895 $wgTotalViews = $s->ss_total_views
;
4896 $wgTotalEdits = $s->ss_total_edits
;
4897 $wgNumberOfArticles = $s->ss_good_articles
;
4902 * Get revision timestamp from the database considering timecorrection
4904 * @param $id Int: page revision id
4907 function wfRevisionTimestamp( $id ) {
4909 $fname = 'wfRevisionTimestamp';
4911 wfProfileIn( $fname );
4912 $dbr =& wfGetDB( DB_SLAVE
);
4913 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4914 array( 'rev_id' => $id ), __METHOD__
);
4915 $timestamp = $wgContLang->userAdjust( $timestamp );
4916 wfProfileOut( $fname );
4923 * Basically replacing " > and < with HTML entities ( ", >, <)
4925 * @param $in String: text that might contain HTML tags.
4926 * @return string Escaped string
4928 function wfEscapeHTMLTagsOnly( $in ) {
4930 array( '"', '>', '<' ),
4931 array( '"', '>', '<' ),