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 $la = Linker
::getExternalLinkAttributes( $url, "$keyword $id" );
1042 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1048 * Parse headers and return html
1052 function doHeadings( $text ) {
1053 $fname = 'Parser::doHeadings';
1054 wfProfileIn( $fname );
1055 for ( $i = 6; $i >= 1; --$i ) {
1056 $h = str_repeat( '=', $i );
1057 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1058 "<h{$i}>\\1</h{$i}>\\2", $text );
1060 wfProfileOut( $fname );
1065 * Replace single quotes with HTML markup
1067 * @return string the altered text
1069 function doAllQuotes( $text ) {
1070 $fname = 'Parser::doAllQuotes';
1071 wfProfileIn( $fname );
1073 $lines = explode( "\n", $text );
1074 foreach ( $lines as $line ) {
1075 $outtext .= $this->doQuotes ( $line ) . "\n";
1077 $outtext = substr($outtext, 0,-1);
1078 wfProfileOut( $fname );
1083 * Helper function for doAllQuotes()
1086 function doQuotes( $text ) {
1087 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1088 if ( count( $arr ) == 1 )
1092 # First, do some preliminary work. This may shift some apostrophes from
1093 # being mark-up to being text. It also counts the number of occurrences
1094 # of bold and italics mark-ups.
1098 foreach ( $arr as $r )
1100 if ( ( $i %
2 ) == 1 )
1102 # If there are ever four apostrophes, assume the first is supposed to
1103 # be text, and the remaining three constitute mark-up for bold text.
1104 if ( strlen( $arr[$i] ) == 4 )
1109 # If there are more than 5 apostrophes in a row, assume they're all
1110 # text except for the last 5.
1111 else if ( strlen( $arr[$i] ) > 5 )
1113 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1116 # Count the number of occurrences of bold and italics mark-ups.
1117 # We are not counting sequences of five apostrophes.
1118 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1119 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1120 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1125 # If there is an odd number of both bold and italics, it is likely
1126 # that one of the bold ones was meant to be an apostrophe followed
1127 # by italics. Which one we cannot know for certain, but it is more
1128 # likely to be one that has a single-letter word before it.
1129 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1132 $firstsingleletterword = -1;
1133 $firstmultiletterword = -1;
1135 foreach ( $arr as $r )
1137 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1139 $x1 = substr ($arr[$i-1], -1);
1140 $x2 = substr ($arr[$i-1], -2, 1);
1142 if ($firstspace == -1) $firstspace = $i;
1143 } else if ($x2 == ' ') {
1144 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1146 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1152 # If there is a single-letter word, use it!
1153 if ($firstsingleletterword > -1)
1155 $arr [ $firstsingleletterword ] = "''";
1156 $arr [ $firstsingleletterword-1 ] .= "'";
1158 # If not, but there's a multi-letter word, use that one.
1159 else if ($firstmultiletterword > -1)
1161 $arr [ $firstmultiletterword ] = "''";
1162 $arr [ $firstmultiletterword-1 ] .= "'";
1164 # ... otherwise use the first one that has neither.
1165 # (notice that it is possible for all three to be -1 if, for example,
1166 # there is only one pentuple-apostrophe in the line)
1167 else if ($firstspace > -1)
1169 $arr [ $firstspace ] = "''";
1170 $arr [ $firstspace-1 ] .= "'";
1174 # Now let's actually convert our apostrophic mush to HTML!
1179 foreach ($arr as $r)
1183 if ($state == 'both')
1190 if (strlen ($r) == 2)
1193 { $output .= '</i>'; $state = ''; }
1194 else if ($state == 'bi')
1195 { $output .= '</i>'; $state = 'b'; }
1196 else if ($state == 'ib')
1197 { $output .= '</b></i><b>'; $state = 'b'; }
1198 else if ($state == 'both')
1199 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1200 else # $state can be 'b' or ''
1201 { $output .= '<i>'; $state .= 'i'; }
1203 else if (strlen ($r) == 3)
1206 { $output .= '</b>'; $state = ''; }
1207 else if ($state == 'bi')
1208 { $output .= '</i></b><i>'; $state = 'i'; }
1209 else if ($state == 'ib')
1210 { $output .= '</b>'; $state = 'i'; }
1211 else if ($state == 'both')
1212 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1213 else # $state can be 'i' or ''
1214 { $output .= '<b>'; $state .= 'b'; }
1216 else if (strlen ($r) == 5)
1219 { $output .= '</b><i>'; $state = 'i'; }
1220 else if ($state == 'i')
1221 { $output .= '</i><b>'; $state = 'b'; }
1222 else if ($state == 'bi')
1223 { $output .= '</i></b>'; $state = ''; }
1224 else if ($state == 'ib')
1225 { $output .= '</b></i>'; $state = ''; }
1226 else if ($state == 'both')
1227 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1228 else # ($state == '')
1229 { $buffer = ''; $state = 'both'; }
1234 # Now close all remaining tags. Notice that the order is important.
1235 if ($state == 'b' ||
$state == 'ib')
1237 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1241 if ($state == 'both')
1242 $output .= '<b><i>'.$buffer.'</i></b>';
1248 * Replace external links
1250 * Note: this is all very hackish and the order of execution matters a lot.
1251 * Make sure to run maintenance/parserTests.php if you change this code.
1255 function replaceExternalLinks( $text ) {
1257 $fname = 'Parser::replaceExternalLinks';
1258 wfProfileIn( $fname );
1260 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1262 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1265 while ( $i<count( $bits ) ) {
1267 $protocol = $bits[$i++
];
1268 $text = $bits[$i++
];
1269 $trail = $bits[$i++
];
1271 # The characters '<' and '>' (which were escaped by
1272 # removeHTMLtags()) should not be included in
1273 # URLs, per RFC 2396.
1275 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1276 $text = substr($url, $m2[0][1]) . ' ' . $text;
1277 $url = substr($url, 0, $m2[0][1]);
1280 # If the link text is an image URL, replace it with an <img> tag
1281 # This happened by accident in the original parser, but some people used it extensively
1282 $img = $this->maybeMakeExternalImage( $text );
1283 if ( $img !== false ) {
1289 # Set linktype for CSS - if URL==text, link is essentially free
1290 $linktype = ($text == $url) ?
'free' : 'text';
1292 # No link text, e.g. [http://domain.tld/some.link]
1293 if ( $text == '' ) {
1294 # Autonumber if allowed. See bug #5918
1295 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1296 $text = '[' . ++
$this->mAutonumber
. ']';
1297 $linktype = 'autonumber';
1299 # Otherwise just use the URL
1300 $text = htmlspecialchars( $url );
1304 # Have link text, e.g. [http://domain.tld/some.link text]s
1306 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1309 $text = $wgContLang->markNoConversion($text);
1311 $url = Sanitizer
::cleanUrl( $url );
1313 # Process the trail (i.e. everything after this link up until start of the next link),
1314 # replacing any non-bracketed links
1315 $trail = $this->replaceFreeExternalLinks( $trail );
1317 # Use the encoded URL
1318 # This means that users can paste URLs directly into the text
1319 # Funny characters like ö aren't valid in URLs anyway
1320 # This was changed in August 2004
1321 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1323 # Register link in the output object.
1324 # Replace unnecessary URL escape codes with the referenced character
1325 # This prevents spammers from hiding links from the filters
1326 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1327 $this->mOutput
->addExternalLink( $pasteurized );
1330 wfProfileOut( $fname );
1335 * Replace anything that looks like a URL with a link
1338 function replaceFreeExternalLinks( $text ) {
1340 $fname = 'Parser::replaceFreeExternalLinks';
1341 wfProfileIn( $fname );
1343 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1344 $s = array_shift( $bits );
1347 while ( $i < count( $bits ) ){
1348 $protocol = $bits[$i++
];
1349 $remainder = $bits[$i++
];
1352 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1353 # Found some characters after the protocol that look promising
1354 $url = $protocol . $m[1];
1357 # special case: handle urls as url args:
1358 # http://www.example.com/foo?=http://www.example.com/bar
1359 if(strlen($trail) == 0 &&
1361 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1362 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1365 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1370 # The characters '<' and '>' (which were escaped by
1371 # removeHTMLtags()) should not be included in
1372 # URLs, per RFC 2396.
1374 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1375 $trail = substr($url, $m2[0][1]) . $trail;
1376 $url = substr($url, 0, $m2[0][1]);
1379 # Move trailing punctuation to $trail
1381 # If there is no left bracket, then consider right brackets fair game too
1382 if ( strpos( $url, '(' ) === false ) {
1386 $numSepChars = strspn( strrev( $url ), $sep );
1387 if ( $numSepChars ) {
1388 $trail = substr( $url, -$numSepChars ) . $trail;
1389 $url = substr( $url, 0, -$numSepChars );
1392 $url = Sanitizer
::cleanUrl( $url );
1394 # Is this an external image?
1395 $text = $this->maybeMakeExternalImage( $url );
1396 if ( $text === false ) {
1397 # Not an image, make a link
1398 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1399 # Register it in the output object...
1400 # Replace unnecessary URL escape codes with their equivalent characters
1401 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1402 $this->mOutput
->addExternalLink( $pasteurized );
1404 $s .= $text . $trail;
1406 $s .= $protocol . $remainder;
1409 wfProfileOut( $fname );
1414 * Replace unusual URL escape codes with their equivalent characters
1418 * @fixme This can merge genuinely required bits in the path or query string,
1419 * breaking legit URLs. A proper fix would treat the various parts of
1420 * the URL differently; as a workaround, just use the output for
1421 * statistical records, not for actual linking/output.
1423 static function replaceUnusualEscapes( $url ) {
1424 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1425 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1429 * Callback function used in replaceUnusualEscapes().
1430 * Replaces unusual URL escape codes with their equivalent character
1434 private static function replaceUnusualEscapesCallback( $matches ) {
1435 $char = urldecode( $matches[0] );
1436 $ord = ord( $char );
1437 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1438 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1439 // No, shouldn't be escaped
1442 // Yes, leave it escaped
1448 * make an image if it's allowed, either through the global
1449 * option or through the exception
1452 function maybeMakeExternalImage( $url ) {
1453 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1454 $imagesexception = !empty($imagesfrom);
1456 if ( $this->mOptions
->getAllowExternalImages()
1457 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1458 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1460 $text = Linker
::makeExternalImage( htmlspecialchars( $url ) );
1467 * Process [[ ]] wikilinks
1471 function replaceInternalLinks( $s ) {
1473 static $fname = 'Parser::replaceInternalLinks' ;
1475 wfProfileIn( $fname );
1477 wfProfileIn( $fname.'-setup' );
1479 # the % is needed to support urlencoded titles as well
1480 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1482 #split the entire text string on occurences of [[
1483 $a = explode( '[[', ' ' . $s );
1484 #get the first element (all text up to first [[), and remove the space we added
1485 $s = array_shift( $a );
1486 $s = substr( $s, 1 );
1488 # Match a link having the form [[namespace:link|alternate]]trail
1490 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1491 # Match cases where there is no "]]", which might still be images
1492 static $e1_img = FALSE;
1493 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1494 # Match the end of a line for a word that's not followed by whitespace,
1495 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1496 $e2 = wfMsgForContent( 'linkprefix' );
1498 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1500 if( is_null( $this->mTitle
) ) {
1501 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1503 $nottalk = !$this->mTitle
->isTalkPage();
1505 if ( $useLinkPrefixExtension ) {
1507 if ( preg_match( $e2, $s, $m ) ) {
1508 $first_prefix = $m[2];
1510 $first_prefix = false;
1516 $selflink = $this->mTitle
->getPrefixedText();
1517 $useSubpages = $this->areSubpagesAllowed();
1518 wfProfileOut( $fname.'-setup' );
1520 # Loop for each link
1521 for ($k = 0; isset( $a[$k] ); $k++
) {
1523 if ( $useLinkPrefixExtension ) {
1524 wfProfileIn( $fname.'-prefixhandling' );
1525 if ( preg_match( $e2, $s, $m ) ) {
1533 $prefix = $first_prefix;
1534 $first_prefix = false;
1536 wfProfileOut( $fname.'-prefixhandling' );
1539 $might_be_img = false;
1541 wfProfileIn( "$fname-e1" );
1542 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1544 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1545 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1546 # the real problem is with the $e1 regex
1549 # Still some problems for cases where the ] is meant to be outside punctuation,
1550 # and no image is in sight. See bug 2095.
1553 substr( $m[3], 0, 1 ) === ']' &&
1554 strpos($text, '[') !== false
1557 $text .= ']'; # so that replaceExternalLinks($text) works later
1558 $m[3] = substr( $m[3], 1 );
1560 # fix up urlencoded title texts
1561 if( strpos( $m[1], '%' ) !== false ) {
1562 # Should anchors '#' also be rejected?
1563 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1566 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1567 $might_be_img = true;
1569 if ( strpos( $m[1], '%' ) !== false ) {
1570 $m[1] = urldecode($m[1]);
1573 } else { # Invalid form; output directly
1574 $s .= $prefix . '[[' . $line ;
1575 wfProfileOut( "$fname-e1" );
1578 wfProfileOut( "$fname-e1" );
1579 wfProfileIn( "$fname-misc" );
1581 # Don't allow internal links to pages containing
1582 # PROTO: where PROTO is a valid URL protocol; these
1583 # should be external links.
1584 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1585 $s .= $prefix . '[[' . $line ;
1589 # Make subpage if necessary
1590 if( $useSubpages ) {
1591 $link = $this->maybeDoSubpageLink( $m[1], $text );
1596 $noforce = (substr($m[1], 0, 1) != ':');
1598 # Strip off leading ':'
1599 $link = substr($link, 1);
1602 wfProfileOut( "$fname-misc" );
1603 wfProfileIn( "$fname-title" );
1604 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1606 $s .= $prefix . '[[' . $line;
1607 wfProfileOut( "$fname-title" );
1611 $ns = $nt->getNamespace();
1612 $iw = $nt->getInterWiki();
1613 wfProfileOut( "$fname-title" );
1615 if ($might_be_img) { # if this is actually an invalid link
1616 wfProfileIn( "$fname-might_be_img" );
1617 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1619 while (isset ($a[$k+
1]) ) {
1620 #look at the next 'line' to see if we can close it there
1621 $spliced = array_splice( $a, $k +
1, 1 );
1622 $next_line = array_shift( $spliced );
1623 $m = explode( ']]', $next_line, 3 );
1624 if ( count( $m ) == 3 ) {
1625 # the first ]] closes the inner link, the second the image
1627 $text .= "[[{$m[0]}]]{$m[1]}";
1630 } elseif ( count( $m ) == 2 ) {
1631 #if there's exactly one ]] that's fine, we'll keep looking
1632 $text .= "[[{$m[0]}]]{$m[1]}";
1634 #if $next_line is invalid too, we need look no further
1635 $text .= '[[' . $next_line;
1640 # we couldn't find the end of this imageLink, so output it raw
1641 #but don't ignore what might be perfectly normal links in the text we've examined
1642 $text = $this->replaceInternalLinks($text);
1643 $s .= "{$prefix}[[$link|$text";
1644 # note: no $trail, because without an end, there *is* no trail
1645 wfProfileOut( "$fname-might_be_img" );
1648 } else { #it's not an image, so output it raw
1649 $s .= "{$prefix}[[$link|$text";
1650 # note: no $trail, because without an end, there *is* no trail
1651 wfProfileOut( "$fname-might_be_img" );
1654 wfProfileOut( "$fname-might_be_img" );
1657 $wasblank = ( '' == $text );
1658 if( $wasblank ) $text = $link;
1660 # Link not escaped by : , create the various objects
1664 wfProfileIn( "$fname-interwiki" );
1665 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1666 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1667 $s = rtrim($s . "\n");
1668 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1669 wfProfileOut( "$fname-interwiki" );
1672 wfProfileOut( "$fname-interwiki" );
1674 if ( $ns == NS_IMAGE
) {
1675 wfProfileIn( "$fname-image" );
1676 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1677 # recursively parse links inside the image caption
1678 # actually, this will parse them in any other parameters, too,
1679 # but it might be hard to fix that, and it doesn't matter ATM
1680 $text = $this->replaceExternalLinks($text);
1681 $text = $this->replaceInternalLinks($text);
1683 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1684 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1685 $this->mOutput
->addImage( $nt->getDBkey() );
1687 wfProfileOut( "$fname-image" );
1690 # We still need to record the image's presence on the page
1691 $this->mOutput
->addImage( $nt->getDBkey() );
1693 wfProfileOut( "$fname-image" );
1697 if ( $ns == NS_CATEGORY
) {
1698 wfProfileIn( "$fname-category" );
1699 $s = rtrim($s . "\n"); # bug 87
1702 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1703 $sortkey = $this->mTitle
->getText();
1705 $sortkey = $this->mTitle
->getPrefixedText();
1710 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1711 $sortkey = str_replace( "\n", '', $sortkey );
1712 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1713 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1716 * Strip the whitespace Category links produce, see bug 87
1717 * @todo We might want to use trim($tmp, "\n") here.
1719 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1721 wfProfileOut( "$fname-category" );
1726 if( ( $nt->getPrefixedText() === $selflink ) &&
1727 ( $nt->getFragment() === '' ) ) {
1728 # Self-links are handled specially; generally de-link and change to bold.
1729 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
1733 # Special and Media are pseudo-namespaces; no pages actually exist in them
1734 if( $ns == NS_MEDIA
) {
1735 $link = Linker
::makeMediaLinkObj( $nt, $text );
1736 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1737 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1738 $this->mOutput
->addImage( $nt->getDBkey() );
1740 } elseif( $ns == NS_SPECIAL
) {
1741 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1743 } elseif( $ns == NS_IMAGE
) {
1744 $img = new Image( $nt );
1745 if( $img->exists() ) {
1746 // Force a blue link if the file exists; may be a remote
1747 // upload on the shared repository, and we want to see its
1748 // auto-generated page.
1749 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1750 $this->mOutput
->addLink( $nt );
1754 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1756 wfProfileOut( $fname );
1761 * Make a link placeholder. The text returned can be later resolved to a real link with
1762 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1763 * parsing of interwiki links, and secondly to allow all existence checks and
1764 * article length checks (for stub links) to be bundled into a single query.
1767 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1768 wfProfileIn( __METHOD__
);
1769 if ( ! is_object($nt) ) {
1771 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1773 # Separate the link trail from the rest of the link
1774 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1776 if ( $nt->isExternal() ) {
1777 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1778 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1779 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1781 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1782 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1783 $this->mLinkHolders
['queries'][] = $query;
1784 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1785 $this->mLinkHolders
['titles'][] = $nt;
1787 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1790 wfProfileOut( __METHOD__
);
1795 * Render a forced-blue link inline; protect against double expansion of
1796 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1797 * Since this little disaster has to split off the trail text to avoid
1798 * breaking URLs in the following text without breaking trails on the
1799 * wiki links, it's been made into a horrible function.
1802 * @param string $text
1803 * @param string $query
1804 * @param string $trail
1805 * @param string $prefix
1806 * @return string HTML-wikitext mix oh yuck
1808 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1809 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1810 $link = Linker
::makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1811 return $this->armorLinks( $link ) . $trail;
1815 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1816 * going to go through further parsing steps before inline URL expansion.
1818 * In particular this is important when using action=render, which causes
1819 * full URLs to be included.
1821 * Oh man I hate our multi-layer parser!
1823 * @param string more-or-less HTML
1824 * @return string less-or-more HTML with NOPARSE bits
1826 function armorLinks( $text ) {
1827 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1828 "{$this->mUniqPrefix}NOPARSE$1", $text );
1832 * Return true if subpage links should be expanded on this page.
1835 function areSubpagesAllowed() {
1836 # Some namespaces don't allow subpages
1837 global $wgNamespacesWithSubpages;
1838 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1842 * Handle link to subpage if necessary
1843 * @param string $target the source of the link
1844 * @param string &$text the link text, modified as necessary
1845 * @return string the full name of the link
1848 function maybeDoSubpageLink($target, &$text) {
1851 # :Foobar -- override special treatment of prefix (images, language links)
1852 # /Foobar -- convert to CurrentPage/Foobar
1853 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1854 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1855 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1857 $fname = 'Parser::maybeDoSubpageLink';
1858 wfProfileIn( $fname );
1859 $ret = $target; # default return value is no change
1862 $target = trim( $target );
1864 # Some namespaces don't allow subpages,
1865 # so only perform processing if subpages are allowed
1866 if( $this->areSubpagesAllowed() ) {
1867 # Look at the first character
1868 if( $target != '' && $target{0} == '/' ) {
1869 # / at end means we don't want the slash to be shown
1870 if( substr( $target, -1, 1 ) == '/' ) {
1871 $target = substr( $target, 1, -1 );
1874 $noslash = substr( $target, 1 );
1877 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1878 if( '' === $text ) {
1880 } # this might be changed for ugliness reasons
1882 # check for .. subpage backlinks
1884 $nodotdot = $target;
1885 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1887 $nodotdot = substr( $nodotdot, 3 );
1889 if($dotdotcount > 0) {
1890 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1891 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1892 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1893 # / at the end means don't show full path
1894 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1895 $nodotdot = substr( $nodotdot, 0, -1 );
1896 if( '' === $text ) {
1900 $nodotdot = trim( $nodotdot );
1901 if( $nodotdot != '' ) {
1902 $ret .= '/' . $nodotdot;
1909 wfProfileOut( $fname );
1914 * Used by doBlockLevels()
1917 /* private */ function closeParagraph() {
1919 if ( '' != $this->mLastSection
) {
1920 $result = '</' . $this->mLastSection
. ">\n";
1922 $this->mInPre
= false;
1923 $this->mLastSection
= '';
1926 # getCommon() returns the length of the longest common substring
1927 # of both arguments, starting at the beginning of both.
1929 /* private */ function getCommon( $st1, $st2 ) {
1930 $fl = strlen( $st1 );
1931 $shorter = strlen( $st2 );
1932 if ( $fl < $shorter ) { $shorter = $fl; }
1934 for ( $i = 0; $i < $shorter; ++
$i ) {
1935 if ( $st1{$i} != $st2{$i} ) { break; }
1939 # These next three functions open, continue, and close the list
1940 # element appropriate to the prefix character passed into them.
1942 /* private */ function openList( $char ) {
1943 $result = $this->closeParagraph();
1945 if ( '*' == $char ) { $result .= '<ul><li>'; }
1946 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1947 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1948 else if ( ';' == $char ) {
1949 $result .= '<dl><dt>';
1950 $this->mDTopen
= true;
1952 else { $result = '<!-- ERR 1 -->'; }
1957 /* private */ function nextItem( $char ) {
1958 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1959 else if ( ':' == $char ||
';' == $char ) {
1961 if ( $this->mDTopen
) { $close = '</dt>'; }
1962 if ( ';' == $char ) {
1963 $this->mDTopen
= true;
1964 return $close . '<dt>';
1966 $this->mDTopen
= false;
1967 return $close . '<dd>';
1970 return '<!-- ERR 2 -->';
1973 /* private */ function closeList( $char ) {
1974 if ( '*' == $char ) { $text = '</li></ul>'; }
1975 else if ( '#' == $char ) { $text = '</li></ol>'; }
1976 else if ( ':' == $char ) {
1977 if ( $this->mDTopen
) {
1978 $this->mDTopen
= false;
1979 $text = '</dt></dl>';
1981 $text = '</dd></dl>';
1984 else { return '<!-- ERR 3 -->'; }
1990 * Make lists from lines starting with ':', '*', '#', etc.
1993 * @return string the lists rendered as HTML
1995 function doBlockLevels( $text, $linestart ) {
1996 $fname = 'Parser::doBlockLevels';
1997 wfProfileIn( $fname );
1999 # Parsing through the text line by line. The main thing
2000 # happening here is handling of block-level elements p, pre,
2001 # and making lists from lines starting with * # : etc.
2003 $textLines = explode( "\n", $text );
2005 $lastPrefix = $output = '';
2006 $this->mDTopen
= $inBlockElem = false;
2008 $paragraphStack = false;
2010 if ( !$linestart ) {
2011 $output .= array_shift( $textLines );
2013 foreach ( $textLines as $oLine ) {
2014 $lastPrefixLength = strlen( $lastPrefix );
2015 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2016 $preOpenMatch = preg_match('/<pre/i', $oLine );
2017 if ( !$this->mInPre
) {
2018 # Multiple prefixes may abut each other for nested lists.
2019 $prefixLength = strspn( $oLine, '*#:;' );
2020 $pref = substr( $oLine, 0, $prefixLength );
2023 $pref2 = str_replace( ';', ':', $pref );
2024 $t = substr( $oLine, $prefixLength );
2025 $this->mInPre
= !empty($preOpenMatch);
2027 # Don't interpret any other prefixes in preformatted text
2029 $pref = $pref2 = '';
2034 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2035 # Same as the last item, so no need to deal with nesting or opening stuff
2036 $output .= $this->nextItem( substr( $pref, -1 ) );
2037 $paragraphStack = false;
2039 if ( substr( $pref, -1 ) == ';') {
2040 # The one nasty exception: definition lists work like this:
2041 # ; title : definition text
2042 # So we check for : in the remainder text to split up the
2043 # title and definition, without b0rking links.
2045 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2047 $output .= $term . $this->nextItem( ':' );
2050 } elseif( $prefixLength ||
$lastPrefixLength ) {
2051 # Either open or close a level...
2052 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2053 $paragraphStack = false;
2055 while( $commonPrefixLength < $lastPrefixLength ) {
2056 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2057 --$lastPrefixLength;
2059 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2060 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2062 while ( $prefixLength > $commonPrefixLength ) {
2063 $char = substr( $pref, $commonPrefixLength, 1 );
2064 $output .= $this->openList( $char );
2066 if ( ';' == $char ) {
2067 # FIXME: This is dupe of code above
2068 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2070 $output .= $term . $this->nextItem( ':' );
2073 ++
$commonPrefixLength;
2075 $lastPrefix = $pref2;
2077 if( 0 == $prefixLength ) {
2078 wfProfileIn( "$fname-paragraph" );
2079 # No prefix (not in list)--go to paragraph mode
2080 // XXX: use a stack for nestable elements like span, table and div
2081 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2082 $closematch = preg_match(
2083 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2084 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2085 if ( $openmatch or $closematch ) {
2086 $paragraphStack = false;
2087 #Â TODO bug 5718: paragraph closed
2088 $output .= $this->closeParagraph();
2089 if ( $preOpenMatch and !$preCloseMatch ) {
2090 $this->mInPre
= true;
2092 if ( $closematch ) {
2093 $inBlockElem = false;
2095 $inBlockElem = true;
2097 } else if ( !$inBlockElem && !$this->mInPre
) {
2098 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2100 if ($this->mLastSection
!= 'pre') {
2101 $paragraphStack = false;
2102 $output .= $this->closeParagraph().'<pre>';
2103 $this->mLastSection
= 'pre';
2105 $t = substr( $t, 1 );
2108 if ( '' == trim($t) ) {
2109 if ( $paragraphStack ) {
2110 $output .= $paragraphStack.'<br />';
2111 $paragraphStack = false;
2112 $this->mLastSection
= 'p';
2114 if ($this->mLastSection
!= 'p' ) {
2115 $output .= $this->closeParagraph();
2116 $this->mLastSection
= '';
2117 $paragraphStack = '<p>';
2119 $paragraphStack = '</p><p>';
2123 if ( $paragraphStack ) {
2124 $output .= $paragraphStack;
2125 $paragraphStack = false;
2126 $this->mLastSection
= 'p';
2127 } else if ($this->mLastSection
!= 'p') {
2128 $output .= $this->closeParagraph().'<p>';
2129 $this->mLastSection
= 'p';
2134 wfProfileOut( "$fname-paragraph" );
2136 // somewhere above we forget to get out of pre block (bug 785)
2137 if($preCloseMatch && $this->mInPre
) {
2138 $this->mInPre
= false;
2140 if ($paragraphStack === false) {
2144 while ( $prefixLength ) {
2145 $output .= $this->closeList( $pref2{$prefixLength-1} );
2148 if ( '' != $this->mLastSection
) {
2149 $output .= '</' . $this->mLastSection
. '>';
2150 $this->mLastSection
= '';
2153 wfProfileOut( $fname );
2158 * Split up a string on ':', ignoring any occurences inside tags
2159 * to prevent illegal overlapping.
2160 * @param string $str the string to split
2161 * @param string &$before set to everything before the ':'
2162 * @param string &$after set to everything after the ':'
2163 * return string the position of the ':', or false if none found
2165 function findColonNoLinks($str, &$before, &$after) {
2166 $fname = 'Parser::findColonNoLinks';
2167 wfProfileIn( $fname );
2169 $pos = strpos( $str, ':' );
2170 if( $pos === false ) {
2172 wfProfileOut( $fname );
2176 $lt = strpos( $str, '<' );
2177 if( $lt === false ||
$lt > $pos ) {
2178 // Easy; no tag nesting to worry about
2179 $before = substr( $str, 0, $pos );
2180 $after = substr( $str, $pos+
1 );
2181 wfProfileOut( $fname );
2185 // Ugly state machine to walk through avoiding tags.
2186 $state = MW_COLON_STATE_TEXT
;
2188 $len = strlen( $str );
2189 for( $i = 0; $i < $len; $i++
) {
2193 // (Using the number is a performance hack for common cases)
2194 case 0: // MW_COLON_STATE_TEXT:
2197 // Could be either a <start> tag or an </end> tag
2198 $state = MW_COLON_STATE_TAGSTART
;
2203 $before = substr( $str, 0, $i );
2204 $after = substr( $str, $i +
1 );
2205 wfProfileOut( $fname );
2208 // Embedded in a tag; don't break it.
2211 // Skip ahead looking for something interesting
2212 $colon = strpos( $str, ':', $i );
2213 if( $colon === false ) {
2214 // Nothing else interesting
2215 wfProfileOut( $fname );
2218 $lt = strpos( $str, '<', $i );
2219 if( $stack === 0 ) {
2220 if( $lt === false ||
$colon < $lt ) {
2222 $before = substr( $str, 0, $colon );
2223 $after = substr( $str, $colon +
1 );
2224 wfProfileOut( $fname );
2228 if( $lt === false ) {
2229 // Nothing else interesting to find; abort!
2230 // We're nested, but there's no close tags left. Abort!
2233 // Skip ahead to next tag start
2235 $state = MW_COLON_STATE_TAGSTART
;
2238 case 1: // MW_COLON_STATE_TAG:
2243 $state = MW_COLON_STATE_TEXT
;
2246 // Slash may be followed by >?
2247 $state = MW_COLON_STATE_TAGSLASH
;
2253 case 2: // MW_COLON_STATE_TAGSTART:
2256 $state = MW_COLON_STATE_CLOSETAG
;
2259 $state = MW_COLON_STATE_COMMENT
;
2262 // Illegal early close? This shouldn't happen D:
2263 $state = MW_COLON_STATE_TEXT
;
2266 $state = MW_COLON_STATE_TAG
;
2269 case 3: // MW_COLON_STATE_CLOSETAG:
2274 wfDebug( "Invalid input in $fname; too many close tags\n" );
2275 wfProfileOut( $fname );
2278 $state = MW_COLON_STATE_TEXT
;
2281 case MW_COLON_STATE_TAGSLASH
:
2283 // Yes, a self-closed tag <blah/>
2284 $state = MW_COLON_STATE_TEXT
;
2286 // Probably we're jumping the gun, and this is an attribute
2287 $state = MW_COLON_STATE_TAG
;
2290 case 5: // MW_COLON_STATE_COMMENT:
2292 $state = MW_COLON_STATE_COMMENTDASH
;
2295 case MW_COLON_STATE_COMMENTDASH
:
2297 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2299 $state = MW_COLON_STATE_COMMENT
;
2302 case MW_COLON_STATE_COMMENTDASHDASH
:
2304 $state = MW_COLON_STATE_TEXT
;
2306 $state = MW_COLON_STATE_COMMENT
;
2310 throw new MWException( "State machine error in $fname" );
2314 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2317 wfProfileOut( $fname );
2322 * Return value of a magic variable (like PAGENAME)
2326 function getVariableValue( $index ) {
2327 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2330 * Some of these require message or data lookups and can be
2331 * expensive to check many times.
2333 static $varCache = array();
2334 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2335 if ( isset( $varCache[$index] ) ) {
2336 return $varCache[$index];
2341 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2344 global $wgLocaltimezone;
2345 if ( isset( $wgLocaltimezone ) ) {
2346 $oldtz = getenv( 'TZ' );
2347 putenv( 'TZ='.$wgLocaltimezone );
2349 $localTimestamp = date( 'YmdHis', $ts );
2350 $localMonth = date( 'm', $ts );
2351 $localMonthName = date( 'n', $ts );
2352 $localDay = date( 'j', $ts );
2353 $localDay2 = date( 'd', $ts );
2354 $localDayOfWeek = date( 'w', $ts );
2355 $localWeek = date( 'W', $ts );
2356 $localYear = date( 'Y', $ts );
2357 $localHour = date( 'H', $ts );
2358 if ( isset( $wgLocaltimezone ) ) {
2359 putenv( 'TZ='.$oldtz );
2363 case 'currentmonth':
2364 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2365 case 'currentmonthname':
2366 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2367 case 'currentmonthnamegen':
2368 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2369 case 'currentmonthabbrev':
2370 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2372 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2374 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2376 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2377 case 'localmonthname':
2378 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2379 case 'localmonthnamegen':
2380 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2381 case 'localmonthabbrev':
2382 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2384 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2386 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2388 return $this->mTitle
->getText();
2390 return $this->mTitle
->getPartialURL();
2391 case 'fullpagename':
2392 return $this->mTitle
->getPrefixedText();
2393 case 'fullpagenamee':
2394 return $this->mTitle
->getPrefixedURL();
2396 return $this->mTitle
->getSubpageText();
2397 case 'subpagenamee':
2398 return $this->mTitle
->getSubpageUrlForm();
2399 case 'basepagename':
2400 return $this->mTitle
->getBaseText();
2401 case 'basepagenamee':
2402 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2403 case 'talkpagename':
2404 if( $this->mTitle
->canTalk() ) {
2405 $talkPage = $this->mTitle
->getTalkPage();
2406 return $talkPage->getPrefixedText();
2410 case 'talkpagenamee':
2411 if( $this->mTitle
->canTalk() ) {
2412 $talkPage = $this->mTitle
->getTalkPage();
2413 return $talkPage->getPrefixedUrl();
2417 case 'subjectpagename':
2418 $subjPage = $this->mTitle
->getSubjectPage();
2419 return $subjPage->getPrefixedText();
2420 case 'subjectpagenamee':
2421 $subjPage = $this->mTitle
->getSubjectPage();
2422 return $subjPage->getPrefixedUrl();
2424 return $this->mRevisionId
;
2426 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 ) );
2427 case 'revisionday2':
2428 return substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 );
2429 case 'revisionmonth':
2430 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 4, 2 ) );
2431 case 'revisionyear':
2432 return substr( wfRevisionTimestamp( $this->mRevisionId
), 0, 4 );
2433 case 'revisiontimestamp':
2434 return wfRevisionTimestamp( $this->mRevisionId
);
2436 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2438 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2440 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2442 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2443 case 'subjectspace':
2444 return $this->mTitle
->getSubjectNsText();
2445 case 'subjectspacee':
2446 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2447 case 'currentdayname':
2448 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2450 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2452 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2454 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2456 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2457 // int to remove the padding
2458 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2460 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2461 case 'localdayname':
2462 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2464 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2466 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2468 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2470 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2471 // int to remove the padding
2472 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2474 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2475 case 'numberofarticles':
2476 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2477 case 'numberoffiles':
2478 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2479 case 'numberofusers':
2480 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2481 case 'numberofpages':
2482 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2483 case 'numberofadmins':
2484 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2485 case 'currenttimestamp':
2486 return $varCache[$index] = wfTimestampNow();
2487 case 'localtimestamp':
2488 return $varCache[$index] = $localTimestamp;
2489 case 'currentversion':
2490 return $varCache[$index] = SpecialVersion
::getVersion();
2496 return $wgServerName;
2498 return $wgScriptPath;
2499 case 'directionmark':
2500 return $wgContLang->getDirMark();
2501 case 'contentlanguage':
2502 global $wgContLanguageCode;
2503 return $wgContLanguageCode;
2506 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2514 * initialise the magic variables (like CURRENTMONTHNAME)
2518 function initialiseVariables() {
2519 $fname = 'Parser::initialiseVariables';
2520 wfProfileIn( $fname );
2521 $variableIDs = MagicWord
::getVariableIDs();
2523 $this->mVariables
= array();
2524 foreach ( $variableIDs as $id ) {
2525 $mw =& MagicWord
::get( $id );
2526 $mw->addToArray( $this->mVariables
, $id );
2528 wfProfileOut( $fname );
2532 * parse any parentheses in format ((title|part|part))
2533 * and call callbacks to get a replacement text for any found piece
2535 * @param string $text The text to parse
2536 * @param array $callbacks rules in form:
2537 * '{' => array( # opening parentheses
2538 * 'end' => '}', # closing parentheses
2539 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2540 * 3 => callback # replacement callback to call if {{{..}}} is found
2543 * 'min' => 2, # Minimum parenthesis count in cb
2544 * 'max' => 3, # Maximum parenthesis count in cb
2547 function replace_callback ($text, $callbacks) {
2548 wfProfileIn( __METHOD__
);
2549 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2550 $lastOpeningBrace = -1; # last not closed parentheses
2552 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2555 while ( $i < strlen( $text ) ) {
2556 # Find next opening brace, closing brace or pipe
2557 if ( $lastOpeningBrace == -1 ) {
2558 $currentClosing = '';
2559 $search = $validOpeningBraces;
2561 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2562 $search = $validOpeningBraces . '|' . $currentClosing;
2565 $i +
= strcspn( $text, $search, $i );
2566 if ( $i < strlen( $text ) ) {
2567 if ( $text[$i] == '|' ) {
2569 } elseif ( $text[$i] == $currentClosing ) {
2571 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2573 $rule = $callbacks[$text[$i]];
2575 # Some versions of PHP have a strcspn which stops on null characters
2576 # Ignore and continue
2585 if ( $found == 'open' ) {
2586 # found opening brace, let's add it to parentheses stack
2587 $piece = array('brace' => $text[$i],
2588 'braceEnd' => $rule['end'],
2592 # count opening brace characters
2593 $piece['count'] = strspn( $text, $piece['brace'], $i );
2594 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2595 $i +
= $piece['count'];
2597 # we need to add to stack only if opening brace count is enough for one of the rules
2598 if ( $piece['count'] >= $rule['min'] ) {
2599 $lastOpeningBrace ++
;
2600 $openingBraceStack[$lastOpeningBrace] = $piece;
2602 } elseif ( $found == 'close' ) {
2603 # lets check if it is enough characters for closing brace
2604 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2605 $count = strspn( $text, $text[$i], $i, $maxCount );
2607 # check for maximum matching characters (if there are 5 closing
2608 # characters, we will probably need only 3 - depending on the rules)
2610 $matchingCallback = null;
2611 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2612 if ( $count > $cbType['max'] ) {
2613 # The specified maximum exists in the callback array, unless the caller
2615 $matchingCount = $cbType['max'];
2617 # Count is less than the maximum
2618 # Skip any gaps in the callback array to find the true largest match
2619 # Need to use array_key_exists not isset because the callback can be null
2620 $matchingCount = $count;
2621 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2626 if ($matchingCount <= 0) {
2630 $matchingCallback = $cbType['cb'][$matchingCount];
2632 # let's set a title or last part (if '|' was found)
2633 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2634 $openingBraceStack[$lastOpeningBrace]['title'] =
2635 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2636 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2638 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2639 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2640 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2643 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2644 $pieceEnd = $i +
$matchingCount;
2646 if( is_callable( $matchingCallback ) ) {
2648 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2649 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2650 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2651 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2653 # finally we can call a user callback and replace piece of text
2654 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2655 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2656 $i = $pieceStart +
strlen($replaceWith);
2658 # null value for callback means that parentheses should be parsed, but not replaced
2659 $i +
= $matchingCount;
2662 # reset last opening parentheses, but keep it in case there are unused characters
2663 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2664 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2665 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2668 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2669 $openingBraceStack[$lastOpeningBrace--] = null;
2671 if ($matchingCount < $piece['count']) {
2672 $piece['count'] -= $matchingCount;
2673 $piece['startAt'] -= $matchingCount;
2674 $piece['partStart'] = $piece['startAt'];
2675 # do we still qualify for any callback with remaining count?
2676 $currentCbList = $callbacks[$piece['brace']]['cb'];
2677 while ( $piece['count'] ) {
2678 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2679 $lastOpeningBrace++
;
2680 $openingBraceStack[$lastOpeningBrace] = $piece;
2686 } elseif ( $found == 'pipe' ) {
2687 # lets set a title if it is a first separator, or next part otherwise
2688 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2689 $openingBraceStack[$lastOpeningBrace]['title'] =
2690 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2691 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2692 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2694 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2695 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2696 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2698 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2702 wfProfileOut( __METHOD__
);
2707 * Replace magic variables, templates, and template arguments
2708 * with the appropriate text. Templates are substituted recursively,
2709 * taking care to avoid infinite loops.
2711 * Note that the substitution depends on value of $mOutputType:
2712 * OT_WIKI: only {{subst:}} templates
2713 * OT_MSG: only magic variables
2714 * OT_HTML: all templates and magic variables
2716 * @param string $tex The text to transform
2717 * @param array $args Key-value pairs representing template parameters to substitute
2718 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2721 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2722 # Prevent too big inclusions
2723 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2727 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2728 wfProfileIn( $fname );
2730 # This function is called recursively. To keep track of arguments we need a stack:
2731 array_push( $this->mArgStack
, $args );
2733 $braceCallbacks = array();
2735 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2737 if ( $this->mOutputType
!= OT_MSG
) {
2738 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2740 if ( $braceCallbacks ) {
2744 'cb' => $braceCallbacks,
2745 'min' => $argsOnly ?
3 : 2,
2746 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2750 'cb' => array(2=>null),
2755 $text = $this->replace_callback ($text, $callbacks);
2757 array_pop( $this->mArgStack
);
2759 wfProfileOut( $fname );
2764 * Replace magic variables
2767 function variableSubstitution( $matches ) {
2769 $fname = 'Parser::variableSubstitution';
2770 $varname = $wgContLang->lc($matches[1]);
2771 wfProfileIn( $fname );
2773 if ( $this->mOutputType
== OT_WIKI
) {
2774 # Do only magic variables prefixed by SUBST
2775 $mwSubst =& MagicWord
::get( 'subst' );
2776 if (!$mwSubst->matchStartAndRemove( $varname ))
2778 # Note that if we don't substitute the variable below,
2779 # we don't remove the {{subst:}} magic word, in case
2780 # it is a template rather than a magic variable.
2782 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2783 $id = $this->mVariables
[$varname];
2784 # Now check if we did really match, case sensitive or not
2785 $mw =& MagicWord
::get( $id );
2786 if ($mw->match($matches[1])) {
2787 $text = $this->getVariableValue( $id );
2788 $this->mOutput
->mContainsOldMagic
= true;
2790 $text = $matches[0];
2793 $text = $matches[0];
2795 wfProfileOut( $fname );
2800 * Return the text of a template, after recursively
2801 * replacing any variables or templates within the template.
2803 * @param array $piece The parts of the template
2804 * $piece['text']: matched text
2805 * $piece['title']: the title, i.e. the part before the |
2806 * $piece['parts']: the parameter array
2807 * @return string the text of the template
2810 function braceSubstitution( $piece ) {
2811 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2812 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2813 wfProfileIn( $fname );
2814 wfProfileIn( __METHOD__
.'-setup' );
2817 $found = false; # $text has been filled
2818 $nowiki = false; # wiki markup in $text should be escaped
2819 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2820 $noargs = false; # Don't replace triple-brace arguments in $text
2821 $replaceHeadings = false; # Make the edit section links go to the template not the article
2822 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2823 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2825 # Title object, where $text came from
2831 # $part1 is the bit before the first |, and must contain only title characters
2832 # $args is a list of arguments, starting from index 0, not including $part1
2834 $titleText = $part1 = $piece['title'];
2835 # If the third subpattern matched anything, it will start with |
2837 if (null == $piece['parts']) {
2838 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2839 if ($replaceWith != $piece['text']) {
2840 $text = $replaceWith;
2847 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2848 wfProfileOut( __METHOD__
.'-setup' );
2851 wfProfileIn( __METHOD__
.'-modifiers' );
2853 $mwSubst =& MagicWord
::get( 'subst' );
2854 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2855 # One of two possibilities is true:
2856 # 1) Found SUBST but not in the PST phase
2857 # 2) Didn't find SUBST and in the PST phase
2858 # In either case, return without further processing
2859 $text = $piece['text'];
2866 # MSG, MSGNW and RAW
2869 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2870 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2873 # Remove obsolete MSG:
2874 $mwMsg =& MagicWord
::get( 'msg' );
2875 $mwMsg->matchStartAndRemove( $part1 );
2879 $mwRaw =& MagicWord
::get( 'raw' );
2880 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2881 $forceRawInterwiki = true;
2884 wfProfileOut( __METHOD__
.'-modifiers' );
2888 wfProfileIn( __METHOD__
. '-pfunc' );
2890 $colonPos = strpos( $part1, ':' );
2891 if ( $colonPos !== false ) {
2892 # Case sensitive functions
2893 $function = substr( $part1, 0, $colonPos );
2894 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2895 $function = $this->mFunctionSynonyms
[1][$function];
2897 # Case insensitive functions
2898 $function = strtolower( $function );
2899 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2900 $function = $this->mFunctionSynonyms
[0][$function];
2906 $funcArgs = array_map( 'trim', $args );
2907 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2908 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2911 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2915 if ( is_array( $result ) ) {
2916 if ( isset( $result[0] ) ) {
2917 $text = $linestart . $result[0];
2918 unset( $result[0] );
2921 // Extract flags into the local scope
2922 // This allows callers to set flags such as nowiki, noparse, found, etc.
2925 $text = $linestart . $result;
2929 wfProfileOut( __METHOD__
. '-pfunc' );
2932 # Template table test
2934 # Did we encounter this template already? If yes, it is in the cache
2935 # and we need to check for loops.
2936 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2939 # Infinite loop test
2940 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2944 $text = $linestart .
2945 "[[$part1]]<!-- WARNING: template loop detected -->";
2946 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2948 # set $text to cached message.
2949 $text = $linestart . $this->mTemplates
[$piece['title']];
2953 # Load from database
2954 $lastPathLevel = $this->mTemplatePath
;
2956 wfProfileIn( __METHOD__
. '-loadtpl' );
2958 # declaring $subpage directly in the function call
2959 # does not work correctly with references and breaks
2960 # {{/subpage}}-style inclusions
2962 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2963 if ($subpage !== '') {
2964 $ns = $this->mTitle
->getNamespace();
2966 $title = Title
::newFromText( $part1, $ns );
2969 if ( !is_null( $title ) ) {
2970 $titleText = $title->getPrefixedText();
2971 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2972 # Check for language variants if the template is not found
2973 if($checkVariantLink && $title->getArticleID() == 0){
2974 $wgContLang->findVariantLink($part1, $title);
2977 if ( !$title->isExternal() ) {
2978 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2979 $text = SpecialPage
::capturePath( $title );
2980 if ( is_string( $text ) ) {
2985 $this->disableCache();
2988 $articleContent = $this->fetchTemplate( $title );
2989 if ( $articleContent !== false ) {
2991 $text = $articleContent;
2992 $replaceHeadings = true;
2996 # If the title is valid but undisplayable, make a link to it
2997 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2998 $text = "[[:$titleText]]";
3001 } elseif ( $title->isTrans() ) {
3002 // Interwiki transclusion
3003 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3004 $text = $this->interwikiTransclude( $title, 'render' );
3008 $text = $this->interwikiTransclude( $title, 'raw' );
3009 $replaceHeadings = true;
3014 # Template cache array insertion
3015 # Use the original $piece['title'] not the mangled $part1, so that
3016 # modifiers such as RAW: produce separate cache entries
3019 // A special page; don't store it in the template cache.
3021 $this->mTemplates
[$piece['title']] = $text;
3023 $text = $linestart . $text;
3026 wfProfileOut( __METHOD__
. '-loadtpl' );
3029 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3030 # Error, oversize inclusion
3031 $text = $linestart .
3032 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3037 # Recursive parsing, escaping and link table handling
3038 # Only for HTML output
3039 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3040 $text = wfEscapeWikiText( $text );
3041 } elseif ( !$this->ot
['msg'] && $found ) {
3043 $assocArgs = array();
3045 # Clean up argument array
3046 $assocArgs = array();
3048 foreach( $args as $arg ) {
3049 $eqpos = strpos( $arg, '=' );
3050 if ( $eqpos === false ) {
3051 $assocArgs[$index++
] = $arg;
3053 $name = trim( substr( $arg, 0, $eqpos ) );
3054 $value = trim( substr( $arg, $eqpos+
1 ) );
3055 if ( $value === false ) {
3058 if ( $name !== false ) {
3059 $assocArgs[$name] = $value;
3064 # Add a new element to the templace recursion path
3065 $this->mTemplatePath
[$part1] = 1;
3069 # If there are any <onlyinclude> tags, only include them
3070 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3072 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3074 foreach ($m[1] as $piece)
3077 # Remove <noinclude> sections and <includeonly> tags
3078 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3079 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3081 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3082 # Strip <nowiki>, <pre>, etc.
3083 $text = $this->strip( $text, $this->mStripState
);
3084 if ( $this->ot
['html'] ) {
3085 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3086 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3087 $text = Sanitizer
::removeHTMLcomments( $text );
3090 $text = $this->replaceVariables( $text, $assocArgs );
3092 # If the template begins with a table or block-level
3093 # element, it should be treated as beginning a new line.
3094 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3095 $text = "\n" . $text;
3097 } elseif ( !$noargs ) {
3098 # $noparse and !$noargs
3099 # Just replace the arguments, not any double-brace items
3100 # This is used for rendered interwiki transclusion
3101 $text = $this->replaceVariables( $text, $assocArgs, true );
3104 # Prune lower levels off the recursion check path
3105 $this->mTemplatePath
= $lastPathLevel;
3107 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3108 # Error, oversize inclusion
3109 $text = $linestart .
3110 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3116 wfProfileOut( $fname );
3117 return $piece['text'];
3119 wfProfileIn( __METHOD__
. '-placeholders' );
3121 # Replace raw HTML by a placeholder
3122 # Add a blank line preceding, to prevent it from mucking up
3123 # immediately preceding headings
3124 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3126 # replace ==section headers==
3127 # XXX this needs to go away once we have a better parser.
3128 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3129 if( !is_null( $title ) )
3130 $encodedname = base64_encode($title->getPrefixedDBkey());
3132 $encodedname = base64_encode("");
3133 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3134 PREG_SPLIT_DELIM_CAPTURE
);
3137 for( $i = 0; $i < count($m); $i +
= 2 ) {
3139 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3141 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3146 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3147 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3148 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3154 wfProfileOut( __METHOD__
. '-placeholders' );
3157 # Prune lower levels off the recursion check path
3158 $this->mTemplatePath
= $lastPathLevel;
3161 wfProfileOut( $fname );
3162 return $piece['text'];
3164 wfProfileOut( $fname );
3170 * Fetch the unparsed text of a template and register a reference to it.
3172 function fetchTemplate( $title ) {
3174 // Loop to fetch the article, with up to 1 redirect
3175 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3176 $rev = Revision
::newFromTitle( $title );
3177 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3181 $text = $rev->getText();
3182 if ( $text === false ) {
3186 $title = Title
::newFromRedirect( $text );
3192 * Transclude an interwiki link.
3194 function interwikiTransclude( $title, $action ) {
3195 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3197 if (!$wgEnableScaryTranscluding)
3198 return wfMsg('scarytranscludedisabled');
3200 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3201 // But we'll handle it generally anyway
3202 if ( $title->getNamespace() ) {
3203 // Use the canonical namespace, which should work anywhere
3204 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3206 $articleName = $title->getDBkey();
3209 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3210 $url .= "?action=$action";
3211 if (strlen($url) > 255)
3212 return wfMsg('scarytranscludetoolong');
3213 return $this->fetchScaryTemplateMaybeFromCache($url);
3216 function fetchScaryTemplateMaybeFromCache($url) {
3217 global $wgTranscludeCacheExpiry;
3218 $dbr =& wfGetDB(DB_SLAVE
);
3219 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3220 array('tc_url' => $url));
3222 $time = $obj->tc_time
;
3223 $text = $obj->tc_contents
;
3224 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3229 $text = Http
::get($url);
3231 return wfMsg('scarytranscludefailed', $url);
3233 $dbw =& wfGetDB(DB_MASTER
);
3234 $dbw->replace('transcache', array('tc_url'), array(
3236 'tc_time' => time(),
3237 'tc_contents' => $text));
3243 * Triple brace replacement -- used for template arguments
3246 function argSubstitution( $matches ) {
3247 $arg = trim( $matches['title'] );
3248 $text = $matches['text'];
3249 $inputArgs = end( $this->mArgStack
);
3251 if ( array_key_exists( $arg, $inputArgs ) ) {
3252 $text = $inputArgs[$arg];
3253 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3254 null != $matches['parts'] && count($matches['parts']) > 0) {
3255 $text = $matches['parts'][0];
3257 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3258 $text = $matches['text'] .
3259 '<!-- WARNING: argument omitted, expansion size too large -->';
3266 * Increment an include size counter
3268 * @param string $type The type of expansion
3269 * @param integer $size The size of the text
3270 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3272 function incrementIncludeSize( $type, $size ) {
3273 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3276 $this->mIncludeSizes
[$type] +
= $size;
3282 * Detect __NOGALLERY__ magic word and set a placeholder
3284 function stripNoGallery( &$text ) {
3285 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3287 $mw = MagicWord
::get( 'nogallery' );
3288 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3292 * Detect __TOC__ magic word and set a placeholder
3294 function stripToc( $text ) {
3295 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3297 $mw = MagicWord
::get( 'notoc' );
3298 if( $mw->matchAndRemove( $text ) ) {
3299 $this->mShowToc
= false;
3302 $mw = MagicWord
::get( 'toc' );
3303 if( $mw->match( $text ) ) {
3304 $this->mShowToc
= true;
3305 $this->mForceTocPosition
= true;
3307 // Set a placeholder. At the end we'll fill it in with the TOC.
3308 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3310 // Only keep the first one.
3311 $text = $mw->replace( '', $text );
3317 * This function accomplishes several tasks:
3318 * 1) Auto-number headings if that option is enabled
3319 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3320 * 3) Add a Table of contents on the top for users who have enabled the option
3321 * 4) Auto-anchor headings
3323 * It loops through all headlines, collects the necessary data, then splits up the
3324 * string and re-inserts the newly formatted headlines.
3326 * @param string $text
3327 * @param boolean $isMain
3330 function formatHeadings( $text, $isMain=true ) {
3331 global $wgMaxTocLevel, $wgContLang;
3333 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3334 if( !$this->mTitle
->userCanEdit() ) {
3337 $showEditLink = $this->mOptions
->getEditSection();
3340 # Inhibit editsection links if requested in the page
3341 $esw =& MagicWord
::get( 'noeditsection' );
3342 if( $esw->matchAndRemove( $text ) ) {
3346 # Get all headlines for numbering them and adding funky stuff like [edit]
3347 # links - this is for later, but we need the number of headlines right now
3349 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3351 # if there are fewer than 4 headlines in the article, do not show TOC
3352 # unless it's been explicitly enabled.
3353 $enoughToc = $this->mShowToc
&&
3354 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3356 # Allow user to stipulate that a page should have a "new section"
3357 # link added via __NEWSECTIONLINK__
3358 $mw =& MagicWord
::get( 'newsectionlink' );
3359 if( $mw->matchAndRemove( $text ) )
3360 $this->mOutput
->setNewSection( true );
3362 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3363 # override above conditions and always show TOC above first header
3364 $mw =& MagicWord
::get( 'forcetoc' );
3365 if ($mw->matchAndRemove( $text ) ) {
3366 $this->mShowToc
= true;
3370 # Never ever show TOC if no headers
3371 if( $numMatches < 1 ) {
3377 $sectionCount = 0; # headlineCount excluding template sections
3379 # Ugh .. the TOC should have neat indentation levels which can be
3380 # passed to the skin functions. These are determined here
3384 $sublevelCount = array();
3385 $levelCount = array();
3392 foreach( $matches[3] as $headline ) {
3394 $templatetitle = '';
3395 $templatesection = 0;
3398 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3400 $templatetitle = base64_decode($mat[1]);
3401 $templatesection = 1 +
(int)base64_decode($mat[2]);
3402 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3406 $prevlevel = $level;
3407 $prevtoclevel = $toclevel;
3409 $level = $matches[1][$headlineCount];
3411 if( $doNumberHeadings ||
$enoughToc ) {
3413 if ( $level > $prevlevel ) {
3414 # Increase TOC level
3416 $sublevelCount[$toclevel] = 0;
3417 if( $toclevel<$wgMaxTocLevel ) {
3418 $toc .= Linker
::tocIndent();
3421 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3422 # Decrease TOC level, find level to jump to
3424 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3425 # Can only go down to level 1
3428 for ($i = $toclevel; $i > 0; $i--) {
3429 if ( $levelCount[$i] == $level ) {
3430 # Found last matching level
3434 elseif ( $levelCount[$i] < $level ) {
3435 # Found first matching level below current level
3441 if( $toclevel<$wgMaxTocLevel ) {
3442 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3446 # No change in level, end TOC line
3447 if( $toclevel<$wgMaxTocLevel ) {
3448 $toc .= Linker
::tocLineEnd();
3452 $levelCount[$toclevel] = $level;
3454 # count number of headlines for each level
3455 @$sublevelCount[$toclevel]++
;
3457 for( $i = 1; $i <= $toclevel; $i++
) {
3458 if( !empty( $sublevelCount[$i] ) ) {
3462 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3468 # The canonized header is a version of the header text safe to use for links
3469 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3470 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3471 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3473 # Remove link placeholders by the link text.
3474 # <!--LINK number-->
3476 # link text with suffix
3477 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3478 "\$this->mLinkHolders['texts'][\$1]",
3479 $canonized_headline );
3480 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3481 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3482 $canonized_headline );
3485 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3486 $tocline = trim( $canonized_headline );
3487 # Save headline for section edit hint before it's escaped
3488 $headline_hint = trim( $canonized_headline );
3489 $canonized_headline = Sanitizer
::escapeId( $tocline );
3490 $refers[$headlineCount] = $canonized_headline;
3492 # count how many in assoc. array so we can track dupes in anchors
3493 @$refers[$canonized_headline]++
;
3494 $refcount[$headlineCount]=$refers[$canonized_headline];
3496 # Don't number the heading if it is the only one (looks silly)
3497 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3498 # the two are different if the line contains a link
3499 $headline=$numbering . ' ' . $headline;
3502 # Create the anchor for linking from the TOC to the section
3503 $anchor = $canonized_headline;
3504 if($refcount[$headlineCount] > 1 ) {
3505 $anchor .= '_' . $refcount[$headlineCount];
3507 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3508 $toc .= Linker
::tocLine($anchor, $tocline, $numbering, $toclevel);
3510 # give headline the correct <h#> tag
3511 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3513 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3514 if ( empty( $head[$headlineCount] ) ) {
3515 $head[$headlineCount] = '';
3518 $head[$headlineCount] .= Linker
::editSectionLinkForOther($templatetitle, $templatesection);
3520 $head[$headlineCount] .= Linker
::editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3522 // Yes, the headline logically goes before the edit section. Why isn't it there
3523 // in source? Ask the CSS people. The float gets screwed up if you do that.
3524 // This might be moved to before the editsection at some point so that it will
3525 // display a bit more prettily without CSS, so please don't rely on the order.
3526 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3534 if( $toclevel<$wgMaxTocLevel ) {
3535 $toc .= Linker
::tocUnindent( $toclevel - 1 );
3537 $toc = Linker
::tocList( $toc );
3540 # split up and insert constructed headlines
3542 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3545 foreach( $blocks as $block ) {
3546 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3547 # This is the [edit] link that appears for the top block of text when
3548 # section editing is enabled
3550 # Disabled because it broke block formatting
3551 # For example, a bullet point in the top line
3552 # $full .= Linker::editSectionLink(0);
3555 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3556 # Top anchor now in skin
3560 if( !empty( $head[$i] ) ) {
3565 if( $this->mForceTocPosition
) {
3566 return str_replace( '<!--MWTOC-->', $toc, $full );
3573 * Transform wiki markup when saving a page by doing \r\n -> \n
3574 * conversion, substitting signatures, {{subst:}} templates, etc.
3576 * @param string $text the text to transform
3577 * @param Title &$title the Title object for the current article
3578 * @param User &$user the User object describing the current user
3579 * @param ParserOptions $options parsing options
3580 * @param bool $clearState whether to clear the parser state first
3581 * @return string the altered wiki markup
3584 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3585 $this->mOptions
= $options;
3586 $this->mTitle
=& $title;
3587 $this->setOutputType( OT_WIKI
);
3589 if ( $clearState ) {
3590 $this->clearState();
3593 $stripState = false;
3597 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3598 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3599 $text = $this->pstPass2( $text, $stripState, $user );
3600 $text = $this->unstrip( $text, $stripState );
3601 $text = $this->unstripNoWiki( $text, $stripState );
3606 * Pre-save transform helper function
3609 function pstPass2( $text, &$stripState, $user ) {
3610 global $wgContLang, $wgLocaltimezone;
3612 /* Note: This is the timestamp saved as hardcoded wikitext to
3613 * the database, we use $wgContLang here in order to give
3614 * everyone the same signature and use the default one rather
3615 * than the one selected in each user's preferences.
3617 if ( isset( $wgLocaltimezone ) ) {
3618 $oldtz = getenv( 'TZ' );
3619 putenv( 'TZ='.$wgLocaltimezone );
3621 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3622 ' (' . date( 'T' ) . ')';
3623 if ( isset( $wgLocaltimezone ) ) {
3624 putenv( 'TZ='.$oldtz );
3627 # Variable replacement
3628 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3629 $text = $this->replaceVariables( $text );
3631 # Strip out <nowiki> etc. added via replaceVariables
3632 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3635 $sigText = $this->getUserSig( $user );
3636 $text = strtr( $text, array(
3638 '~~~~' => "$sigText $d",
3642 # Context links: [[|name]] and [[name (context)|]]
3644 global $wgLegalTitleChars;
3645 $tc = "[$wgLegalTitleChars]";
3646 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3648 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3649 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3650 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3652 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3653 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3654 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3656 $t = $this->mTitle
->getText();
3658 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3659 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3660 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3661 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3663 # if there's no context, don't bother duplicating the title
3664 $text = preg_replace( $p2, '[[\\1]]', $text );
3667 # Trim trailing whitespace
3668 # __END__ tag allows for trailing
3669 # whitespace to be deliberately included
3670 $text = rtrim( $text );
3671 $mw =& MagicWord
::get( 'end' );
3672 $mw->matchAndRemove( $text );
3678 * Fetch the user's signature text, if any, and normalize to
3679 * validated, ready-to-insert wikitext.
3685 function getUserSig( &$user ) {
3686 $username = $user->getName();
3687 $nickname = $user->getOption( 'nickname' );
3688 $nickname = $nickname === '' ?
$username : $nickname;
3690 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3691 # Sig. might contain markup; validate this
3692 if( $this->validateSig( $nickname ) !== false ) {
3693 # Validated; clean up (if needed) and return it
3694 return $this->cleanSig( $nickname, true );
3696 # Failed to validate; fall back to the default
3697 $nickname = $username;
3698 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3702 // Make sure nickname doesnt get a sig in a sig
3703 $nickname = $this->cleanSigInSig( $nickname );
3705 # If we're still here, make it a link to the user page
3706 $userpage = $user->getUserPage();
3707 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3711 * Check that the user's signature contains no bad XML
3713 * @param string $text
3714 * @return mixed An expanded string, or false if invalid.
3716 function validateSig( $text ) {
3717 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3721 * Clean up signature text
3723 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3724 * 2) Substitute all transclusions
3726 * @param string $text
3727 * @param $parsing Whether we're cleaning (preferences save) or parsing
3728 * @return string Signature text
3730 function cleanSig( $text, $parsing = false ) {
3732 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3734 $substWord = MagicWord
::get( 'subst' );
3735 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3736 $substText = '{{' . $substWord->getSynonym( 0 );
3738 $text = preg_replace( $substRegex, $substText, $text );
3739 $text = $this->cleanSigInSig( $text );
3740 $text = $this->replaceVariables( $text );
3742 $this->clearState();
3747 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3748 * @param string $text
3749 * @return string Signature text with /~{3,5}/ removed
3751 function cleanSigInSig( $text ) {
3752 $text = preg_replace( '/~{3,5}/', '', $text );
3757 * Set up some variables which are usually set up in parse()
3758 * so that an external function can call some class members with confidence
3761 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3762 $this->mTitle
=& $title;
3763 $this->mOptions
= $options;
3764 $this->setOutputType( $outputType );
3765 if ( $clearState ) {
3766 $this->clearState();
3771 * Transform a MediaWiki message by replacing magic variables.
3773 * @param string $text the text to transform
3774 * @param ParserOptions $options options
3775 * @return string the text with variables substituted
3778 function transformMsg( $text, $options ) {
3780 static $executing = false;
3782 $fname = "Parser::transformMsg";
3784 # Guard against infinite recursion
3790 wfProfileIn($fname);
3793 $this->mTitle
= $wgTitle;
3795 $this->mTitle
= Title
::newFromText('msg');
3797 $this->mOptions
= $options;
3798 $this->setOutputType( OT_MSG
);
3799 $this->clearState();
3800 $text = $this->replaceVariables( $text );
3803 wfProfileOut($fname);
3808 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3809 * The callback should have the following form:
3810 * function myParserHook( $text, $params, &$parser ) { ... }
3812 * Transform and return $text. Use $parser for any required context, e.g. use
3813 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3817 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3818 * @param mixed $callback The callback function (and object) to use for the tag
3820 * @return The old value of the mTagHooks array associated with the hook
3822 function setHook( $tag, $callback ) {
3823 $tag = strtolower( $tag );
3824 $oldVal = @$this->mTagHooks
[$tag];
3825 $this->mTagHooks
[$tag] = $callback;
3831 * Create a function, e.g. {{sum:1|2|3}}
3832 * The callback function should have the form:
3833 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3835 * The callback may either return the text result of the function, or an array with the text
3836 * in element 0, and a number of flags in the other elements. The names of the flags are
3837 * specified in the keys. Valid flags are:
3838 * found The text returned is valid, stop processing the template. This
3840 * nowiki Wiki markup in the return value should be escaped
3841 * noparse Unsafe HTML tags should not be stripped, etc.
3842 * noargs Don't replace triple-brace arguments in the return value
3843 * isHTML The returned text is HTML, armour it against wikitext transformation
3847 * @param string $id The magic word ID
3848 * @param mixed $callback The callback function (and object) to use
3849 * @param integer $flags a combination of the following flags:
3850 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3852 * @return The old callback function for this name, if any
3854 function setFunctionHook( $id, $callback, $flags = 0 ) {
3855 $oldVal = @$this->mFunctionHooks
[$id];
3856 $this->mFunctionHooks
[$id] = $callback;
3858 # Add to function cache
3859 $mw = MagicWord
::get( $id );
3861 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3863 $synonyms = $mw->getSynonyms();
3864 $sensitive = intval( $mw->isCaseSensitive() );
3866 foreach ( $synonyms as $syn ) {
3868 if ( !$sensitive ) {
3869 $syn = strtolower( $syn );
3872 if ( !( $flags & SFH_NO_HASH
) ) {
3875 # Remove trailing colon
3876 if ( substr( $syn, -1, 1 ) == ':' ) {
3877 $syn = substr( $syn, 0, -1 );
3879 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3885 * Get all registered function hook identifiers
3889 function getFunctionHooks() {
3890 return array_keys( $this->mFunctionHooks
);
3894 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3895 * Placeholders created in Linker::makeLinkObj()
3896 * Returns an array of links found, indexed by PDBK:
3900 * $options is a bit field, RLH_FOR_UPDATE to select for update
3902 function replaceLinkHolders( &$text, $options = 0 ) {
3904 global $wgOutputReplace;
3907 $fname = 'Parser::replaceLinkHolders';
3908 wfProfileIn( $fname );
3912 $linkCache =& LinkCache
::singleton();
3914 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3915 wfProfileIn( $fname.'-check' );
3916 $dbr =& wfGetDB( DB_SLAVE
);
3917 $page = $dbr->tableName( 'page' );
3918 $threshold = $wgUser->getOption('stubthreshold');
3921 asort( $this->mLinkHolders
['namespaces'] );
3926 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3928 $title = $this->mLinkHolders
['titles'][$key];
3930 # Skip invalid entries.
3931 # Result will be ugly, but prevents crash.
3932 if ( is_null( $title ) ) {
3935 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3937 # Check if it's a static known link, e.g. interwiki
3938 if ( $title->isAlwaysKnown() ) {
3939 $colours[$pdbk] = 1;
3940 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3941 $colours[$pdbk] = 1;
3942 $this->mOutput
->addLink( $title, $id );
3943 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3944 $colours[$pdbk] = 0;
3946 # Not in the link cache, add it to the query
3947 if ( !isset( $current ) ) {
3949 $query = "SELECT page_id, page_namespace, page_title";
3950 if ( $threshold > 0 ) {
3951 $query .= ', page_len, page_is_redirect';
3953 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3954 } elseif ( $current != $ns ) {
3956 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3961 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3966 if ( $options & RLH_FOR_UPDATE
) {
3967 $query .= ' FOR UPDATE';
3970 $res = $dbr->query( $query, $fname );
3972 # Fetch data and form into an associative array
3973 # non-existent = broken
3976 while ( $s = $dbr->fetchObject($res) ) {
3977 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3978 $pdbk = $title->getPrefixedDBkey();
3979 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3980 $this->mOutput
->addLink( $title, $s->page_id
);
3982 if ( $threshold > 0 ) {
3983 $size = $s->page_len
;
3984 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3985 $colours[$pdbk] = 1;
3987 $colours[$pdbk] = 2;
3990 $colours[$pdbk] = 1;
3994 wfProfileOut( $fname.'-check' );
3996 # Do a second query for different language variants of links (if needed)
3997 if($wgContLang->hasVariants()){
3998 $linkBatch = new LinkBatch();
3999 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
4001 // Add variants of links to link batch
4002 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4003 $title = $this->mLinkHolders
['titles'][$key];
4004 if ( is_null( $title ) )
4007 $pdbk = $title->getPrefixedDBkey();
4009 // generate all variants of the link title text
4010 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4012 // if link was not found (in first query), add all variants to query
4013 if ( !isset($colours[$pdbk]) ){
4014 foreach($allTextVariants as $textVariant){
4015 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4016 if(is_null($variantTitle)) continue;
4017 $linkBatch->addObj( $variantTitle );
4018 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4024 if(!$linkBatch->isEmpty()){
4026 $titleClause = $linkBatch->constructSet('page', $dbr);
4028 $variantQuery = "SELECT page_id, page_namespace, page_title";
4029 if ( $threshold > 0 ) {
4030 $variantQuery .= ', page_len, page_is_redirect';
4033 $variantQuery .= " FROM $page WHERE $titleClause";
4034 if ( $options & RLH_FOR_UPDATE
) {
4035 $variantQuery .= ' FOR UPDATE';
4038 $varRes = $dbr->query( $variantQuery, $fname );
4040 // for each found variants, figure out link holders and replace
4041 while ( $s = $dbr->fetchObject($varRes) ) {
4043 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4044 $varPdbk = $variantTitle->getPrefixedDBkey();
4045 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4046 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4048 $holderKeys = $variantMap[$varPdbk];
4050 // loop over link holders
4051 foreach($holderKeys as $key){
4052 $title = $this->mLinkHolders
['titles'][$key];
4053 if ( is_null( $title ) ) continue;
4055 $pdbk = $title->getPrefixedDBkey();
4057 if(!isset($colours[$pdbk])){
4058 // found link in some of the variants, replace the link holder data
4059 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4060 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4062 // set pdbk and colour
4063 $pdbks[$key] = $varPdbk;
4064 if ( $threshold > 0 ) {
4065 $size = $s->page_len
;
4066 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4067 $colours[$varPdbk] = 1;
4069 $colours[$varPdbk] = 2;
4073 $colours[$varPdbk] = 1;
4081 # Construct search and replace arrays
4082 wfProfileIn( $fname.'-construct' );
4083 $wgOutputReplace = array();
4084 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4085 $pdbk = $pdbks[$key];
4086 $searchkey = "<!--LINK $key-->";
4087 $title = $this->mLinkHolders
['titles'][$key];
4088 if ( empty( $colours[$pdbk] ) ) {
4089 $linkCache->addBadLinkObj( $title );
4090 $colours[$pdbk] = 0;
4091 $this->mOutput
->addLink( $title, 0 );
4092 $wgOutputReplace[$searchkey] = Linker
::makeBrokenLinkObj( $title,
4093 $this->mLinkHolders
['texts'][$key],
4094 $this->mLinkHolders
['queries'][$key] );
4095 } elseif ( $colours[$pdbk] == 1 ) {
4096 $wgOutputReplace[$searchkey] = Linker
::makeKnownLinkObj( $title,
4097 $this->mLinkHolders
['texts'][$key],
4098 $this->mLinkHolders
['queries'][$key] );
4099 } elseif ( $colours[$pdbk] == 2 ) {
4100 $wgOutputReplace[$searchkey] = Linker
::makeStubLinkObj( $title,
4101 $this->mLinkHolders
['texts'][$key],
4102 $this->mLinkHolders
['queries'][$key] );
4105 wfProfileOut( $fname.'-construct' );
4108 wfProfileIn( $fname.'-replace' );
4110 $text = preg_replace_callback(
4111 '/(<!--LINK .*?-->)/',
4112 "wfOutputReplaceMatches",
4115 wfProfileOut( $fname.'-replace' );
4118 # Now process interwiki link holders
4119 # This is quite a bit simpler than internal links
4120 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4121 wfProfileIn( $fname.'-interwiki' );
4122 # Make interwiki link HTML
4123 $wgOutputReplace = array();
4124 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4125 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4126 $wgOutputReplace[$key] = Linker
::makeLinkObj( $title, $link );
4129 $text = preg_replace_callback(
4130 '/<!--IWLINK (.*?)-->/',
4131 "wfOutputReplaceMatches",
4133 wfProfileOut( $fname.'-interwiki' );
4136 wfProfileOut( $fname );
4141 * Replace <!--LINK--> link placeholders with plain text of links
4142 * (not HTML-formatted).
4143 * @param string $text
4146 function replaceLinkHoldersText( $text ) {
4147 $fname = 'Parser::replaceLinkHoldersText';
4148 wfProfileIn( $fname );
4150 $text = preg_replace_callback(
4151 '/<!--(LINK|IWLINK) (.*?)-->/',
4152 array( &$this, 'replaceLinkHoldersTextCallback' ),
4155 wfProfileOut( $fname );
4160 * @param array $matches
4164 function replaceLinkHoldersTextCallback( $matches ) {
4165 $type = $matches[1];
4167 if( $type == 'LINK' ) {
4168 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4169 return $this->mLinkHolders
['texts'][$key];
4171 } elseif( $type == 'IWLINK' ) {
4172 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4173 return $this->mInterwikiLinkHolders
['texts'][$key];
4180 * Tag hook handler for 'pre'.
4182 function renderPreTag( $text, $attribs ) {
4183 // Backwards-compatibility hack
4184 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4186 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4187 return wfOpenElement( 'pre', $attribs ) .
4188 wfEscapeHTMLTagsOnly( $content ) .
4193 * Renders an image gallery from a text with one line per image.
4194 * text labels may be given by using |-style alternative text. E.g.
4195 * Image:one.jpg|The number "1"
4196 * Image:tree.jpg|A tree
4197 * given as text will return the HTML of a gallery with two images,
4198 * labeled 'The number "1"' and
4201 function renderImageGallery( $text, $params ) {
4202 $ig = new ImageGallery();
4203 $ig->setShowBytes( false );
4204 $ig->setShowFilename( false );
4207 if( isset( $params['caption'] ) )
4208 $ig->setCaption( $params['caption'] );
4210 $lines = explode( "\n", $text );
4211 foreach ( $lines as $line ) {
4212 # match lines like these:
4213 # Image:someimage.jpg|This is some image
4215 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4217 if ( count( $matches ) == 0 ) {
4220 $tp = Title
::newFromText( $matches[1] );
4222 if( is_null( $nt ) ) {
4223 # Bogus title. Ignore these so we don't bomb out later.
4226 if ( isset( $matches[3] ) ) {
4227 $label = $matches[3];
4232 $pout = $this->parse( $label,
4235 false, // Strip whitespace...?
4236 false // Don't clear state!
4238 $html = $pout->getText();
4240 $ig->add( new Image( $nt ), $html );
4242 # Only add real images (bug #5586)
4243 if ( $nt->getNamespace() == NS_IMAGE
) {
4244 $this->mOutput
->addImage( $nt->getDBkey() );
4247 return $ig->toHTML();
4251 * Parse image options text and use it to make an image
4253 function makeImage( $nt, $options ) {
4254 global $wgUseImageResize, $wgDjvuRenderer;
4258 # Check if the options text is of the form "options|alt text"
4260 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4261 # * left no resizing, just left align. label is used for alt= only
4262 # * right same, but right aligned
4263 # * none same, but not aligned
4264 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4265 # * center center the image
4266 # * framed Keep original image size, no magnify-button.
4268 $part = explode( '|', $options);
4270 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4271 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4272 $mwLeft =& MagicWord
::get( 'img_left' );
4273 $mwRight =& MagicWord
::get( 'img_right' );
4274 $mwNone =& MagicWord
::get( 'img_none' );
4275 $mwWidth =& MagicWord
::get( 'img_width' );
4276 $mwCenter =& MagicWord
::get( 'img_center' );
4277 $mwFramed =& MagicWord
::get( 'img_framed' );
4278 $mwPage =& MagicWord
::get( 'img_page' );
4281 $width = $height = $framed = $thumb = false;
4283 $manual_thumb = '' ;
4285 foreach( $part as $val ) {
4286 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4288 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4289 # use manually specified thumbnail
4291 $manual_thumb = $match;
4292 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4293 # remember to set an alignment, don't render immediately
4295 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4296 # remember to set an alignment, don't render immediately
4298 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4299 # remember to set an alignment, don't render immediately
4301 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4302 # remember to set an alignment, don't render immediately
4304 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4305 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4306 # Select a page in a multipage document
4308 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4309 wfDebug( "img_width match: $match\n" );
4310 # $match is the image width in pixels
4312 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4313 $width = intval( $m[1] );
4314 $height = intval( $m[2] );
4316 $width = intval($match);
4318 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4324 # Strip bad stuff out of the alt text
4325 $alt = $this->replaceLinkHoldersText( $caption );
4327 # make sure there are no placeholders in thumbnail attributes
4328 # that are later expanded to html- so expand them now and
4330 $alt = $this->unstrip($alt, $this->mStripState
);
4331 $alt = Sanitizer
::stripAllTags( $alt );
4333 # Linker does the rest
4334 return Linker
::makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4338 * Set a flag in the output object indicating that the content is dynamic and
4339 * shouldn't be cached.
4341 function disableCache() {
4342 wfDebug( "Parser output marked as uncacheable.\n" );
4343 $this->mOutput
->mCacheTime
= -1;
4347 * Callback from the Sanitizer for expanding items found in HTML attribute
4348 * values, so they can be safely tested and escaped.
4349 * @param string $text
4350 * @param array $args
4354 function attributeStripCallback( &$text, $args ) {
4355 $text = $this->replaceVariables( $text, $args );
4356 $text = $this->unstripForHTML( $text );
4360 function unstripForHTML( $text ) {
4361 $text = $this->unstrip( $text, $this->mStripState
);
4362 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4370 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4371 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4372 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4378 function getTags() { return array_keys( $this->mTagHooks
); }
4383 * Break wikitext input into sections, and either pull or replace
4384 * some particular section's text.
4386 * External callers should use the getSection and replaceSection methods.
4388 * @param $text Page wikitext
4389 * @param $section Numbered section. 0 pulls the text before the first
4390 * heading; other numbers will pull the given section
4391 * along with its lower-level subsections.
4392 * @param $mode One of "get" or "replace"
4393 * @param $newtext Replacement text for section data.
4394 * @return string for "get", the extracted section text.
4395 * for "replace", the whole page with the section replaced.
4397 private function extractSections( $text, $section, $mode, $newtext='' ) {
4398 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4399 # comments to be stripped as well)
4400 $striparray = array();
4402 $oldOutputType = $this->mOutputType
;
4403 $oldOptions = $this->mOptions
;
4404 $this->mOptions
= new ParserOptions();
4405 $this->setOutputType( OT_WIKI
);
4407 $striptext = $this->strip( $text, $striparray, true );
4409 $this->setOutputType( $oldOutputType );
4410 $this->mOptions
= $oldOptions;
4412 # now that we can be sure that no pseudo-sections are in the source,
4413 # split it up by section
4414 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4415 $comment = "(?:$uniq-!--.*?QINU)";
4420 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4422 (=+) # Should this be limited to 6?
4423 .+? # Section title...
4424 \\2 # Ending = count must match start
4431 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4438 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4439 (=+) # Should this be limited to 6?
4440 .+? # Section title...
4441 \\2 # Ending = count must match start
4442 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4451 PREG_SPLIT_DELIM_CAPTURE
);
4453 if( $mode == "get" ) {
4454 if( $section == 0 ) {
4455 // "Section 0" returns the content before any other section.
4460 } elseif( $mode == "replace" ) {
4461 if( $section == 0 ) {
4462 $rv = $newtext . "\n\n";
4471 for( $index = 1; $index < count( $secs ); ) {
4472 $headerLine = $secs[$index++
];
4473 if( $secs[$index] ) {
4475 $headerLevel = strlen( $secs[$index++
] );
4479 $headerLevel = intval( $secs[$index++
] );
4481 $content = $secs[$index++
];
4484 if( $mode == "get" ) {
4485 if( $count == $section ) {
4486 $rv = $headerLine . $content;
4487 $sectionLevel = $headerLevel;
4488 } elseif( $count > $section ) {
4489 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4490 $rv .= $headerLine . $content;
4492 // Broke out to a higher-level section
4496 } elseif( $mode == "replace" ) {
4497 if( $count < $section ) {
4498 $rv .= $headerLine . $content;
4499 } elseif( $count == $section ) {
4500 $rv .= $newtext . "\n\n";
4501 $sectionLevel = $headerLevel;
4502 } elseif( $count > $section ) {
4503 if( $headerLevel <= $sectionLevel ) {
4504 // Passed the section's sub-parts.
4508 $rv .= $headerLine . $content;
4513 # reinsert stripped tags
4514 $rv = $this->unstrip( $rv, $striparray );
4515 $rv = $this->unstripNoWiki( $rv, $striparray );
4521 * This function returns the text of a section, specified by a number ($section).
4522 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4523 * the first section before any such heading (section 0).
4525 * If a section contains subsections, these are also returned.
4527 * @param $text String: text to look in
4528 * @param $section Integer: section number
4529 * @return string text of the requested section
4531 function getSection( $text, $section ) {
4532 return $this->extractSections( $text, $section, "get" );
4535 function replaceSection( $oldtext, $section, $text ) {
4536 return $this->extractSections( $oldtext, $section, "replace", $text );
4543 * @package MediaWiki
4547 var $mText, # The output text
4548 $mLanguageLinks, # List of the full text of language links, in the order they appear
4549 $mCategories, # Map of category names to sort keys
4550 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4551 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4552 $mVersion, # Compatibility check
4553 $mTitleText, # title text of the chosen language variant
4554 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4555 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4556 $mImages, # DB keys of the images used, in the array key only
4557 $mExternalLinks, # External link URLs, in the key only
4558 $mHTMLtitle, # Display HTML title
4559 $mSubtitle, # Additional subtitle
4560 $mNewSection, # Show a new section link?
4561 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4563 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4564 $containsOldMagic = false, $titletext = '' )
4566 $this->mText
= $text;
4567 $this->mLanguageLinks
= $languageLinks;
4568 $this->mCategories
= $categoryLinks;
4569 $this->mContainsOldMagic
= $containsOldMagic;
4570 $this->mCacheTime
= '';
4571 $this->mVersion
= MW_PARSER_VERSION
;
4572 $this->mTitleText
= $titletext;
4573 $this->mLinks
= array();
4574 $this->mTemplates
= array();
4575 $this->mImages
= array();
4576 $this->mExternalLinks
= array();
4577 $this->mHTMLtitle
= "" ;
4578 $this->mSubtitle
= "" ;
4579 $this->mNewSection
= false;
4580 $this->mNoGallery
= false;
4583 function getText() { return $this->mText
; }
4584 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4585 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4586 function &getCategories() { return $this->mCategories
; }
4587 function getCacheTime() { return $this->mCacheTime
; }
4588 function getTitleText() { return $this->mTitleText
; }
4589 function &getLinks() { return $this->mLinks
; }
4590 function &getTemplates() { return $this->mTemplates
; }
4591 function &getImages() { return $this->mImages
; }
4592 function &getExternalLinks() { return $this->mExternalLinks
; }
4593 function getNoGallery() { return $this->mNoGallery
; }
4594 function getSubtitle() { return $this->mSubtitle
; }
4596 function containsOldMagic() { return $this->mContainsOldMagic
; }
4597 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4598 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4599 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4600 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4601 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4602 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4603 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4605 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4606 function addImage( $name ) { $this->mImages
[$name] = 1; }
4607 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4608 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4610 function setNewSection( $value ) {
4611 $this->mNewSection
= (bool)$value;
4613 function getNewSection() {
4614 return (bool)$this->mNewSection
;
4617 function addLink( $title, $id = null ) {
4618 $ns = $title->getNamespace();
4619 $dbk = $title->getDBkey();
4620 if ( !isset( $this->mLinks
[$ns] ) ) {
4621 $this->mLinks
[$ns] = array();
4623 if ( is_null( $id ) ) {
4624 $id = $title->getArticleID();
4626 $this->mLinks
[$ns][$dbk] = $id;
4629 function addTemplate( $title, $id ) {
4630 $ns = $title->getNamespace();
4631 $dbk = $title->getDBkey();
4632 if ( !isset( $this->mTemplates
[$ns] ) ) {
4633 $this->mTemplates
[$ns] = array();
4635 $this->mTemplates
[$ns][$dbk] = $id;
4639 * Return true if this cached output object predates the global or
4640 * per-article cache invalidation timestamps, or if it comes from
4641 * an incompatible older version.
4643 * @param string $touched the affected article's last touched timestamp
4647 function expired( $touched ) {
4648 global $wgCacheEpoch;
4649 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4650 $this->getCacheTime() < $touched ||
4651 $this->getCacheTime() <= $wgCacheEpoch ||
4652 !isset( $this->mVersion
) ||
4653 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4658 * Set options of the Parser
4660 * @package MediaWiki
4664 # All variables are supposed to be private in theory, although in practise this is not the case.
4665 var $mUseTeX; # Use texvc to expand <math> tags
4666 var $mUseDynamicDates; # Use DateFormatter to format dates
4667 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4668 var $mAllowExternalImages; # Allow external images inline
4669 var $mAllowExternalImagesFrom; # If not, any exception?
4670 var $mDateFormat; # Date format index
4671 var $mEditSection; # Create "edit section" links
4672 var $mNumberHeadings; # Automatically number headings
4673 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4674 var $mTidy; # Ask for tidy cleanup
4675 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4676 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4677 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4679 var $mUser; # Stored user object, just used to initialise the date format
4681 function getUseTeX() { return $this->mUseTeX
; }
4682 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4683 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4684 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4685 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4686 function getEditSection() { return $this->mEditSection
; }
4687 function getNumberHeadings() { return $this->mNumberHeadings
; }
4688 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4689 function getTidy() { return $this->mTidy
; }
4690 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4691 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4692 function getRemoveComments() { return $this->mRemoveComments
; }
4694 function getDateFormat() {
4695 if ( !isset( $this->mDateFormat
) ) {
4696 $this->mDateFormat
= $this->mUser
->getDatePreference();
4698 return $this->mDateFormat
;
4701 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4702 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4703 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4704 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4705 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4706 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4707 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4708 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4709 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4710 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4711 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4712 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4713 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4715 function ParserOptions( $user = null ) {
4716 $this->initialiseFromUser( $user );
4720 * Get parser options
4723 static function newFromUser( $user ) {
4724 return new ParserOptions( $user );
4727 /** Get user options */
4728 function initialiseFromUser( $userInput ) {
4729 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4730 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4731 $fname = 'ParserOptions::initialiseFromUser';
4732 wfProfileIn( $fname );
4733 if ( !$userInput ) {
4735 if ( isset( $wgUser ) ) {
4741 $user =& $userInput;
4744 $this->mUser
= $user;
4746 $this->mUseTeX
= $wgUseTeX;
4747 $this->mUseDynamicDates
= $wgUseDynamicDates;
4748 $this->mInterwikiMagic
= $wgInterwikiMagic;
4749 $this->mAllowExternalImages
= $wgAllowExternalImages;
4750 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4751 $this->mDateFormat
= null; # Deferred
4752 $this->mEditSection
= true;
4753 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4754 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4755 $this->mTidy
= false;
4756 $this->mInterfaceMessage
= false;
4757 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4758 $this->mRemoveComments
= true;
4759 wfProfileOut( $fname );
4764 * Callback function used by Parser::replaceLinkHolders()
4765 * to substitute link placeholders.
4767 function &wfOutputReplaceMatches( $matches ) {
4768 global $wgOutputReplace;
4769 return $wgOutputReplace[$matches[1]];
4773 * Return the total number of articles
4775 function wfNumberOfArticles() {
4776 global $wgNumberOfArticles;
4779 return $wgNumberOfArticles;
4783 * Return the number of files
4785 function wfNumberOfFiles() {
4786 $fname = 'wfNumberOfFiles';
4788 wfProfileIn( $fname );
4789 $dbr =& wfGetDB( DB_SLAVE
);
4790 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4791 wfProfileOut( $fname );
4797 * Return the number of user accounts
4800 function wfNumberOfUsers() {
4801 wfProfileIn( 'wfNumberOfUsers' );
4802 $dbr =& wfGetDB( DB_SLAVE
);
4803 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4804 wfProfileOut( 'wfNumberOfUsers' );
4809 * Return the total number of pages
4812 function wfNumberOfPages() {
4813 wfProfileIn( 'wfNumberOfPages' );
4814 $dbr =& wfGetDB( DB_SLAVE
);
4815 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4816 wfProfileOut( 'wfNumberOfPages' );
4821 * Return the total number of admins
4825 function wfNumberOfAdmins() {
4826 static $admins = -1;
4827 wfProfileIn( 'wfNumberOfAdmins' );
4828 if( $admins == -1 ) {
4829 $dbr =& wfGetDB( DB_SLAVE
);
4830 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4832 wfProfileOut( 'wfNumberOfAdmins' );
4833 return (int)$admins;
4837 * Count the number of pages in a particular namespace
4839 * @param $ns Namespace
4842 function wfPagesInNs( $ns ) {
4843 static $pageCount = array();
4844 wfProfileIn( 'wfPagesInNs' );
4845 if( !isset( $pageCount[$ns] ) ) {
4846 $dbr =& wfGetDB( DB_SLAVE
);
4847 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4849 wfProfileOut( 'wfPagesInNs' );
4850 return (int)$pageCount[$ns];
4854 * Get various statistics from the database
4857 function wfLoadSiteStats() {
4858 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4859 $fname = 'wfLoadSiteStats';
4861 if ( -1 != $wgNumberOfArticles ) return;
4862 $dbr =& wfGetDB( DB_SLAVE
);
4863 $s = $dbr->selectRow( 'site_stats',
4864 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4865 array( 'ss_row_id' => 1 ), $fname
4868 if ( $s === false ) {
4871 $wgTotalViews = $s->ss_total_views
;
4872 $wgTotalEdits = $s->ss_total_edits
;
4873 $wgNumberOfArticles = $s->ss_good_articles
;
4878 * Get revision timestamp from the database considering timecorrection
4880 * @param $id Int: page revision id
4883 function wfRevisionTimestamp( $id ) {
4885 $fname = 'wfRevisionTimestamp';
4887 wfProfileIn( $fname );
4888 $dbr =& wfGetDB( DB_SLAVE
);
4889 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4890 array( 'rev_id' => $id ), __METHOD__
);
4891 $timestamp = $wgContLang->userAdjust( $timestamp );
4892 wfProfileOut( $fname );
4899 * Basically replacing " > and < with HTML entities ( ", >, <)
4901 * @param $in String: text that might contain HTML tags.
4902 * @return string Escaped string
4904 function wfEscapeHTMLTagsOnly( $in ) {
4906 array( '"', '>', '<' ),
4907 array( '"', '>', '<' ),