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 three main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
74 * objects: $wgLang, $wgContLang
76 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
80 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
81 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
84 * * only within ParserOptions
95 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
97 # Cleared with clearState():
98 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
99 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
100 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId; // ID to display in {{REVISIONID}} tags
123 $this->mTagHooks
= array();
124 $this->mFunctionHooks
= array();
125 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
126 $this->mFirstCall
= true;
130 * Do various kinds of initialisation on the first call of the parser
132 function firstCallInit() {
133 if ( !$this->mFirstCall
) {
137 wfProfileIn( __METHOD__
);
138 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
140 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
142 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
143 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
144 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
166 if ( $wgAllowDisplayTitle ) {
167 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
169 if ( $wgAllowSlowParserFunctions ) {
170 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
173 $this->initialiseVariables();
175 $this->mFirstCall
= false;
176 wfProfileOut( __METHOD__
);
184 function clearState() {
185 wfProfileIn( __METHOD__
);
186 if ( $this->mFirstCall
) {
187 $this->firstCallInit();
189 $this->mOutput
= new ParserOutput
;
190 $this->mAutonumber
= 0;
191 $this->mLastSection
= '';
192 $this->mDTopen
= false;
193 $this->mIncludeCount
= array();
194 $this->mStripState
= array();
195 $this->mArgStack
= array();
196 $this->mInPre
= false;
197 $this->mInterwikiLinkHolders
= array(
201 $this->mLinkHolders
= array(
202 'namespaces' => array(),
204 'queries' => array(),
208 $this->mRevisionId
= null;
211 * Prefix for temporary replacement strings for the multipass parser.
212 * \x07 should never appear in input as it's disallowed in XML.
213 * Using it at the front also gives us a little extra robustness
214 * since it shouldn't match when butted up against identifier-like
217 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
219 # Clear these on every parse, bug 4549
220 $this->mTemplates
= array();
221 $this->mTemplatePath
= array();
223 $this->mShowToc
= true;
224 $this->mForceTocPosition
= false;
225 $this->mIncludeSizes
= array(
231 wfRunHooks( 'ParserClearState', array( &$this ) );
232 wfProfileOut( __METHOD__
);
235 function setOutputType( $ot ) {
236 $this->mOutputType
= $ot;
239 'html' => $ot == OT_HTML
,
240 'wiki' => $ot == OT_WIKI
,
241 'msg' => $ot == OT_MSG
,
242 'pre' => $ot == OT_PREPROCESS
,
247 * Accessor for mUniqPrefix.
251 function uniqPrefix() {
252 return $this->mUniqPrefix
;
256 * Convert wikitext to HTML
257 * Do not call this function recursively.
260 * @param string $text Text we want to parse
261 * @param Title &$title A title object
262 * @param array $options
263 * @param boolean $linestart
264 * @param boolean $clearState
265 * @param int $revid number to pass in {{REVISIONID}}
266 * @return ParserOutput a ParserOutput
268 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
270 * First pass--just handle <nowiki> sections, pass the rest off
271 * to internalParse() which does all the real work.
274 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
275 $fname = 'Parser::parse-' . wfGetCaller();
276 wfProfileIn( $fname );
282 $this->mOptions
= $options;
283 $this->mTitle
=& $title;
284 $oldRevisionId = $this->mRevisionId
;
285 if( $revid !== null ) {
286 $this->mRevisionId
= $revid;
288 $this->setOutputType( OT_HTML
);
290 //$text = $this->strip( $text, $this->mStripState );
291 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
292 $x =& $this->mStripState
;
294 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
295 $text = $this->strip( $text, $x );
296 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
298 $text = $this->internalParse( $text );
300 $text = $this->unstrip( $text, $this->mStripState
);
302 # Clean up special characters, only run once, next-to-last before doBlockLevels
304 # french spaces, last one Guillemet-left
305 # only if there is something before the space
306 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
307 # french spaces, Guillemet-right
308 '/(\\302\\253) /' => '\\1 ',
310 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
313 $text = $this->doBlockLevels( $text, $linestart );
315 $this->replaceLinkHolders( $text );
317 # the position of the parserConvert() call should not be changed. it
318 # assumes that the links are all replaced and the only thing left
319 # is the <nowiki> mark.
320 # Side-effects: this calls $this->mOutput->setTitleText()
321 $text = $wgContLang->parserConvert( $text, $this );
323 $text = $this->unstripNoWiki( $text, $this->mStripState
);
325 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
327 $text = Sanitizer
::normalizeCharReferences( $text );
329 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
330 $text = Parser
::tidy($text);
332 # attempt to sanitize at least some nesting problems
333 # (bug #2702 and quite a few others)
335 # ''Something [http://www.cool.com cool''] -->
336 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
337 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
338 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
339 # fix up an anchor inside another anchor, only
340 # at least for a single single nested link (bug 3695)
341 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
342 '\\1\\2</a>\\3</a>\\1\\4</a>',
343 # fix div inside inline elements- doBlockLevels won't wrap a line which
344 # contains a div, so fix it up here; replace
345 # div with escaped text
346 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
347 '\\1\\3<div\\5>\\6</div>\\8\\9',
348 # remove empty italic or bold tag pairs, some
349 # introduced by rules above
350 '/<([bi])><\/\\1>/' => '',
353 $text = preg_replace(
354 array_keys( $tidyregs ),
355 array_values( $tidyregs ),
359 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
361 # Information on include size limits, for the benefit of users who try to skirt them
362 if ( max( $this->mIncludeSizes
) > 1000 ) {
363 $max = $this->mOptions
->getMaxIncludeSize();
365 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
366 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
367 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
368 "Maximum: $max bytes\n" .
371 $this->mOutput
->setText( $text );
372 $this->mRevisionId
= $oldRevisionId;
373 wfProfileOut( $fname );
375 return $this->mOutput
;
379 * Recursive parser entry point that can be called from an extension tag
382 function recursiveTagParse( $text ) {
383 wfProfileIn( __METHOD__
);
384 $x =& $this->mStripState
;
385 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
386 $text = $this->strip( $text, $x );
387 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
388 $text = $this->internalParse( $text );
389 wfProfileOut( __METHOD__
);
394 * Expand templates and variables in the text, producing valid, static wikitext.
395 * Also removes comments.
397 function preprocess( $text, $title, $options ) {
398 wfProfileIn( __METHOD__
);
400 $this->setOutputType( OT_PREPROCESS
);
401 $this->mOptions
= $options;
402 $this->mTitle
= $title;
403 $x =& $this->mStripState
;
404 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
405 $text = $this->strip( $text, $x );
406 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
407 if ( $this->mOptions
->getRemoveComments() ) {
408 $text = Sanitizer
::removeHTMLcomments( $text );
410 $text = $this->replaceVariables( $text );
411 $text = $this->unstrip( $text, $x );
412 $text = $this->unstripNowiki( $text, $x );
413 wfProfileOut( __METHOD__
);
418 * Get a random string
423 function getRandomString() {
424 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
427 function &getTitle() { return $this->mTitle
; }
428 function getOptions() { return $this->mOptions
; }
430 function getFunctionLang() {
431 global $wgLang, $wgContLang;
432 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
436 * Replaces all occurrences of HTML-style comments and the given tags
437 * in the text with a random marker and returns teh next text. The output
438 * parameter $matches will be an associative array filled with data in
440 * 'UNIQ-xxxxx' => array(
443 * array( 'param' => 'x' ),
444 * '<element param="x">tag content</element>' ) )
446 * @param $elements list of element names. Comments are always extracted.
447 * @param $text Source text string.
448 * @param $uniq_prefix
453 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
458 $taglist = implode( '|', $elements );
459 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
461 while ( '' != $text ) {
462 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
464 if( count( $p ) < 5 ) {
467 if( count( $p ) > 5 ) {
481 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
482 $stripped .= $marker;
484 if ( $close === '/>' ) {
485 // Empty element tag, <tag />
490 if( $element == '!--' ) {
493 $end = "/(<\\/$element\\s*>)/i";
495 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
497 if( count( $q ) < 3 ) {
498 # No end tag -- let it run out to the end of the text.
507 $matches[$marker] = array( $element,
509 Sanitizer
::decodeTagAttributes( $attributes ),
510 "<$element$attributes$close$content$tail" );
516 * Strips and renders nowiki, pre, math, hiero
517 * If $render is set, performs necessary rendering operations on plugins
518 * Returns the text, and fills an array with data needed in unstrip()
519 * If the $state is already a valid strip state, it adds to the state
521 * @param bool $stripcomments when set, HTML comments <!-- like this -->
522 * will be stripped in addition to other tags. This is important
523 * for section editing, where these comments cause confusion when
524 * counting the sections in the wikisource
526 * @param array dontstrip contains tags which should not be stripped;
527 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
531 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
532 wfProfileIn( __METHOD__
);
533 $render = ($this->mOutputType
== OT_HTML
);
535 $uniq_prefix = $this->mUniqPrefix
;
536 $commentState = array();
538 $elements = array_merge(
539 array( 'nowiki', 'gallery' ),
540 array_keys( $this->mTagHooks
) );
543 $elements[] = 'html';
545 if( $this->mOptions
->getUseTeX() ) {
546 $elements[] = 'math';
549 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
550 foreach ( $elements AS $k => $v ) {
551 if ( !in_array ( $v , $dontstrip ) ) continue;
552 unset ( $elements[$k] );
556 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
558 foreach( $matches as $marker => $data ) {
559 list( $element, $content, $params, $tag ) = $data;
561 $tagName = strtolower( $element );
562 wfProfileIn( __METHOD__
."-render-$tagName" );
566 if( substr( $tag, -3 ) == '-->' ) {
569 // Unclosed comment in input.
570 // Close it so later stripping can remove it
579 // Shouldn't happen otherwise. :)
581 $output = wfEscapeHTMLTagsOnly( $content );
584 $output = MathRenderer
::renderMath( $content );
587 $output = $this->renderImageGallery( $content, $params );
590 if( isset( $this->mTagHooks
[$tagName] ) ) {
591 $output = call_user_func_array( $this->mTagHooks
[$tagName],
592 array( $content, $params, $this ) );
594 throw new MWException( "Invalid call hook $element" );
597 wfProfileOut( __METHOD__
."-render-$tagName" );
599 // Just stripping tags; keep the source
603 // Unstrip the output, because unstrip() is no longer recursive so
604 // it won't do it itself
605 $output = $this->unstrip( $output, $state );
607 if( !$stripcomments && $element == '!--' ) {
608 $commentState[$marker] = $output;
609 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
610 $state['nowiki'][$marker] = $output;
612 $state['general'][$marker] = $output;
616 # Unstrip comments unless explicitly told otherwise.
617 # (The comments are always stripped prior to this point, so as to
618 # not invoke any extension tags / parser hooks contained within
620 if ( !$stripcomments ) {
621 // Put them all back and forget them
622 $text = strtr( $text, $commentState );
625 wfProfileOut( __METHOD__
);
630 * Restores pre, math, and other extensions removed by strip()
632 * always call unstripNoWiki() after this one
635 function unstrip( $text, &$state ) {
636 if ( !isset( $state['general'] ) ) {
640 wfProfileIn( __METHOD__
);
641 # TODO: good candidate for FSS
642 $text = strtr( $text, $state['general'] );
643 wfProfileOut( __METHOD__
);
648 * Always call this after unstrip() to preserve the order
652 function unstripNoWiki( $text, &$state ) {
653 if ( !isset( $state['nowiki'] ) ) {
657 wfProfileIn( __METHOD__
);
658 # TODO: good candidate for FSS
659 $text = strtr( $text, $state['nowiki'] );
660 wfProfileOut( __METHOD__
);
666 * Add an item to the strip state
667 * Returns the unique tag which must be inserted into the stripped text
668 * The tag will be replaced with the original text in unstrip()
672 function insertStripItem( $text, &$state ) {
673 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
677 $state['general'][$rnd] = $text;
682 * Interface with html tidy, used if $wgUseTidy = true.
683 * If tidy isn't able to correct the markup, the original will be
684 * returned in all its glory with a warning comment appended.
686 * Either the external tidy program or the in-process tidy extension
687 * will be used depending on availability. Override the default
688 * $wgTidyInternal setting to disable the internal if it's not working.
690 * @param string $text Hideous HTML input
691 * @return string Corrected HTML output
695 function tidy( $text ) {
696 global $wgTidyInternal;
697 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
698 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
699 '<head><title>test</title></head><body>'.$text.'</body></html>';
700 if( $wgTidyInternal ) {
701 $correctedtext = Parser
::internalTidy( $wrappedtext );
703 $correctedtext = Parser
::externalTidy( $wrappedtext );
705 if( is_null( $correctedtext ) ) {
706 wfDebug( "Tidy error detected!\n" );
707 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
709 return $correctedtext;
713 * Spawn an external HTML tidy process and get corrected markup back from it.
718 function externalTidy( $text ) {
719 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
720 $fname = 'Parser::externalTidy';
721 wfProfileIn( $fname );
726 $descriptorspec = array(
727 0 => array('pipe', 'r'),
728 1 => array('pipe', 'w'),
729 2 => array('file', '/dev/null', 'a')
732 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
733 if (is_resource($process)) {
734 // Theoretically, this style of communication could cause a deadlock
735 // here. If the stdout buffer fills up, then writes to stdin could
736 // block. This doesn't appear to happen with tidy, because tidy only
737 // writes to stdout after it's finished reading from stdin. Search
738 // for tidyParseStdin and tidySaveStdout in console/tidy.c
739 fwrite($pipes[0], $text);
741 while (!feof($pipes[1])) {
742 $cleansource .= fgets($pipes[1], 1024);
745 proc_close($process);
748 wfProfileOut( $fname );
750 if( $cleansource == '' && $text != '') {
751 // Some kind of error happened, so we couldn't get the corrected text.
752 // Just give up; we'll use the source text and append a warning.
760 * Use the HTML tidy PECL extension to use the tidy library in-process,
761 * saving the overhead of spawning a new process. Currently written to
762 * the PHP 4.3.x version of the extension, may not work on PHP 5.
764 * 'pear install tidy' should be able to compile the extension module.
769 function internalTidy( $text ) {
771 $fname = 'Parser::internalTidy';
772 wfProfileIn( $fname );
774 tidy_load_config( $wgTidyConf );
775 tidy_set_encoding( 'utf8' );
776 tidy_parse_string( $text );
778 if( tidy_get_status() == 2 ) {
779 // 2 is magic number for fatal error
780 // http://www.php.net/manual/en/function.tidy-get-status.php
783 $cleansource = tidy_get_output();
785 wfProfileOut( $fname );
790 * parse the wiki syntax used to render tables
794 function doTableStuff ( $t ) {
795 $fname = 'Parser::doTableStuff';
796 wfProfileIn( $fname );
798 $t = explode ( "\n" , $t ) ;
799 $td = array () ; # Is currently a td tag open?
800 $ltd = array () ; # Was it TD or TH?
801 $tr = array () ; # Is currently a tr tag open?
802 $ltr = array () ; # tr attributes
803 $has_opened_tr = array(); # Did this table open a <tr> element?
804 $indent_level = 0; # indent level of the table
805 foreach ( $t AS $k => $x )
808 $fc = substr ( $x , 0 , 1 ) ;
809 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
810 $indent_level = strlen( $matches[1] );
812 $attributes = $this->unstripForHTML( $matches[2] );
814 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
815 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
816 array_push ( $td , false ) ;
817 array_push ( $ltd , '' ) ;
818 array_push ( $tr , false ) ;
819 array_push ( $ltr , '' ) ;
820 array_push ( $has_opened_tr, false );
822 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
823 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
824 $z = "</table>" . substr ( $x , 2);
825 $l = array_pop ( $ltd ) ;
826 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
827 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
828 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
830 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
832 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
833 $x = substr ( $x , 1 ) ;
834 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
836 $l = array_pop ( $ltd ) ;
837 array_pop ( $has_opened_tr );
838 array_push ( $has_opened_tr , true ) ;
839 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
840 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
843 array_push ( $tr , false ) ;
844 array_push ( $td , false ) ;
845 array_push ( $ltd , '' ) ;
846 $attributes = $this->unstripForHTML( $x );
847 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
849 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
851 if ( '|+' == substr ( $x , 0 , 2 ) ) {
853 $x = substr ( $x , 1 ) ;
855 $after = substr ( $x , 1 ) ;
856 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
858 // Split up multiple cells on the same line.
859 // FIXME: This can result in improper nesting of tags processed
860 // by earlier parser steps, but should avoid splitting up eg
861 // attribute values containing literal "||".
862 $after = wfExplodeMarkup( '||', $after );
866 # Loop through each table cell
867 foreach ( $after AS $theline )
872 $tra = array_pop ( $ltr ) ;
873 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
874 array_push ( $tr , true ) ;
875 array_push ( $ltr , '' ) ;
876 array_pop ( $has_opened_tr );
877 array_push ( $has_opened_tr , true ) ;
880 $l = array_pop ( $ltd ) ;
881 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
882 if ( $fc == '|' ) $l = 'td' ;
883 else if ( $fc == '!' ) $l = 'th' ;
884 else if ( $fc == '+' ) $l = 'caption' ;
886 array_push ( $ltd , $l ) ;
889 $y = explode ( '|' , $theline , 2 ) ;
890 # Note that a '|' inside an invalid link should not
891 # be mistaken as delimiting cell parameters
892 if ( strpos( $y[0], '[[' ) !== false ) {
893 $y = array ($theline);
895 if ( count ( $y ) == 1 )
896 $y = "{$z}<{$l}>{$y[0]}" ;
898 $attributes = $this->unstripForHTML( $y[0] );
899 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
902 array_push ( $td , true ) ;
907 # Closing open td, tr && table
908 while ( count ( $td ) > 0 )
910 $l = array_pop ( $ltd ) ;
911 if ( array_pop ( $td ) ) $t[] = '</td>' ;
912 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
913 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
917 $t = implode ( "\n" , $t ) ;
918 # special case: don't return empty table
919 if($t == "<table>\n<tr><td></td></tr>\n</table>")
921 wfProfileOut( $fname );
926 * Helper function for parse() that transforms wiki markup into
927 * HTML. Only called for $mOutputType == OT_HTML.
931 function internalParse( $text ) {
934 $fname = 'Parser::internalParse';
935 wfProfileIn( $fname );
937 # Hook to suspend the parser in this state
938 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
939 wfProfileOut( $fname );
943 # Remove <noinclude> tags and <includeonly> sections
944 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
945 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
946 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
948 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
950 $text = $this->replaceVariables( $text, $args );
952 // Tables need to come after variable replacement for things to work
953 // properly; putting them before other transformations should keep
954 // exciting things like link expansions from showing up in surprising
956 $text = $this->doTableStuff( $text );
958 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
960 $text = $this->stripToc( $text );
961 $this->stripNoGallery( $text );
962 $text = $this->doHeadings( $text );
963 if($this->mOptions
->getUseDynamicDates()) {
964 $df =& DateFormatter
::getInstance();
965 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
967 $text = $this->doAllQuotes( $text );
968 $text = $this->replaceInternalLinks( $text );
969 $text = $this->replaceExternalLinks( $text );
971 # replaceInternalLinks may sometimes leave behind
972 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
973 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
975 $text = $this->doMagicLinks( $text );
976 $text = $this->formatHeadings( $text, $isMain );
978 wfProfileOut( $fname );
983 * Replace special strings like "ISBN xxx" and "RFC xxx" with
984 * magic external links.
988 function &doMagicLinks( &$text ) {
989 wfProfileIn( __METHOD__
);
990 $text = preg_replace_callback(
992 <a.*?</a> | # Skip link text
993 <.*?> | # Skip stuff inside HTML elements
994 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
995 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
996 )!x', array( &$this, 'magicLinkCallback' ), $text );
997 wfProfileOut( __METHOD__
);
1001 function magicLinkCallback( $m ) {
1002 if ( substr( $m[0], 0, 1 ) == '<' ) {
1005 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1007 $num = strtr( $isbn, array(
1012 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
1013 $text = '<a href="' .
1014 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1015 "\" class=\"internal\">ISBN $isbn</a>";
1017 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1021 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1023 $urlmsg = 'pubmedurl';
1026 throw new MWException( __METHOD__
.': unrecognised match type "' .
1027 substr($m[0], 0, 20 ) . '"' );
1030 $url = wfMsg( $urlmsg, $id);
1031 $sk =& $this->mOptions
->getSkin();
1032 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1033 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1039 * Parse headers and return html
1043 function doHeadings( $text ) {
1044 $fname = 'Parser::doHeadings';
1045 wfProfileIn( $fname );
1046 for ( $i = 6; $i >= 1; --$i ) {
1047 $h = str_repeat( '=', $i );
1048 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1049 "<h{$i}>\\1</h{$i}>\\2", $text );
1051 wfProfileOut( $fname );
1056 * Replace single quotes with HTML markup
1058 * @return string the altered text
1060 function doAllQuotes( $text ) {
1061 $fname = 'Parser::doAllQuotes';
1062 wfProfileIn( $fname );
1064 $lines = explode( "\n", $text );
1065 foreach ( $lines as $line ) {
1066 $outtext .= $this->doQuotes ( $line ) . "\n";
1068 $outtext = substr($outtext, 0,-1);
1069 wfProfileOut( $fname );
1074 * Helper function for doAllQuotes()
1077 function doQuotes( $text ) {
1078 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1079 if ( count( $arr ) == 1 )
1083 # First, do some preliminary work. This may shift some apostrophes from
1084 # being mark-up to being text. It also counts the number of occurrences
1085 # of bold and italics mark-ups.
1089 foreach ( $arr as $r )
1091 if ( ( $i %
2 ) == 1 )
1093 # If there are ever four apostrophes, assume the first is supposed to
1094 # be text, and the remaining three constitute mark-up for bold text.
1095 if ( strlen( $arr[$i] ) == 4 )
1100 # If there are more than 5 apostrophes in a row, assume they're all
1101 # text except for the last 5.
1102 else if ( strlen( $arr[$i] ) > 5 )
1104 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1107 # Count the number of occurrences of bold and italics mark-ups.
1108 # We are not counting sequences of five apostrophes.
1109 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1110 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1111 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1116 # If there is an odd number of both bold and italics, it is likely
1117 # that one of the bold ones was meant to be an apostrophe followed
1118 # by italics. Which one we cannot know for certain, but it is more
1119 # likely to be one that has a single-letter word before it.
1120 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1123 $firstsingleletterword = -1;
1124 $firstmultiletterword = -1;
1126 foreach ( $arr as $r )
1128 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1130 $x1 = substr ($arr[$i-1], -1);
1131 $x2 = substr ($arr[$i-1], -2, 1);
1133 if ($firstspace == -1) $firstspace = $i;
1134 } else if ($x2 == ' ') {
1135 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1137 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1143 # If there is a single-letter word, use it!
1144 if ($firstsingleletterword > -1)
1146 $arr [ $firstsingleletterword ] = "''";
1147 $arr [ $firstsingleletterword-1 ] .= "'";
1149 # If not, but there's a multi-letter word, use that one.
1150 else if ($firstmultiletterword > -1)
1152 $arr [ $firstmultiletterword ] = "''";
1153 $arr [ $firstmultiletterword-1 ] .= "'";
1155 # ... otherwise use the first one that has neither.
1156 # (notice that it is possible for all three to be -1 if, for example,
1157 # there is only one pentuple-apostrophe in the line)
1158 else if ($firstspace > -1)
1160 $arr [ $firstspace ] = "''";
1161 $arr [ $firstspace-1 ] .= "'";
1165 # Now let's actually convert our apostrophic mush to HTML!
1170 foreach ($arr as $r)
1174 if ($state == 'both')
1181 if (strlen ($r) == 2)
1184 { $output .= '</i>'; $state = ''; }
1185 else if ($state == 'bi')
1186 { $output .= '</i>'; $state = 'b'; }
1187 else if ($state == 'ib')
1188 { $output .= '</b></i><b>'; $state = 'b'; }
1189 else if ($state == 'both')
1190 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1191 else # $state can be 'b' or ''
1192 { $output .= '<i>'; $state .= 'i'; }
1194 else if (strlen ($r) == 3)
1197 { $output .= '</b>'; $state = ''; }
1198 else if ($state == 'bi')
1199 { $output .= '</i></b><i>'; $state = 'i'; }
1200 else if ($state == 'ib')
1201 { $output .= '</b>'; $state = 'i'; }
1202 else if ($state == 'both')
1203 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1204 else # $state can be 'i' or ''
1205 { $output .= '<b>'; $state .= 'b'; }
1207 else if (strlen ($r) == 5)
1210 { $output .= '</b><i>'; $state = 'i'; }
1211 else if ($state == 'i')
1212 { $output .= '</i><b>'; $state = 'b'; }
1213 else if ($state == 'bi')
1214 { $output .= '</i></b>'; $state = ''; }
1215 else if ($state == 'ib')
1216 { $output .= '</b></i>'; $state = ''; }
1217 else if ($state == 'both')
1218 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1219 else # ($state == '')
1220 { $buffer = ''; $state = 'both'; }
1225 # Now close all remaining tags. Notice that the order is important.
1226 if ($state == 'b' ||
$state == 'ib')
1228 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1232 if ($state == 'both')
1233 $output .= '<b><i>'.$buffer.'</i></b>';
1239 * Replace external links
1241 * Note: this is all very hackish and the order of execution matters a lot.
1242 * Make sure to run maintenance/parserTests.php if you change this code.
1246 function replaceExternalLinks( $text ) {
1248 $fname = 'Parser::replaceExternalLinks';
1249 wfProfileIn( $fname );
1251 $sk =& $this->mOptions
->getSkin();
1253 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1255 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1258 while ( $i<count( $bits ) ) {
1260 $protocol = $bits[$i++
];
1261 $text = $bits[$i++
];
1262 $trail = $bits[$i++
];
1264 # The characters '<' and '>' (which were escaped by
1265 # removeHTMLtags()) should not be included in
1266 # URLs, per RFC 2396.
1267 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1268 $text = substr($url, $m2[0][1]) . ' ' . $text;
1269 $url = substr($url, 0, $m2[0][1]);
1272 # If the link text is an image URL, replace it with an <img> tag
1273 # This happened by accident in the original parser, but some people used it extensively
1274 $img = $this->maybeMakeExternalImage( $text );
1275 if ( $img !== false ) {
1281 # Set linktype for CSS - if URL==text, link is essentially free
1282 $linktype = ($text == $url) ?
'free' : 'text';
1284 # No link text, e.g. [http://domain.tld/some.link]
1285 if ( $text == '' ) {
1286 # Autonumber if allowed. See bug #5918
1287 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1288 $text = '[' . ++
$this->mAutonumber
. ']';
1289 $linktype = 'autonumber';
1291 # Otherwise just use the URL
1292 $text = htmlspecialchars( $url );
1296 # Have link text, e.g. [http://domain.tld/some.link text]s
1298 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1301 $text = $wgContLang->markNoConversion($text);
1303 $url = Sanitizer
::cleanUrl( $url );
1305 # Process the trail (i.e. everything after this link up until start of the next link),
1306 # replacing any non-bracketed links
1307 $trail = $this->replaceFreeExternalLinks( $trail );
1309 # Use the encoded URL
1310 # This means that users can paste URLs directly into the text
1311 # Funny characters like ö aren't valid in URLs anyway
1312 # This was changed in August 2004
1313 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1315 # Register link in the output object.
1316 # Replace unnecessary URL escape codes with the referenced character
1317 # This prevents spammers from hiding links from the filters
1318 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1319 $this->mOutput
->addExternalLink( $pasteurized );
1322 wfProfileOut( $fname );
1327 * Replace anything that looks like a URL with a link
1330 function replaceFreeExternalLinks( $text ) {
1332 $fname = 'Parser::replaceFreeExternalLinks';
1333 wfProfileIn( $fname );
1335 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1336 $s = array_shift( $bits );
1339 $sk =& $this->mOptions
->getSkin();
1341 while ( $i < count( $bits ) ){
1342 $protocol = $bits[$i++
];
1343 $remainder = $bits[$i++
];
1345 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1346 # Found some characters after the protocol that look promising
1347 $url = $protocol . $m[1];
1350 # special case: handle urls as url args:
1351 # http://www.example.com/foo?=http://www.example.com/bar
1352 if(strlen($trail) == 0 &&
1354 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1355 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1358 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1363 # The characters '<' and '>' (which were escaped by
1364 # removeHTMLtags()) should not be included in
1365 # URLs, per RFC 2396.
1366 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1367 $trail = substr($url, $m2[0][1]) . $trail;
1368 $url = substr($url, 0, $m2[0][1]);
1371 # Move trailing punctuation to $trail
1373 # If there is no left bracket, then consider right brackets fair game too
1374 if ( strpos( $url, '(' ) === false ) {
1378 $numSepChars = strspn( strrev( $url ), $sep );
1379 if ( $numSepChars ) {
1380 $trail = substr( $url, -$numSepChars ) . $trail;
1381 $url = substr( $url, 0, -$numSepChars );
1384 $url = Sanitizer
::cleanUrl( $url );
1386 # Is this an external image?
1387 $text = $this->maybeMakeExternalImage( $url );
1388 if ( $text === false ) {
1389 # Not an image, make a link
1390 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1391 # Register it in the output object...
1392 # Replace unnecessary URL escape codes with their equivalent characters
1393 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1394 $this->mOutput
->addExternalLink( $pasteurized );
1396 $s .= $text . $trail;
1398 $s .= $protocol . $remainder;
1401 wfProfileOut( $fname );
1406 * Replace unusual URL escape codes with their equivalent characters
1410 * @fixme This can merge genuinely required bits in the path or query string,
1411 * breaking legit URLs. A proper fix would treat the various parts of
1412 * the URL differently; as a workaround, just use the output for
1413 * statistical records, not for actual linking/output.
1415 static function replaceUnusualEscapes( $url ) {
1416 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1417 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1421 * Callback function used in replaceUnusualEscapes().
1422 * Replaces unusual URL escape codes with their equivalent character
1426 private static function replaceUnusualEscapesCallback( $matches ) {
1427 $char = urldecode( $matches[0] );
1428 $ord = ord( $char );
1429 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1430 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1431 // No, shouldn't be escaped
1434 // Yes, leave it escaped
1440 * make an image if it's allowed, either through the global
1441 * option or through the exception
1444 function maybeMakeExternalImage( $url ) {
1445 $sk =& $this->mOptions
->getSkin();
1446 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1447 $imagesexception = !empty($imagesfrom);
1449 if ( $this->mOptions
->getAllowExternalImages()
1450 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1451 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1453 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1460 * Process [[ ]] wikilinks
1464 function replaceInternalLinks( $s ) {
1466 static $fname = 'Parser::replaceInternalLinks' ;
1468 wfProfileIn( $fname );
1470 wfProfileIn( $fname.'-setup' );
1472 # the % is needed to support urlencoded titles as well
1473 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1475 $sk =& $this->mOptions
->getSkin();
1477 #split the entire text string on occurences of [[
1478 $a = explode( '[[', ' ' . $s );
1479 #get the first element (all text up to first [[), and remove the space we added
1480 $s = array_shift( $a );
1481 $s = substr( $s, 1 );
1483 # Match a link having the form [[namespace:link|alternate]]trail
1485 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1486 # Match cases where there is no "]]", which might still be images
1487 static $e1_img = FALSE;
1488 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1489 # Match the end of a line for a word that's not followed by whitespace,
1490 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1491 $e2 = wfMsgForContent( 'linkprefix' );
1493 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1495 if( is_null( $this->mTitle
) ) {
1496 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1498 $nottalk = !$this->mTitle
->isTalkPage();
1500 if ( $useLinkPrefixExtension ) {
1501 if ( preg_match( $e2, $s, $m ) ) {
1502 $first_prefix = $m[2];
1504 $first_prefix = false;
1510 $selflink = $this->mTitle
->getPrefixedText();
1511 $useSubpages = $this->areSubpagesAllowed();
1512 wfProfileOut( $fname.'-setup' );
1514 # Loop for each link
1515 for ($k = 0; isset( $a[$k] ); $k++
) {
1517 if ( $useLinkPrefixExtension ) {
1518 wfProfileIn( $fname.'-prefixhandling' );
1519 if ( preg_match( $e2, $s, $m ) ) {
1527 $prefix = $first_prefix;
1528 $first_prefix = false;
1530 wfProfileOut( $fname.'-prefixhandling' );
1533 $might_be_img = false;
1535 wfProfileIn( "$fname-e1" );
1536 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1538 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1539 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1540 # the real problem is with the $e1 regex
1543 # Still some problems for cases where the ] is meant to be outside punctuation,
1544 # and no image is in sight. See bug 2095.
1547 substr( $m[3], 0, 1 ) === ']' &&
1548 strpos($text, '[') !== false
1551 $text .= ']'; # so that replaceExternalLinks($text) works later
1552 $m[3] = substr( $m[3], 1 );
1554 # fix up urlencoded title texts
1555 if( strpos( $m[1], '%' ) !== false ) {
1556 # Should anchors '#' also be rejected?
1557 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1560 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1561 $might_be_img = true;
1563 if ( strpos( $m[1], '%' ) !== false ) {
1564 $m[1] = urldecode($m[1]);
1567 } else { # Invalid form; output directly
1568 $s .= $prefix . '[[' . $line ;
1569 wfProfileOut( "$fname-e1" );
1572 wfProfileOut( "$fname-e1" );
1573 wfProfileIn( "$fname-misc" );
1575 # Don't allow internal links to pages containing
1576 # PROTO: where PROTO is a valid URL protocol; these
1577 # should be external links.
1578 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1579 $s .= $prefix . '[[' . $line ;
1583 # Make subpage if necessary
1584 if( $useSubpages ) {
1585 $link = $this->maybeDoSubpageLink( $m[1], $text );
1590 $noforce = (substr($m[1], 0, 1) != ':');
1592 # Strip off leading ':'
1593 $link = substr($link, 1);
1596 wfProfileOut( "$fname-misc" );
1597 wfProfileIn( "$fname-title" );
1598 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1600 $s .= $prefix . '[[' . $line;
1601 wfProfileOut( "$fname-title" );
1605 $ns = $nt->getNamespace();
1606 $iw = $nt->getInterWiki();
1607 wfProfileOut( "$fname-title" );
1609 if ($might_be_img) { # if this is actually an invalid link
1610 wfProfileIn( "$fname-might_be_img" );
1611 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1613 while (isset ($a[$k+
1]) ) {
1614 #look at the next 'line' to see if we can close it there
1615 $spliced = array_splice( $a, $k +
1, 1 );
1616 $next_line = array_shift( $spliced );
1617 $m = explode( ']]', $next_line, 3 );
1618 if ( count( $m ) == 3 ) {
1619 # the first ]] closes the inner link, the second the image
1621 $text .= "[[{$m[0]}]]{$m[1]}";
1624 } elseif ( count( $m ) == 2 ) {
1625 #if there's exactly one ]] that's fine, we'll keep looking
1626 $text .= "[[{$m[0]}]]{$m[1]}";
1628 #if $next_line is invalid too, we need look no further
1629 $text .= '[[' . $next_line;
1634 # we couldn't find the end of this imageLink, so output it raw
1635 #but don't ignore what might be perfectly normal links in the text we've examined
1636 $text = $this->replaceInternalLinks($text);
1637 $s .= "{$prefix}[[$link|$text";
1638 # note: no $trail, because without an end, there *is* no trail
1639 wfProfileOut( "$fname-might_be_img" );
1642 } else { #it's not an image, so output it raw
1643 $s .= "{$prefix}[[$link|$text";
1644 # note: no $trail, because without an end, there *is* no trail
1645 wfProfileOut( "$fname-might_be_img" );
1648 wfProfileOut( "$fname-might_be_img" );
1651 $wasblank = ( '' == $text );
1652 if( $wasblank ) $text = $link;
1654 # Link not escaped by : , create the various objects
1658 wfProfileIn( "$fname-interwiki" );
1659 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1660 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1661 $s = rtrim($s . "\n");
1662 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1663 wfProfileOut( "$fname-interwiki" );
1666 wfProfileOut( "$fname-interwiki" );
1668 if ( $ns == NS_IMAGE
) {
1669 wfProfileIn( "$fname-image" );
1670 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1671 # recursively parse links inside the image caption
1672 # actually, this will parse them in any other parameters, too,
1673 # but it might be hard to fix that, and it doesn't matter ATM
1674 $text = $this->replaceExternalLinks($text);
1675 $text = $this->replaceInternalLinks($text);
1677 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1678 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1679 $this->mOutput
->addImage( $nt->getDBkey() );
1681 wfProfileOut( "$fname-image" );
1684 # We still need to record the image's presence on the page
1685 $this->mOutput
->addImage( $nt->getDBkey() );
1687 wfProfileOut( "$fname-image" );
1691 if ( $ns == NS_CATEGORY
) {
1692 wfProfileIn( "$fname-category" );
1693 $s = rtrim($s . "\n"); # bug 87
1696 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1697 $sortkey = $this->mTitle
->getText();
1699 $sortkey = $this->mTitle
->getPrefixedText();
1704 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1705 $sortkey = str_replace( "\n", '', $sortkey );
1706 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1707 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1710 * Strip the whitespace Category links produce, see bug 87
1711 * @todo We might want to use trim($tmp, "\n") here.
1713 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1715 wfProfileOut( "$fname-category" );
1720 if( ( $nt->getPrefixedText() === $selflink ) &&
1721 ( $nt->getFragment() === '' ) ) {
1722 # Self-links are handled specially; generally de-link and change to bold.
1723 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1727 # Special and Media are pseudo-namespaces; no pages actually exist in them
1728 if( $ns == NS_MEDIA
) {
1729 $link = $sk->makeMediaLinkObj( $nt, $text );
1730 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1731 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1732 $this->mOutput
->addImage( $nt->getDBkey() );
1734 } elseif( $ns == NS_SPECIAL
) {
1735 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1737 } elseif( $ns == NS_IMAGE
) {
1738 $img = new Image( $nt );
1739 if( $img->exists() ) {
1740 // Force a blue link if the file exists; may be a remote
1741 // upload on the shared repository, and we want to see its
1742 // auto-generated page.
1743 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1744 $this->mOutput
->addLink( $nt );
1748 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1750 wfProfileOut( $fname );
1755 * Make a link placeholder. The text returned can be later resolved to a real link with
1756 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1757 * parsing of interwiki links, and secondly to allow all existence checks and
1758 * article length checks (for stub links) to be bundled into a single query.
1761 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1762 wfProfileIn( __METHOD__
);
1763 if ( ! is_object($nt) ) {
1765 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1767 # Separate the link trail from the rest of the link
1768 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1770 if ( $nt->isExternal() ) {
1771 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1772 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1773 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1775 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1776 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1777 $this->mLinkHolders
['queries'][] = $query;
1778 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1779 $this->mLinkHolders
['titles'][] = $nt;
1781 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1784 wfProfileOut( __METHOD__
);
1789 * Render a forced-blue link inline; protect against double expansion of
1790 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1791 * Since this little disaster has to split off the trail text to avoid
1792 * breaking URLs in the following text without breaking trails on the
1793 * wiki links, it's been made into a horrible function.
1796 * @param string $text
1797 * @param string $query
1798 * @param string $trail
1799 * @param string $prefix
1800 * @return string HTML-wikitext mix oh yuck
1802 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1803 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1804 $sk =& $this->mOptions
->getSkin();
1805 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1806 return $this->armorLinks( $link ) . $trail;
1810 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1811 * going to go through further parsing steps before inline URL expansion.
1813 * In particular this is important when using action=render, which causes
1814 * full URLs to be included.
1816 * Oh man I hate our multi-layer parser!
1818 * @param string more-or-less HTML
1819 * @return string less-or-more HTML with NOPARSE bits
1821 function armorLinks( $text ) {
1822 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1823 "{$this->mUniqPrefix}NOPARSE$1", $text );
1827 * Return true if subpage links should be expanded on this page.
1830 function areSubpagesAllowed() {
1831 # Some namespaces don't allow subpages
1832 global $wgNamespacesWithSubpages;
1833 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1837 * Handle link to subpage if necessary
1838 * @param string $target the source of the link
1839 * @param string &$text the link text, modified as necessary
1840 * @return string the full name of the link
1843 function maybeDoSubpageLink($target, &$text) {
1846 # :Foobar -- override special treatment of prefix (images, language links)
1847 # /Foobar -- convert to CurrentPage/Foobar
1848 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1849 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1850 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1852 $fname = 'Parser::maybeDoSubpageLink';
1853 wfProfileIn( $fname );
1854 $ret = $target; # default return value is no change
1857 $target = trim( $target );
1859 # Some namespaces don't allow subpages,
1860 # so only perform processing if subpages are allowed
1861 if( $this->areSubpagesAllowed() ) {
1862 # Look at the first character
1863 if( $target != '' && $target{0} == '/' ) {
1864 # / at end means we don't want the slash to be shown
1865 if( substr( $target, -1, 1 ) == '/' ) {
1866 $target = substr( $target, 1, -1 );
1869 $noslash = substr( $target, 1 );
1872 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1873 if( '' === $text ) {
1875 } # this might be changed for ugliness reasons
1877 # check for .. subpage backlinks
1879 $nodotdot = $target;
1880 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1882 $nodotdot = substr( $nodotdot, 3 );
1884 if($dotdotcount > 0) {
1885 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1886 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1887 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1888 # / at the end means don't show full path
1889 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1890 $nodotdot = substr( $nodotdot, 0, -1 );
1891 if( '' === $text ) {
1895 $nodotdot = trim( $nodotdot );
1896 if( $nodotdot != '' ) {
1897 $ret .= '/' . $nodotdot;
1904 wfProfileOut( $fname );
1909 * Used by doBlockLevels()
1912 /* private */ function closeParagraph() {
1914 if ( '' != $this->mLastSection
) {
1915 $result = '</' . $this->mLastSection
. ">\n";
1917 $this->mInPre
= false;
1918 $this->mLastSection
= '';
1921 # getCommon() returns the length of the longest common substring
1922 # of both arguments, starting at the beginning of both.
1924 /* private */ function getCommon( $st1, $st2 ) {
1925 $fl = strlen( $st1 );
1926 $shorter = strlen( $st2 );
1927 if ( $fl < $shorter ) { $shorter = $fl; }
1929 for ( $i = 0; $i < $shorter; ++
$i ) {
1930 if ( $st1{$i} != $st2{$i} ) { break; }
1934 # These next three functions open, continue, and close the list
1935 # element appropriate to the prefix character passed into them.
1937 /* private */ function openList( $char ) {
1938 $result = $this->closeParagraph();
1940 if ( '*' == $char ) { $result .= '<ul><li>'; }
1941 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1942 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1943 else if ( ';' == $char ) {
1944 $result .= '<dl><dt>';
1945 $this->mDTopen
= true;
1947 else { $result = '<!-- ERR 1 -->'; }
1952 /* private */ function nextItem( $char ) {
1953 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1954 else if ( ':' == $char ||
';' == $char ) {
1956 if ( $this->mDTopen
) { $close = '</dt>'; }
1957 if ( ';' == $char ) {
1958 $this->mDTopen
= true;
1959 return $close . '<dt>';
1961 $this->mDTopen
= false;
1962 return $close . '<dd>';
1965 return '<!-- ERR 2 -->';
1968 /* private */ function closeList( $char ) {
1969 if ( '*' == $char ) { $text = '</li></ul>'; }
1970 else if ( '#' == $char ) { $text = '</li></ol>'; }
1971 else if ( ':' == $char ) {
1972 if ( $this->mDTopen
) {
1973 $this->mDTopen
= false;
1974 $text = '</dt></dl>';
1976 $text = '</dd></dl>';
1979 else { return '<!-- ERR 3 -->'; }
1985 * Make lists from lines starting with ':', '*', '#', etc.
1988 * @return string the lists rendered as HTML
1990 function doBlockLevels( $text, $linestart ) {
1991 $fname = 'Parser::doBlockLevels';
1992 wfProfileIn( $fname );
1994 # Parsing through the text line by line. The main thing
1995 # happening here is handling of block-level elements p, pre,
1996 # and making lists from lines starting with * # : etc.
1998 $textLines = explode( "\n", $text );
2000 $lastPrefix = $output = '';
2001 $this->mDTopen
= $inBlockElem = false;
2003 $paragraphStack = false;
2005 if ( !$linestart ) {
2006 $output .= array_shift( $textLines );
2008 foreach ( $textLines as $oLine ) {
2009 $lastPrefixLength = strlen( $lastPrefix );
2010 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2011 $preOpenMatch = preg_match('/<pre/i', $oLine );
2012 if ( !$this->mInPre
) {
2013 # Multiple prefixes may abut each other for nested lists.
2014 $prefixLength = strspn( $oLine, '*#:;' );
2015 $pref = substr( $oLine, 0, $prefixLength );
2018 $pref2 = str_replace( ';', ':', $pref );
2019 $t = substr( $oLine, $prefixLength );
2020 $this->mInPre
= !empty($preOpenMatch);
2022 # Don't interpret any other prefixes in preformatted text
2024 $pref = $pref2 = '';
2029 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2030 # Same as the last item, so no need to deal with nesting or opening stuff
2031 $output .= $this->nextItem( substr( $pref, -1 ) );
2032 $paragraphStack = false;
2034 if ( substr( $pref, -1 ) == ';') {
2035 # The one nasty exception: definition lists work like this:
2036 # ; title : definition text
2037 # So we check for : in the remainder text to split up the
2038 # title and definition, without b0rking links.
2040 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2042 $output .= $term . $this->nextItem( ':' );
2045 } elseif( $prefixLength ||
$lastPrefixLength ) {
2046 # Either open or close a level...
2047 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2048 $paragraphStack = false;
2050 while( $commonPrefixLength < $lastPrefixLength ) {
2051 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2052 --$lastPrefixLength;
2054 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2055 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2057 while ( $prefixLength > $commonPrefixLength ) {
2058 $char = substr( $pref, $commonPrefixLength, 1 );
2059 $output .= $this->openList( $char );
2061 if ( ';' == $char ) {
2062 # FIXME: This is dupe of code above
2063 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2065 $output .= $term . $this->nextItem( ':' );
2068 ++
$commonPrefixLength;
2070 $lastPrefix = $pref2;
2072 if( 0 == $prefixLength ) {
2073 wfProfileIn( "$fname-paragraph" );
2074 # No prefix (not in list)--go to paragraph mode
2075 // XXX: use a stack for nestable elements like span, table and div
2076 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2077 $closematch = preg_match(
2078 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2079 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2080 if ( $openmatch or $closematch ) {
2081 $paragraphStack = false;
2082 #Â TODO bug 5718: paragraph closed
2083 $output .= $this->closeParagraph();
2084 if ( $preOpenMatch and !$preCloseMatch ) {
2085 $this->mInPre
= true;
2087 if ( $closematch ) {
2088 $inBlockElem = false;
2090 $inBlockElem = true;
2092 } else if ( !$inBlockElem && !$this->mInPre
) {
2093 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2095 if ($this->mLastSection
!= 'pre') {
2096 $paragraphStack = false;
2097 $output .= $this->closeParagraph().'<pre>';
2098 $this->mLastSection
= 'pre';
2100 $t = substr( $t, 1 );
2103 if ( '' == trim($t) ) {
2104 if ( $paragraphStack ) {
2105 $output .= $paragraphStack.'<br />';
2106 $paragraphStack = false;
2107 $this->mLastSection
= 'p';
2109 if ($this->mLastSection
!= 'p' ) {
2110 $output .= $this->closeParagraph();
2111 $this->mLastSection
= '';
2112 $paragraphStack = '<p>';
2114 $paragraphStack = '</p><p>';
2118 if ( $paragraphStack ) {
2119 $output .= $paragraphStack;
2120 $paragraphStack = false;
2121 $this->mLastSection
= 'p';
2122 } else if ($this->mLastSection
!= 'p') {
2123 $output .= $this->closeParagraph().'<p>';
2124 $this->mLastSection
= 'p';
2129 wfProfileOut( "$fname-paragraph" );
2131 // somewhere above we forget to get out of pre block (bug 785)
2132 if($preCloseMatch && $this->mInPre
) {
2133 $this->mInPre
= false;
2135 if ($paragraphStack === false) {
2139 while ( $prefixLength ) {
2140 $output .= $this->closeList( $pref2{$prefixLength-1} );
2143 if ( '' != $this->mLastSection
) {
2144 $output .= '</' . $this->mLastSection
. '>';
2145 $this->mLastSection
= '';
2148 wfProfileOut( $fname );
2153 * Split up a string on ':', ignoring any occurences inside tags
2154 * to prevent illegal overlapping.
2155 * @param string $str the string to split
2156 * @param string &$before set to everything before the ':'
2157 * @param string &$after set to everything after the ':'
2158 * return string the position of the ':', or false if none found
2160 function findColonNoLinks($str, &$before, &$after) {
2161 $fname = 'Parser::findColonNoLinks';
2162 wfProfileIn( $fname );
2164 $pos = strpos( $str, ':' );
2165 if( $pos === false ) {
2167 wfProfileOut( $fname );
2171 $lt = strpos( $str, '<' );
2172 if( $lt === false ||
$lt > $pos ) {
2173 // Easy; no tag nesting to worry about
2174 $before = substr( $str, 0, $pos );
2175 $after = substr( $str, $pos+
1 );
2176 wfProfileOut( $fname );
2180 // Ugly state machine to walk through avoiding tags.
2181 $state = MW_COLON_STATE_TEXT
;
2183 $len = strlen( $str );
2184 for( $i = 0; $i < $len; $i++
) {
2188 // (Using the number is a performance hack for common cases)
2189 case 0: // MW_COLON_STATE_TEXT:
2192 // Could be either a <start> tag or an </end> tag
2193 $state = MW_COLON_STATE_TAGSTART
;
2198 $before = substr( $str, 0, $i );
2199 $after = substr( $str, $i +
1 );
2200 wfProfileOut( $fname );
2203 // Embedded in a tag; don't break it.
2206 // Skip ahead looking for something interesting
2207 $colon = strpos( $str, ':', $i );
2208 if( $colon === false ) {
2209 // Nothing else interesting
2210 wfProfileOut( $fname );
2213 $lt = strpos( $str, '<', $i );
2214 if( $stack === 0 ) {
2215 if( $lt === false ||
$colon < $lt ) {
2217 $before = substr( $str, 0, $colon );
2218 $after = substr( $str, $colon +
1 );
2219 wfProfileOut( $fname );
2223 if( $lt === false ) {
2224 // Nothing else interesting to find; abort!
2225 // We're nested, but there's no close tags left. Abort!
2228 // Skip ahead to next tag start
2230 $state = MW_COLON_STATE_TAGSTART
;
2233 case 1: // MW_COLON_STATE_TAG:
2238 $state = MW_COLON_STATE_TEXT
;
2241 // Slash may be followed by >?
2242 $state = MW_COLON_STATE_TAGSLASH
;
2248 case 2: // MW_COLON_STATE_TAGSTART:
2251 $state = MW_COLON_STATE_CLOSETAG
;
2254 $state = MW_COLON_STATE_COMMENT
;
2257 // Illegal early close? This shouldn't happen D:
2258 $state = MW_COLON_STATE_TEXT
;
2261 $state = MW_COLON_STATE_TAG
;
2264 case 3: // MW_COLON_STATE_CLOSETAG:
2269 wfDebug( "Invalid input in $fname; too many close tags\n" );
2270 wfProfileOut( $fname );
2273 $state = MW_COLON_STATE_TEXT
;
2276 case MW_COLON_STATE_TAGSLASH
:
2278 // Yes, a self-closed tag <blah/>
2279 $state = MW_COLON_STATE_TEXT
;
2281 // Probably we're jumping the gun, and this is an attribute
2282 $state = MW_COLON_STATE_TAG
;
2285 case 5: // MW_COLON_STATE_COMMENT:
2287 $state = MW_COLON_STATE_COMMENTDASH
;
2290 case MW_COLON_STATE_COMMENTDASH
:
2292 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2294 $state = MW_COLON_STATE_COMMENT
;
2297 case MW_COLON_STATE_COMMENTDASHDASH
:
2299 $state = MW_COLON_STATE_TEXT
;
2301 $state = MW_COLON_STATE_COMMENT
;
2305 throw new MWException( "State machine error in $fname" );
2309 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2312 wfProfileOut( $fname );
2317 * Return value of a magic variable (like PAGENAME)
2321 function getVariableValue( $index ) {
2322 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2325 * Some of these require message or data lookups and can be
2326 * expensive to check many times.
2328 static $varCache = array();
2329 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2330 if ( isset( $varCache[$index] ) )
2331 return $varCache[$index];
2334 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2337 global $wgLocaltimezone;
2338 if ( isset( $wgLocaltimezone ) ) {
2339 $oldtz = getenv( 'TZ' );
2340 putenv( 'TZ='.$wgLocaltimezone );
2342 $localTimestamp = date( 'YmdHis', $ts );
2343 $localMonth = date( 'm', $ts );
2344 $localMonthName = date( 'n', $ts );
2345 $localDay = date( 'j', $ts );
2346 $localDay2 = date( 'd', $ts );
2347 $localDayOfWeek = date( 'w', $ts );
2348 $localWeek = date( 'W', $ts );
2349 $localYear = date( 'Y', $ts );
2350 $localHour = date( 'H', $ts );
2351 if ( isset( $wgLocaltimezone ) ) {
2352 putenv( 'TZ='.$oldtz );
2356 case 'currentmonth':
2357 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2358 case 'currentmonthname':
2359 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2360 case 'currentmonthnamegen':
2361 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2362 case 'currentmonthabbrev':
2363 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2365 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2367 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2369 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2370 case 'localmonthname':
2371 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2372 case 'localmonthnamegen':
2373 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2374 case 'localmonthabbrev':
2375 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2377 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2379 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2381 return $this->mTitle
->getText();
2383 return $this->mTitle
->getPartialURL();
2384 case 'fullpagename':
2385 return $this->mTitle
->getPrefixedText();
2386 case 'fullpagenamee':
2387 return $this->mTitle
->getPrefixedURL();
2389 return $this->mTitle
->getSubpageText();
2390 case 'subpagenamee':
2391 return $this->mTitle
->getSubpageUrlForm();
2392 case 'basepagename':
2393 return $this->mTitle
->getBaseText();
2394 case 'basepagenamee':
2395 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2396 case 'talkpagename':
2397 if( $this->mTitle
->canTalk() ) {
2398 $talkPage = $this->mTitle
->getTalkPage();
2399 return $talkPage->getPrefixedText();
2403 case 'talkpagenamee':
2404 if( $this->mTitle
->canTalk() ) {
2405 $talkPage = $this->mTitle
->getTalkPage();
2406 return $talkPage->getPrefixedUrl();
2410 case 'subjectpagename':
2411 $subjPage = $this->mTitle
->getSubjectPage();
2412 return $subjPage->getPrefixedText();
2413 case 'subjectpagenamee':
2414 $subjPage = $this->mTitle
->getSubjectPage();
2415 return $subjPage->getPrefixedUrl();
2417 return $this->mRevisionId
;
2419 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 ) );
2420 case 'revisionday2':
2421 return substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 );
2422 case 'revisionmonth':
2423 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 4, 2 ) );
2424 case 'revisionyear':
2425 return substr( wfRevisionTimestamp( $this->mRevisionId
), 0, 4 );
2426 case 'revisiontimestamp':
2427 return wfRevisionTimestamp( $this->mRevisionId
);
2429 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2431 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2433 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2435 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2436 case 'subjectspace':
2437 return $this->mTitle
->getSubjectNsText();
2438 case 'subjectspacee':
2439 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2440 case 'currentdayname':
2441 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2443 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2445 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2447 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2449 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2450 // int to remove the padding
2451 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2453 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2454 case 'localdayname':
2455 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2457 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2459 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2461 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2463 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2464 // int to remove the padding
2465 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2467 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2468 case 'numberofarticles':
2469 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2470 case 'numberoffiles':
2471 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2472 case 'numberofusers':
2473 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2474 case 'numberofpages':
2475 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2476 case 'numberofadmins':
2477 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2478 case 'currenttimestamp':
2479 return $varCache[$index] = wfTimestampNow();
2480 case 'localtimestamp':
2481 return $varCache[$index] = $localTimestamp;
2482 case 'currentversion':
2483 return $varCache[$index] = SpecialVersion
::getVersion();
2489 return $wgServerName;
2491 return $wgScriptPath;
2492 case 'directionmark':
2493 return $wgContLang->getDirMark();
2494 case 'contentlanguage':
2495 global $wgContLanguageCode;
2496 return $wgContLanguageCode;
2499 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2507 * initialise the magic variables (like CURRENTMONTHNAME)
2511 function initialiseVariables() {
2512 $fname = 'Parser::initialiseVariables';
2513 wfProfileIn( $fname );
2514 $variableIDs = MagicWord
::getVariableIDs();
2516 $this->mVariables
= array();
2517 foreach ( $variableIDs as $id ) {
2518 $mw =& MagicWord
::get( $id );
2519 $mw->addToArray( $this->mVariables
, $id );
2521 wfProfileOut( $fname );
2525 * parse any parentheses in format ((title|part|part))
2526 * and call callbacks to get a replacement text for any found piece
2528 * @param string $text The text to parse
2529 * @param array $callbacks rules in form:
2530 * '{' => array( # opening parentheses
2531 * 'end' => '}', # closing parentheses
2532 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2533 * 3 => callback # replacement callback to call if {{{..}}} is found
2536 * 'min' => 2, # Minimum parenthesis count in cb
2537 * 'max' => 3, # Maximum parenthesis count in cb
2540 function replace_callback ($text, $callbacks) {
2541 wfProfileIn( __METHOD__
);
2542 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2543 $lastOpeningBrace = -1; # last not closed parentheses
2545 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2548 while ( $i < strlen( $text ) ) {
2549 # Find next opening brace, closing brace or pipe
2550 if ( $lastOpeningBrace == -1 ) {
2551 $currentClosing = '';
2552 $search = $validOpeningBraces;
2554 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2555 $search = $validOpeningBraces . '|' . $currentClosing;
2558 $i +
= strcspn( $text, $search, $i );
2559 if ( $i < strlen( $text ) ) {
2560 if ( $text[$i] == '|' ) {
2562 } elseif ( $text[$i] == $currentClosing ) {
2564 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2566 $rule = $callbacks[$text[$i]];
2568 # Some versions of PHP have a strcspn which stops on null characters
2569 # Ignore and continue
2578 if ( $found == 'open' ) {
2579 # found opening brace, let's add it to parentheses stack
2580 $piece = array('brace' => $text[$i],
2581 'braceEnd' => $rule['end'],
2585 # count opening brace characters
2586 $piece['count'] = strspn( $text, $piece['brace'], $i );
2587 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2588 $i +
= $piece['count'];
2590 # we need to add to stack only if opening brace count is enough for one of the rules
2591 if ( $piece['count'] >= $rule['min'] ) {
2592 $lastOpeningBrace ++
;
2593 $openingBraceStack[$lastOpeningBrace] = $piece;
2595 } elseif ( $found == 'close' ) {
2596 # lets check if it is enough characters for closing brace
2597 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2598 $count = strspn( $text, $text[$i], $i, $maxCount );
2600 # check for maximum matching characters (if there are 5 closing
2601 # characters, we will probably need only 3 - depending on the rules)
2603 $matchingCallback = null;
2604 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2605 if ( $count > $cbType['max'] ) {
2606 # The specified maximum exists in the callback array, unless the caller
2608 $matchingCount = $cbType['max'];
2610 # Count is less than the maximum
2611 # Skip any gaps in the callback array to find the true largest match
2612 # Need to use array_key_exists not isset because the callback can be null
2613 $matchingCount = $count;
2614 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2619 if ($matchingCount <= 0) {
2623 $matchingCallback = $cbType['cb'][$matchingCount];
2625 # let's set a title or last part (if '|' was found)
2626 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2627 $openingBraceStack[$lastOpeningBrace]['title'] =
2628 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2629 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2631 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2632 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2633 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2636 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2637 $pieceEnd = $i +
$matchingCount;
2639 if( is_callable( $matchingCallback ) ) {
2641 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2642 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2643 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2644 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2646 # finally we can call a user callback and replace piece of text
2647 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2648 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2649 $i = $pieceStart +
strlen($replaceWith);
2651 # null value for callback means that parentheses should be parsed, but not replaced
2652 $i +
= $matchingCount;
2655 # reset last opening parentheses, but keep it in case there are unused characters
2656 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2657 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2658 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2661 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2662 $openingBraceStack[$lastOpeningBrace--] = null;
2664 if ($matchingCount < $piece['count']) {
2665 $piece['count'] -= $matchingCount;
2666 $piece['startAt'] -= $matchingCount;
2667 $piece['partStart'] = $piece['startAt'];
2668 # do we still qualify for any callback with remaining count?
2669 $currentCbList = $callbacks[$piece['brace']]['cb'];
2670 while ( $piece['count'] ) {
2671 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2672 $lastOpeningBrace++
;
2673 $openingBraceStack[$lastOpeningBrace] = $piece;
2679 } elseif ( $found == 'pipe' ) {
2680 # lets set a title if it is a first separator, or next part otherwise
2681 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2682 $openingBraceStack[$lastOpeningBrace]['title'] =
2683 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2684 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2685 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2687 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2688 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2689 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2691 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2695 wfProfileOut( __METHOD__
);
2700 * Replace magic variables, templates, and template arguments
2701 * with the appropriate text. Templates are substituted recursively,
2702 * taking care to avoid infinite loops.
2704 * Note that the substitution depends on value of $mOutputType:
2705 * OT_WIKI: only {{subst:}} templates
2706 * OT_MSG: only magic variables
2707 * OT_HTML: all templates and magic variables
2709 * @param string $tex The text to transform
2710 * @param array $args Key-value pairs representing template parameters to substitute
2711 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2714 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2715 # Prevent too big inclusions
2716 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2720 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2721 wfProfileIn( $fname );
2723 # This function is called recursively. To keep track of arguments we need a stack:
2724 array_push( $this->mArgStack
, $args );
2726 $braceCallbacks = array();
2728 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2730 if ( $this->mOutputType
!= OT_MSG
) {
2731 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2733 if ( $braceCallbacks ) {
2737 'cb' => $braceCallbacks,
2738 'min' => $argsOnly ?
3 : 2,
2739 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2743 'cb' => array(2=>null),
2748 $text = $this->replace_callback ($text, $callbacks);
2750 array_pop( $this->mArgStack
);
2752 wfProfileOut( $fname );
2757 * Replace magic variables
2760 function variableSubstitution( $matches ) {
2762 $fname = 'Parser::variableSubstitution';
2763 $varname = $wgContLang->lc($matches[1]);
2764 wfProfileIn( $fname );
2766 if ( $this->mOutputType
== OT_WIKI
) {
2767 # Do only magic variables prefixed by SUBST
2768 $mwSubst =& MagicWord
::get( 'subst' );
2769 if (!$mwSubst->matchStartAndRemove( $varname ))
2771 # Note that if we don't substitute the variable below,
2772 # we don't remove the {{subst:}} magic word, in case
2773 # it is a template rather than a magic variable.
2775 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2776 $id = $this->mVariables
[$varname];
2777 # Now check if we did really match, case sensitive or not
2778 $mw =& MagicWord
::get( $id );
2779 if ($mw->match($matches[1])) {
2780 $text = $this->getVariableValue( $id );
2781 $this->mOutput
->mContainsOldMagic
= true;
2783 $text = $matches[0];
2786 $text = $matches[0];
2788 wfProfileOut( $fname );
2792 # Split template arguments
2793 function getTemplateArgs( $argsString ) {
2794 if ( $argsString === '' ) {
2798 $args = explode( '|', substr( $argsString, 1 ) );
2800 # If any of the arguments contains a '[[' but no ']]', it needs to be
2801 # merged with the next arg because the '|' character between belongs
2802 # to the link syntax and not the template parameter syntax.
2803 $argc = count($args);
2805 for ( $i = 0; $i < $argc-1; $i++
) {
2806 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2807 $args[$i] .= '|'.$args[$i+
1];
2808 array_splice($args, $i+
1, 1);
2818 * Return the text of a template, after recursively
2819 * replacing any variables or templates within the template.
2821 * @param array $piece The parts of the template
2822 * $piece['text']: matched text
2823 * $piece['title']: the title, i.e. the part before the |
2824 * $piece['parts']: the parameter array
2825 * @return string the text of the template
2828 function braceSubstitution( $piece ) {
2829 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2830 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2831 wfProfileIn( $fname );
2832 wfProfileIn( __METHOD__
.'-setup' );
2835 $found = false; # $text has been filled
2836 $nowiki = false; # wiki markup in $text should be escaped
2837 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2838 $noargs = false; # Don't replace triple-brace arguments in $text
2839 $replaceHeadings = false; # Make the edit section links go to the template not the article
2840 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2841 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2843 # Title object, where $text came from
2849 # $part1 is the bit before the first |, and must contain only title characters
2850 # $args is a list of arguments, starting from index 0, not including $part1
2852 $titleText = $part1 = $piece['title'];
2853 # If the third subpattern matched anything, it will start with |
2855 if (null == $piece['parts']) {
2856 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2857 if ($replaceWith != $piece['text']) {
2858 $text = $replaceWith;
2865 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2866 $argc = count( $args );
2867 wfProfileOut( __METHOD__
.'-setup' );
2870 wfProfileIn( __METHOD__
.'-modifiers' );
2872 $mwSubst =& MagicWord
::get( 'subst' );
2873 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2874 # One of two possibilities is true:
2875 # 1) Found SUBST but not in the PST phase
2876 # 2) Didn't find SUBST and in the PST phase
2877 # In either case, return without further processing
2878 $text = $piece['text'];
2885 # MSG, MSGNW and RAW
2888 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2889 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2892 # Remove obsolete MSG:
2893 $mwMsg =& MagicWord
::get( 'msg' );
2894 $mwMsg->matchStartAndRemove( $part1 );
2898 $mwRaw =& MagicWord
::get( 'raw' );
2899 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2900 $forceRawInterwiki = true;
2903 wfProfileOut( __METHOD__
.'-modifiers' );
2907 wfProfileIn( __METHOD__
. '-pfunc' );
2909 $colonPos = strpos( $part1, ':' );
2910 if ( $colonPos !== false ) {
2911 # Case sensitive functions
2912 $function = substr( $part1, 0, $colonPos );
2913 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2914 $function = $this->mFunctionSynonyms
[1][$function];
2916 # Case insensitive functions
2917 $function = strtolower( $function );
2918 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2919 $function = $this->mFunctionSynonyms
[0][$function];
2925 $funcArgs = array_map( 'trim', $args );
2926 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2927 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2930 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2934 if ( is_array( $result ) ) {
2935 if ( isset( $result[0] ) ) {
2936 $text = $linestart . $result[0];
2937 unset( $result[0] );
2940 // Extract flags into the local scope
2941 // This allows callers to set flags such as nowiki, noparse, found, etc.
2944 $text = $linestart . $result;
2948 wfProfileOut( __METHOD__
. '-pfunc' );
2951 # Template table test
2953 # Did we encounter this template already? If yes, it is in the cache
2954 # and we need to check for loops.
2955 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2958 # Infinite loop test
2959 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2963 $text = $linestart .
2964 "[[$part1]]<!-- WARNING: template loop detected -->";
2965 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2967 # set $text to cached message.
2968 $text = $linestart . $this->mTemplates
[$piece['title']];
2972 # Load from database
2973 $lastPathLevel = $this->mTemplatePath
;
2975 wfProfileIn( __METHOD__
. '-loadtpl' );
2977 # declaring $subpage directly in the function call
2978 # does not work correctly with references and breaks
2979 # {{/subpage}}-style inclusions
2981 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2982 if ($subpage !== '') {
2983 $ns = $this->mTitle
->getNamespace();
2985 $title = Title
::newFromText( $part1, $ns );
2988 if ( !is_null( $title ) ) {
2989 $titleText = $title->getPrefixedText();
2990 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2991 # Check for language variants if the template is not found
2992 if($checkVariantLink && $title->getArticleID() == 0){
2993 $wgContLang->findVariantLink($part1, $title);
2996 if ( !$title->isExternal() ) {
2997 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2998 $text = SpecialPage
::capturePath( $title );
2999 if ( is_string( $text ) ) {
3004 $this->disableCache();
3007 $articleContent = $this->fetchTemplate( $title );
3008 if ( $articleContent !== false ) {
3010 $text = $articleContent;
3011 $replaceHeadings = true;
3015 # If the title is valid but undisplayable, make a link to it
3016 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3017 $text = "[[$titleText]]";
3020 } elseif ( $title->isTrans() ) {
3021 // Interwiki transclusion
3022 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3023 $text = $this->interwikiTransclude( $title, 'render' );
3027 $text = $this->interwikiTransclude( $title, 'raw' );
3028 $replaceHeadings = true;
3033 # Template cache array insertion
3034 # Use the original $piece['title'] not the mangled $part1, so that
3035 # modifiers such as RAW: produce separate cache entries
3038 // A special page; don't store it in the template cache.
3040 $this->mTemplates
[$piece['title']] = $text;
3042 $text = $linestart . $text;
3045 wfProfileOut( __METHOD__
. '-loadtpl' );
3048 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3049 # Error, oversize inclusion
3050 $text = $linestart .
3051 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3056 # Recursive parsing, escaping and link table handling
3057 # Only for HTML output
3058 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3059 $text = wfEscapeWikiText( $text );
3060 } elseif ( !$this->ot
['msg'] && $found ) {
3062 $assocArgs = array();
3064 # Clean up argument array
3065 $assocArgs = array();
3067 foreach( $args as $arg ) {
3068 $eqpos = strpos( $arg, '=' );
3069 if ( $eqpos === false ) {
3070 $assocArgs[$index++
] = $arg;
3072 $name = trim( substr( $arg, 0, $eqpos ) );
3073 $value = trim( substr( $arg, $eqpos+
1 ) );
3074 if ( $value === false ) {
3077 if ( $name !== false ) {
3078 $assocArgs[$name] = $value;
3083 # Add a new element to the templace recursion path
3084 $this->mTemplatePath
[$part1] = 1;
3088 # If there are any <onlyinclude> tags, only include them
3089 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3090 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3092 foreach ($m[1] as $piece)
3095 # Remove <noinclude> sections and <includeonly> tags
3096 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3097 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3099 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3100 # Strip <nowiki>, <pre>, etc.
3101 $text = $this->strip( $text, $this->mStripState
);
3102 if ( $this->ot
['html'] ) {
3103 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3104 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3105 $text = Sanitizer
::removeHTMLcomments( $text );
3108 $text = $this->replaceVariables( $text, $assocArgs );
3110 # If the template begins with a table or block-level
3111 # element, it should be treated as beginning a new line.
3112 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3113 $text = "\n" . $text;
3115 } elseif ( !$noargs ) {
3116 # $noparse and !$noargs
3117 # Just replace the arguments, not any double-brace items
3118 # This is used for rendered interwiki transclusion
3119 $text = $this->replaceVariables( $text, $assocArgs, true );
3122 # Prune lower levels off the recursion check path
3123 $this->mTemplatePath
= $lastPathLevel;
3125 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3126 # Error, oversize inclusion
3127 $text = $linestart .
3128 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3134 wfProfileOut( $fname );
3135 return $piece['text'];
3137 wfProfileIn( __METHOD__
. '-placeholders' );
3139 # Replace raw HTML by a placeholder
3140 # Add a blank line preceding, to prevent it from mucking up
3141 # immediately preceding headings
3142 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3144 # replace ==section headers==
3145 # XXX this needs to go away once we have a better parser.
3146 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3147 if( !is_null( $title ) )
3148 $encodedname = base64_encode($title->getPrefixedDBkey());
3150 $encodedname = base64_encode("");
3151 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3152 PREG_SPLIT_DELIM_CAPTURE
);
3155 for( $i = 0; $i < count($m); $i +
= 2 ) {
3157 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3159 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3163 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3164 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3165 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3171 wfProfileOut( __METHOD__
. '-placeholders' );
3174 # Prune lower levels off the recursion check path
3175 $this->mTemplatePath
= $lastPathLevel;
3178 wfProfileOut( $fname );
3179 return $piece['text'];
3181 wfProfileOut( $fname );
3187 * Fetch the unparsed text of a template and register a reference to it.
3189 function fetchTemplate( $title ) {
3191 // Loop to fetch the article, with up to 1 redirect
3192 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3193 $rev = Revision
::newFromTitle( $title );
3194 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3198 $text = $rev->getText();
3199 if ( $text === false ) {
3203 $title = Title
::newFromRedirect( $text );
3209 * Transclude an interwiki link.
3211 function interwikiTransclude( $title, $action ) {
3212 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3214 if (!$wgEnableScaryTranscluding)
3215 return wfMsg('scarytranscludedisabled');
3217 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3218 // But we'll handle it generally anyway
3219 if ( $title->getNamespace() ) {
3220 // Use the canonical namespace, which should work anywhere
3221 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3223 $articleName = $title->getDBkey();
3226 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3227 $url .= "?action=$action";
3228 if (strlen($url) > 255)
3229 return wfMsg('scarytranscludetoolong');
3230 return $this->fetchScaryTemplateMaybeFromCache($url);
3233 function fetchScaryTemplateMaybeFromCache($url) {
3234 global $wgTranscludeCacheExpiry;
3235 $dbr =& wfGetDB(DB_SLAVE
);
3236 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3237 array('tc_url' => $url));
3239 $time = $obj->tc_time
;
3240 $text = $obj->tc_contents
;
3241 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3246 $text = Http
::get($url);
3248 return wfMsg('scarytranscludefailed', $url);
3250 $dbw =& wfGetDB(DB_MASTER
);
3251 $dbw->replace('transcache', array('tc_url'), array(
3253 'tc_time' => time(),
3254 'tc_contents' => $text));
3260 * Triple brace replacement -- used for template arguments
3263 function argSubstitution( $matches ) {
3264 $arg = trim( $matches['title'] );
3265 $text = $matches['text'];
3266 $inputArgs = end( $this->mArgStack
);
3268 if ( array_key_exists( $arg, $inputArgs ) ) {
3269 $text = $inputArgs[$arg];
3270 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3271 null != $matches['parts'] && count($matches['parts']) > 0) {
3272 $text = $matches['parts'][0];
3274 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3275 $text = $matches['text'] .
3276 '<!-- WARNING: argument omitted, expansion size too large -->';
3283 * Increment an include size counter
3285 * @param string $type The type of expansion
3286 * @param integer $size The size of the text
3287 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3289 function incrementIncludeSize( $type, $size ) {
3290 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3293 $this->mIncludeSizes
[$type] +
= $size;
3299 * Detect __NOGALLERY__ magic word and set a placeholder
3301 function stripNoGallery( &$text ) {
3302 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3304 $mw = MagicWord
::get( 'nogallery' );
3305 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3309 * Detect __TOC__ magic word and set a placeholder
3311 function stripToc( $text ) {
3312 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3314 $mw = MagicWord
::get( 'notoc' );
3315 if( $mw->matchAndRemove( $text ) ) {
3316 $this->mShowToc
= false;
3319 $mw = MagicWord
::get( 'toc' );
3320 if( $mw->match( $text ) ) {
3321 $this->mShowToc
= true;
3322 $this->mForceTocPosition
= true;
3324 // Set a placeholder. At the end we'll fill it in with the TOC.
3325 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3327 // Only keep the first one.
3328 $text = $mw->replace( '', $text );
3334 * This function accomplishes several tasks:
3335 * 1) Auto-number headings if that option is enabled
3336 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3337 * 3) Add a Table of contents on the top for users who have enabled the option
3338 * 4) Auto-anchor headings
3340 * It loops through all headlines, collects the necessary data, then splits up the
3341 * string and re-inserts the newly formatted headlines.
3343 * @param string $text
3344 * @param boolean $isMain
3347 function formatHeadings( $text, $isMain=true ) {
3348 global $wgMaxTocLevel, $wgContLang;
3350 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3351 if( !$this->mTitle
->userCanEdit() ) {
3354 $showEditLink = $this->mOptions
->getEditSection();
3357 # Inhibit editsection links if requested in the page
3358 $esw =& MagicWord
::get( 'noeditsection' );
3359 if( $esw->matchAndRemove( $text ) ) {
3363 # Get all headlines for numbering them and adding funky stuff like [edit]
3364 # links - this is for later, but we need the number of headlines right now
3365 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3367 # if there are fewer than 4 headlines in the article, do not show TOC
3368 # unless it's been explicitly enabled.
3369 $enoughToc = $this->mShowToc
&&
3370 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3372 # Allow user to stipulate that a page should have a "new section"
3373 # link added via __NEWSECTIONLINK__
3374 $mw =& MagicWord
::get( 'newsectionlink' );
3375 if( $mw->matchAndRemove( $text ) )
3376 $this->mOutput
->setNewSection( true );
3378 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3379 # override above conditions and always show TOC above first header
3380 $mw =& MagicWord
::get( 'forcetoc' );
3381 if ($mw->matchAndRemove( $text ) ) {
3382 $this->mShowToc
= true;
3386 # Never ever show TOC if no headers
3387 if( $numMatches < 1 ) {
3391 # We need this to perform operations on the HTML
3392 $sk =& $this->mOptions
->getSkin();
3396 $sectionCount = 0; # headlineCount excluding template sections
3398 # Ugh .. the TOC should have neat indentation levels which can be
3399 # passed to the skin functions. These are determined here
3403 $sublevelCount = array();
3404 $levelCount = array();
3411 foreach( $matches[3] as $headline ) {
3413 $templatetitle = '';
3414 $templatesection = 0;
3417 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3419 $templatetitle = base64_decode($mat[1]);
3420 $templatesection = 1 +
(int)base64_decode($mat[2]);
3421 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3425 $prevlevel = $level;
3426 $prevtoclevel = $toclevel;
3428 $level = $matches[1][$headlineCount];
3430 if( $doNumberHeadings ||
$enoughToc ) {
3432 if ( $level > $prevlevel ) {
3433 # Increase TOC level
3435 $sublevelCount[$toclevel] = 0;
3436 if( $toclevel<$wgMaxTocLevel ) {
3437 $toc .= $sk->tocIndent();
3440 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3441 # Decrease TOC level, find level to jump to
3443 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3444 # Can only go down to level 1
3447 for ($i = $toclevel; $i > 0; $i--) {
3448 if ( $levelCount[$i] == $level ) {
3449 # Found last matching level
3453 elseif ( $levelCount[$i] < $level ) {
3454 # Found first matching level below current level
3460 if( $toclevel<$wgMaxTocLevel ) {
3461 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3465 # No change in level, end TOC line
3466 if( $toclevel<$wgMaxTocLevel ) {
3467 $toc .= $sk->tocLineEnd();
3471 $levelCount[$toclevel] = $level;
3473 # count number of headlines for each level
3474 @$sublevelCount[$toclevel]++
;
3476 for( $i = 1; $i <= $toclevel; $i++
) {
3477 if( !empty( $sublevelCount[$i] ) ) {
3481 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3487 # The canonized header is a version of the header text safe to use for links
3488 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3489 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3490 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3492 # Remove link placeholders by the link text.
3493 # <!--LINK number-->
3495 # link text with suffix
3496 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3497 "\$this->mLinkHolders['texts'][\$1]",
3498 $canonized_headline );
3499 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3500 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3501 $canonized_headline );
3504 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3505 $tocline = trim( $canonized_headline );
3506 # Save headline for section edit hint before it's escaped
3507 $headline_hint = trim( $canonized_headline );
3508 $canonized_headline = Sanitizer
::escapeId( $tocline );
3509 $refers[$headlineCount] = $canonized_headline;
3511 # count how many in assoc. array so we can track dupes in anchors
3512 @$refers[$canonized_headline]++
;
3513 $refcount[$headlineCount]=$refers[$canonized_headline];
3515 # Don't number the heading if it is the only one (looks silly)
3516 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3517 # the two are different if the line contains a link
3518 $headline=$numbering . ' ' . $headline;
3521 # Create the anchor for linking from the TOC to the section
3522 $anchor = $canonized_headline;
3523 if($refcount[$headlineCount] > 1 ) {
3524 $anchor .= '_' . $refcount[$headlineCount];
3526 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3527 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3529 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3530 if ( empty( $head[$headlineCount] ) ) {
3531 $head[$headlineCount] = '';
3534 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3536 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3539 # give headline the correct <h#> tag
3540 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3548 if( $toclevel<$wgMaxTocLevel ) {
3549 $toc .= $sk->tocUnindent( $toclevel - 1 );
3551 $toc = $sk->tocList( $toc );
3554 # split up and insert constructed headlines
3556 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3559 foreach( $blocks as $block ) {
3560 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3561 # This is the [edit] link that appears for the top block of text when
3562 # section editing is enabled
3564 # Disabled because it broke block formatting
3565 # For example, a bullet point in the top line
3566 # $full .= $sk->editSectionLink(0);
3569 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3570 # Top anchor now in skin
3574 if( !empty( $head[$i] ) ) {
3579 if( $this->mForceTocPosition
) {
3580 return str_replace( '<!--MWTOC-->', $toc, $full );
3587 * Transform wiki markup when saving a page by doing \r\n -> \n
3588 * conversion, substitting signatures, {{subst:}} templates, etc.
3590 * @param string $text the text to transform
3591 * @param Title &$title the Title object for the current article
3592 * @param User &$user the User object describing the current user
3593 * @param ParserOptions $options parsing options
3594 * @param bool $clearState whether to clear the parser state first
3595 * @return string the altered wiki markup
3598 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3599 $this->mOptions
= $options;
3600 $this->mTitle
=& $title;
3601 $this->setOutputType( OT_WIKI
);
3603 if ( $clearState ) {
3604 $this->clearState();
3607 $stripState = false;
3611 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3612 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3613 $text = $this->pstPass2( $text, $stripState, $user );
3614 $text = $this->unstrip( $text, $stripState );
3615 $text = $this->unstripNoWiki( $text, $stripState );
3620 * Pre-save transform helper function
3623 function pstPass2( $text, &$stripState, &$user ) {
3624 global $wgContLang, $wgLocaltimezone;
3626 /* Note: This is the timestamp saved as hardcoded wikitext to
3627 * the database, we use $wgContLang here in order to give
3628 * everyone the same signature and use the default one rather
3629 * than the one selected in each user's preferences.
3631 if ( isset( $wgLocaltimezone ) ) {
3632 $oldtz = getenv( 'TZ' );
3633 putenv( 'TZ='.$wgLocaltimezone );
3635 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3636 ' (' . date( 'T' ) . ')';
3637 if ( isset( $wgLocaltimezone ) ) {
3638 putenv( 'TZ='.$oldtz );
3641 # Variable replacement
3642 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3643 $text = $this->replaceVariables( $text );
3645 # Strip out <nowiki> etc. added via replaceVariables
3646 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3649 $sigText = $this->getUserSig( $user );
3650 $text = strtr( $text, array(
3652 '~~~~' => "$sigText $d",
3656 # Context links: [[|name]] and [[name (context)|]]
3658 global $wgLegalTitleChars;
3659 $tc = "[$wgLegalTitleChars]";
3660 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3662 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3663 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3664 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3666 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3667 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3668 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3670 $t = $this->mTitle
->getText();
3671 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3672 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3673 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3674 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3676 # if there's no context, don't bother duplicating the title
3677 $text = preg_replace( $p2, '[[\\1]]', $text );
3680 # Trim trailing whitespace
3681 # __END__ tag allows for trailing
3682 # whitespace to be deliberately included
3683 $text = rtrim( $text );
3684 $mw =& MagicWord
::get( 'end' );
3685 $mw->matchAndRemove( $text );
3691 * Fetch the user's signature text, if any, and normalize to
3692 * validated, ready-to-insert wikitext.
3698 function getUserSig( &$user ) {
3699 $username = $user->getName();
3700 $nickname = $user->getOption( 'nickname' );
3701 $nickname = $nickname === '' ?
$username : $nickname;
3703 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3704 # Sig. might contain markup; validate this
3705 if( $this->validateSig( $nickname ) !== false ) {
3706 # Validated; clean up (if needed) and return it
3707 return $this->cleanSig( $nickname, true );
3709 # Failed to validate; fall back to the default
3710 $nickname = $username;
3711 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3715 // Make sure nickname doesnt get a sig in a sig
3716 $nickname = $this->cleanSigInSig( $nickname );
3718 # If we're still here, make it a link to the user page
3719 $userpage = $user->getUserPage();
3720 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3724 * Check that the user's signature contains no bad XML
3726 * @param string $text
3727 * @return mixed An expanded string, or false if invalid.
3729 function validateSig( $text ) {
3730 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3734 * Clean up signature text
3736 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3737 * 2) Substitute all transclusions
3739 * @param string $text
3740 * @param $parsing Whether we're cleaning (preferences save) or parsing
3741 * @return string Signature text
3743 function cleanSig( $text, $parsing = false ) {
3745 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3747 $substWord = MagicWord
::get( 'subst' );
3748 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3749 $substText = '{{' . $substWord->getSynonym( 0 );
3751 $text = preg_replace( $substRegex, $substText, $text );
3752 $text = $this->cleanSigInSig( $text );
3753 $text = $this->replaceVariables( $text );
3755 $this->clearState();
3760 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3761 * @param string $text
3762 * @return string Signature text with /~{3,5}/ removed
3764 function cleanSigInSig( $text ) {
3765 $text = preg_replace( '/~{3,5}/', '', $text );
3770 * Set up some variables which are usually set up in parse()
3771 * so that an external function can call some class members with confidence
3774 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3775 $this->mTitle
=& $title;
3776 $this->mOptions
= $options;
3777 $this->setOutputType( $outputType );
3778 if ( $clearState ) {
3779 $this->clearState();
3784 * Transform a MediaWiki message by replacing magic variables.
3786 * @param string $text the text to transform
3787 * @param ParserOptions $options options
3788 * @return string the text with variables substituted
3791 function transformMsg( $text, $options ) {
3793 static $executing = false;
3795 $fname = "Parser::transformMsg";
3797 # Guard against infinite recursion
3803 wfProfileIn($fname);
3806 $this->mTitle
= $wgTitle;
3808 $this->mTitle
= Title
::newFromText('msg');
3810 $this->mOptions
= $options;
3811 $this->setOutputType( OT_MSG
);
3812 $this->clearState();
3813 $text = $this->replaceVariables( $text );
3816 wfProfileOut($fname);
3821 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3822 * The callback should have the following form:
3823 * function myParserHook( $text, $params, &$parser ) { ... }
3825 * Transform and return $text. Use $parser for any required context, e.g. use
3826 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3830 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3831 * @param mixed $callback The callback function (and object) to use for the tag
3833 * @return The old value of the mTagHooks array associated with the hook
3835 function setHook( $tag, $callback ) {
3836 $tag = strtolower( $tag );
3837 $oldVal = @$this->mTagHooks
[$tag];
3838 $this->mTagHooks
[$tag] = $callback;
3844 * Create a function, e.g. {{sum:1|2|3}}
3845 * The callback function should have the form:
3846 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3848 * The callback may either return the text result of the function, or an array with the text
3849 * in element 0, and a number of flags in the other elements. The names of the flags are
3850 * specified in the keys. Valid flags are:
3851 * found The text returned is valid, stop processing the template. This
3853 * nowiki Wiki markup in the return value should be escaped
3854 * noparse Unsafe HTML tags should not be stripped, etc.
3855 * noargs Don't replace triple-brace arguments in the return value
3856 * isHTML The returned text is HTML, armour it against wikitext transformation
3860 * @param string $id The magic word ID
3861 * @param mixed $callback The callback function (and object) to use
3862 * @param integer $flags a combination of the following flags:
3863 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3865 * @return The old callback function for this name, if any
3867 function setFunctionHook( $id, $callback, $flags = 0 ) {
3868 $oldVal = @$this->mFunctionHooks
[$id];
3869 $this->mFunctionHooks
[$id] = $callback;
3871 # Add to function cache
3872 $mw = MagicWord
::get( $id );
3874 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3876 $synonyms = $mw->getSynonyms();
3877 $sensitive = intval( $mw->isCaseSensitive() );
3879 foreach ( $synonyms as $syn ) {
3881 if ( !$sensitive ) {
3882 $syn = strtolower( $syn );
3885 if ( !( $flags & SFH_NO_HASH
) ) {
3888 # Remove trailing colon
3889 if ( substr( $syn, -1, 1 ) == ':' ) {
3890 $syn = substr( $syn, 0, -1 );
3892 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3898 * Get all registered function hook identifiers
3902 function getFunctionHooks() {
3903 return array_keys( $this->mFunctionHooks
);
3907 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3908 * Placeholders created in Skin::makeLinkObj()
3909 * Returns an array of links found, indexed by PDBK:
3913 * $options is a bit field, RLH_FOR_UPDATE to select for update
3915 function replaceLinkHolders( &$text, $options = 0 ) {
3917 global $wgOutputReplace;
3918 global $wgContLang, $wgLanguageCode;
3920 $fname = 'Parser::replaceLinkHolders';
3921 wfProfileIn( $fname );
3925 $sk =& $this->mOptions
->getSkin();
3926 $linkCache =& LinkCache
::singleton();
3928 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3929 wfProfileIn( $fname.'-check' );
3930 $dbr =& wfGetDB( DB_SLAVE
);
3931 $page = $dbr->tableName( 'page' );
3932 $threshold = $wgUser->getOption('stubthreshold');
3935 asort( $this->mLinkHolders
['namespaces'] );
3939 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3941 $title = $this->mLinkHolders
['titles'][$key];
3943 # Skip invalid entries.
3944 # Result will be ugly, but prevents crash.
3945 if ( is_null( $title ) ) {
3948 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3950 # Check if it's a static known link, e.g. interwiki
3951 if ( $title->isAlwaysKnown() ) {
3952 $colours[$pdbk] = 1;
3953 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3954 $colours[$pdbk] = 1;
3955 $this->mOutput
->addLink( $title, $id );
3956 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3957 $colours[$pdbk] = 0;
3959 # Not in the link cache, add it to the query
3960 if ( !isset( $current ) ) {
3962 $query = "SELECT page_id, page_namespace, page_title";
3963 if ( $threshold > 0 ) {
3964 $query .= ', page_len, page_is_redirect';
3966 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3967 } elseif ( $current != $ns ) {
3969 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3974 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3979 if ( $options & RLH_FOR_UPDATE
) {
3980 $query .= ' FOR UPDATE';
3983 $res = $dbr->query( $query, $fname );
3985 # Fetch data and form into an associative array
3986 # non-existent = broken
3989 while ( $s = $dbr->fetchObject($res) ) {
3990 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3991 $pdbk = $title->getPrefixedDBkey();
3992 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3993 $this->mOutput
->addLink( $title, $s->page_id
);
3995 if ( $threshold > 0 ) {
3996 $size = $s->page_len
;
3997 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3998 $colours[$pdbk] = 1;
4000 $colours[$pdbk] = 2;
4003 $colours[$pdbk] = 1;
4007 wfProfileOut( $fname.'-check' );
4009 # Do a second query for different language variants of links (if needed)
4010 if($wgContLang->hasVariants()){
4011 $linkBatch = new LinkBatch();
4012 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
4014 // Add variants of links to link batch
4015 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4016 $title = $this->mLinkHolders
['titles'][$key];
4017 if ( is_null( $title ) )
4020 $pdbk = $title->getPrefixedDBkey();
4022 // generate all variants of the link title text
4023 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4025 // if link was not found (in first query), add all variants to query
4026 if ( !isset($colours[$pdbk]) ){
4027 foreach($allTextVariants as $textVariant){
4028 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4029 if(is_null($variantTitle)) continue;
4030 $linkBatch->addObj( $variantTitle );
4031 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4037 if(!$linkBatch->isEmpty()){
4039 $titleClause = $linkBatch->constructSet('page', $dbr);
4041 $variantQuery = "SELECT page_id, page_namespace, page_title";
4042 if ( $threshold > 0 ) {
4043 $variantQuery .= ', page_len, page_is_redirect';
4046 $variantQuery .= " FROM $page WHERE $titleClause";
4047 if ( $options & RLH_FOR_UPDATE
) {
4048 $variantQuery .= ' FOR UPDATE';
4051 $varRes = $dbr->query( $variantQuery, $fname );
4053 // for each found variants, figure out link holders and replace
4054 while ( $s = $dbr->fetchObject($varRes) ) {
4056 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4057 $varPdbk = $variantTitle->getPrefixedDBkey();
4058 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4059 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4061 $holderKeys = $variantMap[$varPdbk];
4063 // loop over link holders
4064 foreach($holderKeys as $key){
4065 $title = $this->mLinkHolders
['titles'][$key];
4066 if ( is_null( $title ) ) continue;
4068 $pdbk = $title->getPrefixedDBkey();
4070 if(!isset($colours[$pdbk])){
4071 // found link in some of the variants, replace the link holder data
4072 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4073 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4075 // set pdbk and colour
4076 $pdbks[$key] = $varPdbk;
4077 if ( $threshold > 0 ) {
4078 $size = $s->page_len
;
4079 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4080 $colours[$varPdbk] = 1;
4082 $colours[$varPdbk] = 2;
4086 $colours[$varPdbk] = 1;
4094 # Construct search and replace arrays
4095 wfProfileIn( $fname.'-construct' );
4096 $wgOutputReplace = array();
4097 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4098 $pdbk = $pdbks[$key];
4099 $searchkey = "<!--LINK $key-->";
4100 $title = $this->mLinkHolders
['titles'][$key];
4101 if ( empty( $colours[$pdbk] ) ) {
4102 $linkCache->addBadLinkObj( $title );
4103 $colours[$pdbk] = 0;
4104 $this->mOutput
->addLink( $title, 0 );
4105 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4106 $this->mLinkHolders
['texts'][$key],
4107 $this->mLinkHolders
['queries'][$key] );
4108 } elseif ( $colours[$pdbk] == 1 ) {
4109 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4110 $this->mLinkHolders
['texts'][$key],
4111 $this->mLinkHolders
['queries'][$key] );
4112 } elseif ( $colours[$pdbk] == 2 ) {
4113 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4114 $this->mLinkHolders
['texts'][$key],
4115 $this->mLinkHolders
['queries'][$key] );
4118 wfProfileOut( $fname.'-construct' );
4121 wfProfileIn( $fname.'-replace' );
4123 $text = preg_replace_callback(
4124 '/(<!--LINK .*?-->)/',
4125 "wfOutputReplaceMatches",
4128 wfProfileOut( $fname.'-replace' );
4131 # Now process interwiki link holders
4132 # This is quite a bit simpler than internal links
4133 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4134 wfProfileIn( $fname.'-interwiki' );
4135 # Make interwiki link HTML
4136 $wgOutputReplace = array();
4137 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4138 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4139 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4142 $text = preg_replace_callback(
4143 '/<!--IWLINK (.*?)-->/',
4144 "wfOutputReplaceMatches",
4146 wfProfileOut( $fname.'-interwiki' );
4149 wfProfileOut( $fname );
4154 * Replace <!--LINK--> link placeholders with plain text of links
4155 * (not HTML-formatted).
4156 * @param string $text
4159 function replaceLinkHoldersText( $text ) {
4160 $fname = 'Parser::replaceLinkHoldersText';
4161 wfProfileIn( $fname );
4163 $text = preg_replace_callback(
4164 '/<!--(LINK|IWLINK) (.*?)-->/',
4165 array( &$this, 'replaceLinkHoldersTextCallback' ),
4168 wfProfileOut( $fname );
4173 * @param array $matches
4177 function replaceLinkHoldersTextCallback( $matches ) {
4178 $type = $matches[1];
4180 if( $type == 'LINK' ) {
4181 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4182 return $this->mLinkHolders
['texts'][$key];
4184 } elseif( $type == 'IWLINK' ) {
4185 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4186 return $this->mInterwikiLinkHolders
['texts'][$key];
4193 * Tag hook handler for 'pre'.
4195 function renderPreTag( $text, $attribs, $parser ) {
4196 // Backwards-compatibility hack
4197 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4199 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4200 return wfOpenElement( 'pre', $attribs ) .
4201 wfEscapeHTMLTagsOnly( $content ) .
4206 * Renders an image gallery from a text with one line per image.
4207 * text labels may be given by using |-style alternative text. E.g.
4208 * Image:one.jpg|The number "1"
4209 * Image:tree.jpg|A tree
4210 * given as text will return the HTML of a gallery with two images,
4211 * labeled 'The number "1"' and
4214 function renderImageGallery( $text, $params ) {
4215 $ig = new ImageGallery();
4216 $ig->setShowBytes( false );
4217 $ig->setShowFilename( false );
4219 $ig->useSkin( $this->mOptions
->getSkin() );
4221 if( isset( $params['caption'] ) )
4222 $ig->setCaption( $params['caption'] );
4224 $lines = explode( "\n", $text );
4225 foreach ( $lines as $line ) {
4226 # match lines like these:
4227 # Image:someimage.jpg|This is some image
4228 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4230 if ( count( $matches ) == 0 ) {
4233 $tp = Title
::newFromText( $matches[1] );
4235 if( is_null( $nt ) ) {
4236 # Bogus title. Ignore these so we don't bomb out later.
4239 if ( isset( $matches[3] ) ) {
4240 $label = $matches[3];
4245 $pout = $this->parse( $label,
4248 false, // Strip whitespace...?
4249 false // Don't clear state!
4251 $html = $pout->getText();
4253 $ig->add( new Image( $nt ), $html );
4255 # Only add real images (bug #5586)
4256 if ( $nt->getNamespace() == NS_IMAGE
) {
4257 $this->mOutput
->addImage( $nt->getDBkey() );
4260 return $ig->toHTML();
4264 * Parse image options text and use it to make an image
4266 function makeImage( &$nt, $options ) {
4267 global $wgUseImageResize, $wgDjvuRenderer;
4271 # Check if the options text is of the form "options|alt text"
4273 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4274 # * left no resizing, just left align. label is used for alt= only
4275 # * right same, but right aligned
4276 # * none same, but not aligned
4277 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4278 # * center center the image
4279 # * framed Keep original image size, no magnify-button.
4281 $part = explode( '|', $options);
4283 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4284 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4285 $mwLeft =& MagicWord
::get( 'img_left' );
4286 $mwRight =& MagicWord
::get( 'img_right' );
4287 $mwNone =& MagicWord
::get( 'img_none' );
4288 $mwWidth =& MagicWord
::get( 'img_width' );
4289 $mwCenter =& MagicWord
::get( 'img_center' );
4290 $mwFramed =& MagicWord
::get( 'img_framed' );
4291 $mwPage =& MagicWord
::get( 'img_page' );
4294 $width = $height = $framed = $thumb = false;
4296 $manual_thumb = '' ;
4298 foreach( $part as $key => $val ) {
4299 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4301 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4302 # use manually specified thumbnail
4304 $manual_thumb = $match;
4305 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4306 # remember to set an alignment, don't render immediately
4308 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4309 # remember to set an alignment, don't render immediately
4311 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4312 # remember to set an alignment, don't render immediately
4314 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4315 # remember to set an alignment, don't render immediately
4317 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4318 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4319 # Select a page in a multipage document
4321 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4322 wfDebug( "img_width match: $match\n" );
4323 # $match is the image width in pixels
4324 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4325 $width = intval( $m[1] );
4326 $height = intval( $m[2] );
4328 $width = intval($match);
4330 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4336 # Strip bad stuff out of the alt text
4337 $alt = $this->replaceLinkHoldersText( $caption );
4339 # make sure there are no placeholders in thumbnail attributes
4340 # that are later expanded to html- so expand them now and
4342 $alt = $this->unstrip($alt, $this->mStripState
);
4343 $alt = Sanitizer
::stripAllTags( $alt );
4345 # Linker does the rest
4346 $sk =& $this->mOptions
->getSkin();
4347 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4351 * Set a flag in the output object indicating that the content is dynamic and
4352 * shouldn't be cached.
4354 function disableCache() {
4355 wfDebug( "Parser output marked as uncacheable.\n" );
4356 $this->mOutput
->mCacheTime
= -1;
4360 * Callback from the Sanitizer for expanding items found in HTML attribute
4361 * values, so they can be safely tested and escaped.
4362 * @param string $text
4363 * @param array $args
4367 function attributeStripCallback( &$text, $args ) {
4368 $text = $this->replaceVariables( $text, $args );
4369 $text = $this->unstripForHTML( $text );
4373 function unstripForHTML( $text ) {
4374 $text = $this->unstrip( $text, $this->mStripState
);
4375 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4383 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4384 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4385 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4391 function getTags() { return array_keys( $this->mTagHooks
); }
4396 * Break wikitext input into sections, and either pull or replace
4397 * some particular section's text.
4399 * External callers should use the getSection and replaceSection methods.
4401 * @param $text Page wikitext
4402 * @param $section Numbered section. 0 pulls the text before the first
4403 * heading; other numbers will pull the given section
4404 * along with its lower-level subsections.
4405 * @param $mode One of "get" or "replace"
4406 * @param $newtext Replacement text for section data.
4407 * @return string for "get", the extracted section text.
4408 * for "replace", the whole page with the section replaced.
4410 private function extractSections( $text, $section, $mode, $newtext='' ) {
4411 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4412 # comments to be stripped as well)
4413 $striparray = array();
4415 $oldOutputType = $this->mOutputType
;
4416 $oldOptions = $this->mOptions
;
4417 $this->mOptions
= new ParserOptions();
4418 $this->setOutputType( OT_WIKI
);
4420 $striptext = $this->strip( $text, $striparray, true );
4422 $this->setOutputType( $oldOutputType );
4423 $this->mOptions
= $oldOptions;
4425 # now that we can be sure that no pseudo-sections are in the source,
4426 # split it up by section
4427 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4428 $comment = "(?:$uniq-!--.*?QINU)";
4433 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4435 (=+) # Should this be limited to 6?
4436 .+? # Section title...
4437 \\2 # Ending = count must match start
4444 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4451 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4452 (=+) # Should this be limited to 6?
4453 .+? # Section title...
4454 \\2 # Ending = count must match start
4455 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4464 PREG_SPLIT_DELIM_CAPTURE
);
4466 if( $mode == "get" ) {
4467 if( $section == 0 ) {
4468 // "Section 0" returns the content before any other section.
4473 } elseif( $mode == "replace" ) {
4474 if( $section == 0 ) {
4475 $rv = $newtext . "\n\n";
4484 for( $index = 1; $index < count( $secs ); ) {
4485 $headerLine = $secs[$index++
];
4486 if( $secs[$index] ) {
4488 $headerLevel = strlen( $secs[$index++
] );
4492 $headerLevel = intval( $secs[$index++
] );
4494 $content = $secs[$index++
];
4497 if( $mode == "get" ) {
4498 if( $count == $section ) {
4499 $rv = $headerLine . $content;
4500 $sectionLevel = $headerLevel;
4501 } elseif( $count > $section ) {
4502 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4503 $rv .= $headerLine . $content;
4505 // Broke out to a higher-level section
4509 } elseif( $mode == "replace" ) {
4510 if( $count < $section ) {
4511 $rv .= $headerLine . $content;
4512 } elseif( $count == $section ) {
4513 $rv .= $newtext . "\n\n";
4514 $sectionLevel = $headerLevel;
4515 } elseif( $count > $section ) {
4516 if( $headerLevel <= $sectionLevel ) {
4517 // Passed the section's sub-parts.
4521 $rv .= $headerLine . $content;
4526 # reinsert stripped tags
4527 $rv = $this->unstrip( $rv, $striparray );
4528 $rv = $this->unstripNoWiki( $rv, $striparray );
4534 * This function returns the text of a section, specified by a number ($section).
4535 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4536 * the first section before any such heading (section 0).
4538 * If a section contains subsections, these are also returned.
4540 * @param $text String: text to look in
4541 * @param $section Integer: section number
4542 * @return string text of the requested section
4544 function getSection( $text, $section ) {
4545 return $this->extractSections( $text, $section, "get" );
4548 function replaceSection( $oldtext, $section, $text ) {
4549 return $this->extractSections( $oldtext, $section, "replace", $text );
4556 * @package MediaWiki
4560 var $mText, # The output text
4561 $mLanguageLinks, # List of the full text of language links, in the order they appear
4562 $mCategories, # Map of category names to sort keys
4563 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4564 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4565 $mVersion, # Compatibility check
4566 $mTitleText, # title text of the chosen language variant
4567 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4568 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4569 $mImages, # DB keys of the images used, in the array key only
4570 $mExternalLinks, # External link URLs, in the key only
4571 $mHTMLtitle, # Display HTML title
4572 $mSubtitle, # Additional subtitle
4573 $mNewSection, # Show a new section link?
4574 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4576 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4577 $containsOldMagic = false, $titletext = '' )
4579 $this->mText
= $text;
4580 $this->mLanguageLinks
= $languageLinks;
4581 $this->mCategories
= $categoryLinks;
4582 $this->mContainsOldMagic
= $containsOldMagic;
4583 $this->mCacheTime
= '';
4584 $this->mVersion
= MW_PARSER_VERSION
;
4585 $this->mTitleText
= $titletext;
4586 $this->mLinks
= array();
4587 $this->mTemplates
= array();
4588 $this->mImages
= array();
4589 $this->mExternalLinks
= array();
4590 $this->mHTMLtitle
= "" ;
4591 $this->mSubtitle
= "" ;
4592 $this->mNewSection
= false;
4593 $this->mNoGallery
= false;
4596 function getText() { return $this->mText
; }
4597 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4598 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4599 function &getCategories() { return $this->mCategories
; }
4600 function getCacheTime() { return $this->mCacheTime
; }
4601 function getTitleText() { return $this->mTitleText
; }
4602 function &getLinks() { return $this->mLinks
; }
4603 function &getTemplates() { return $this->mTemplates
; }
4604 function &getImages() { return $this->mImages
; }
4605 function &getExternalLinks() { return $this->mExternalLinks
; }
4606 function getNoGallery() { return $this->mNoGallery
; }
4607 function getSubtitle() { return $this->mSubtitle
; }
4609 function containsOldMagic() { return $this->mContainsOldMagic
; }
4610 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4611 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4612 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4613 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4614 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4615 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4616 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4618 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4619 function addImage( $name ) { $this->mImages
[$name] = 1; }
4620 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4621 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4623 function setNewSection( $value ) {
4624 $this->mNewSection
= (bool)$value;
4626 function getNewSection() {
4627 return (bool)$this->mNewSection
;
4630 function addLink( $title, $id = null ) {
4631 $ns = $title->getNamespace();
4632 $dbk = $title->getDBkey();
4633 if ( !isset( $this->mLinks
[$ns] ) ) {
4634 $this->mLinks
[$ns] = array();
4636 if ( is_null( $id ) ) {
4637 $id = $title->getArticleID();
4639 $this->mLinks
[$ns][$dbk] = $id;
4642 function addTemplate( $title, $id ) {
4643 $ns = $title->getNamespace();
4644 $dbk = $title->getDBkey();
4645 if ( !isset( $this->mTemplates
[$ns] ) ) {
4646 $this->mTemplates
[$ns] = array();
4648 $this->mTemplates
[$ns][$dbk] = $id;
4652 * Return true if this cached output object predates the global or
4653 * per-article cache invalidation timestamps, or if it comes from
4654 * an incompatible older version.
4656 * @param string $touched the affected article's last touched timestamp
4660 function expired( $touched ) {
4661 global $wgCacheEpoch;
4662 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4663 $this->getCacheTime() < $touched ||
4664 $this->getCacheTime() <= $wgCacheEpoch ||
4665 !isset( $this->mVersion
) ||
4666 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4671 * Set options of the Parser
4673 * @package MediaWiki
4677 # All variables are private
4678 var $mUseTeX; # Use texvc to expand <math> tags
4679 var $mUseDynamicDates; # Use DateFormatter to format dates
4680 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4681 var $mAllowExternalImages; # Allow external images inline
4682 var $mAllowExternalImagesFrom; # If not, any exception?
4683 var $mSkin; # Reference to the preferred skin
4684 var $mDateFormat; # Date format index
4685 var $mEditSection; # Create "edit section" links
4686 var $mNumberHeadings; # Automatically number headings
4687 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4688 var $mTidy; # Ask for tidy cleanup
4689 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4690 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4691 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4693 var $mUser; # Stored user object, just used to initialise the skin
4695 function getUseTeX() { return $this->mUseTeX
; }
4696 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4697 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4698 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4699 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4700 function getEditSection() { return $this->mEditSection
; }
4701 function getNumberHeadings() { return $this->mNumberHeadings
; }
4702 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4703 function getTidy() { return $this->mTidy
; }
4704 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4705 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4706 function getRemoveComments() { return $this->mRemoveComments
; }
4708 function &getSkin() {
4709 if ( !isset( $this->mSkin
) ) {
4710 $this->mSkin
= $this->mUser
->getSkin();
4712 return $this->mSkin
;
4715 function getDateFormat() {
4716 if ( !isset( $this->mDateFormat
) ) {
4717 $this->mDateFormat
= $this->mUser
->getDatePreference();
4719 return $this->mDateFormat
;
4722 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4723 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4724 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4725 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4726 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4727 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4728 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4729 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4730 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4731 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4732 function setSkin( &$x ) { $this->mSkin
=& $x; }
4733 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4734 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4735 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4737 function ParserOptions( $user = null ) {
4738 $this->initialiseFromUser( $user );
4742 * Get parser options
4745 static function newFromUser( $user ) {
4746 return new ParserOptions( $user );
4749 /** Get user options */
4750 function initialiseFromUser( $userInput ) {
4751 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4752 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4753 $fname = 'ParserOptions::initialiseFromUser';
4754 wfProfileIn( $fname );
4755 if ( !$userInput ) {
4757 if ( isset( $wgUser ) ) {
4761 $user->setLoaded( true );
4764 $user =& $userInput;
4767 $this->mUser
= $user;
4769 $this->mUseTeX
= $wgUseTeX;
4770 $this->mUseDynamicDates
= $wgUseDynamicDates;
4771 $this->mInterwikiMagic
= $wgInterwikiMagic;
4772 $this->mAllowExternalImages
= $wgAllowExternalImages;
4773 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4774 $this->mSkin
= null; # Deferred
4775 $this->mDateFormat
= null; # Deferred
4776 $this->mEditSection
= true;
4777 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4778 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4779 $this->mTidy
= false;
4780 $this->mInterfaceMessage
= false;
4781 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4782 $this->mRemoveComments
= true;
4783 wfProfileOut( $fname );
4788 * Callback function used by Parser::replaceLinkHolders()
4789 * to substitute link placeholders.
4791 function &wfOutputReplaceMatches( $matches ) {
4792 global $wgOutputReplace;
4793 return $wgOutputReplace[$matches[1]];
4797 * Return the total number of articles
4799 function wfNumberOfArticles() {
4800 global $wgNumberOfArticles;
4803 return $wgNumberOfArticles;
4807 * Return the number of files
4809 function wfNumberOfFiles() {
4810 $fname = 'wfNumberOfFiles';
4812 wfProfileIn( $fname );
4813 $dbr =& wfGetDB( DB_SLAVE
);
4814 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4815 wfProfileOut( $fname );
4821 * Return the number of user accounts
4824 function wfNumberOfUsers() {
4825 wfProfileIn( 'wfNumberOfUsers' );
4826 $dbr =& wfGetDB( DB_SLAVE
);
4827 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4828 wfProfileOut( 'wfNumberOfUsers' );
4833 * Return the total number of pages
4836 function wfNumberOfPages() {
4837 wfProfileIn( 'wfNumberOfPages' );
4838 $dbr =& wfGetDB( DB_SLAVE
);
4839 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4840 wfProfileOut( 'wfNumberOfPages' );
4845 * Return the total number of admins
4849 function wfNumberOfAdmins() {
4850 static $admins = -1;
4851 wfProfileIn( 'wfNumberOfAdmins' );
4852 if( $admins == -1 ) {
4853 $dbr =& wfGetDB( DB_SLAVE
);
4854 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4856 wfProfileOut( 'wfNumberOfAdmins' );
4857 return (int)$admins;
4861 * Count the number of pages in a particular namespace
4863 * @param $ns Namespace
4866 function wfPagesInNs( $ns ) {
4867 static $pageCount = array();
4868 wfProfileIn( 'wfPagesInNs' );
4869 if( !isset( $pageCount[$ns] ) ) {
4870 $dbr =& wfGetDB( DB_SLAVE
);
4871 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4873 wfProfileOut( 'wfPagesInNs' );
4874 return (int)$pageCount[$ns];
4878 * Get various statistics from the database
4881 function wfLoadSiteStats() {
4882 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4883 $fname = 'wfLoadSiteStats';
4885 if ( -1 != $wgNumberOfArticles ) return;
4886 $dbr =& wfGetDB( DB_SLAVE
);
4887 $s = $dbr->selectRow( 'site_stats',
4888 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4889 array( 'ss_row_id' => 1 ), $fname
4892 if ( $s === false ) {
4895 $wgTotalViews = $s->ss_total_views
;
4896 $wgTotalEdits = $s->ss_total_edits
;
4897 $wgNumberOfArticles = $s->ss_good_articles
;
4902 * Get revision timestamp from the database considering timecorrection
4904 * @param $id Int: page revision id
4907 function wfRevisionTimestamp( $id ) {
4909 $fname = 'wfRevisionTimestamp';
4911 wfProfileIn( $fname );
4912 $dbr =& wfGetDB( DB_SLAVE
);
4913 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4914 array( 'rev_id' => $id ), __METHOD__
);
4915 $timestamp = $wgContLang->userAdjust( $timestamp );
4916 wfProfileOut( $fname );
4923 * Basically replacing " > and < with HTML entities ( ", >, <)
4925 * @param $in String: text that might contain HTML tags.
4926 * @return string Escaped string
4928 function wfEscapeHTMLTagsOnly( $in ) {
4930 array( '"', '>', '<' ),
4931 array( '"', '>', '<' ),