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 ) ;
810 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
811 $indent_level = strlen( $matches[1] );
813 $attributes = $this->unstripForHTML( $matches[2] );
815 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
816 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
817 array_push ( $td , false ) ;
818 array_push ( $ltd , '' ) ;
819 array_push ( $tr , false ) ;
820 array_push ( $ltr , '' ) ;
821 array_push ( $has_opened_tr, false );
823 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
824 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
825 $z = "</table>" . substr ( $x , 2);
826 $l = array_pop ( $ltd ) ;
827 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
828 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
829 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
831 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
833 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
834 $x = substr ( $x , 1 ) ;
835 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
837 $l = array_pop ( $ltd ) ;
838 array_pop ( $has_opened_tr );
839 array_push ( $has_opened_tr , true ) ;
840 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
841 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
844 array_push ( $tr , false ) ;
845 array_push ( $td , false ) ;
846 array_push ( $ltd , '' ) ;
847 $attributes = $this->unstripForHTML( $x );
848 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
850 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
852 if ( '|+' == substr ( $x , 0 , 2 ) ) {
854 $x = substr ( $x , 1 ) ;
856 $after = substr ( $x , 1 ) ;
857 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
859 // Split up multiple cells on the same line.
860 // FIXME: This can result in improper nesting of tags processed
861 // by earlier parser steps, but should avoid splitting up eg
862 // attribute values containing literal "||".
863 $after = wfExplodeMarkup( '||', $after );
867 # Loop through each table cell
868 foreach ( $after AS $theline )
873 $tra = array_pop ( $ltr ) ;
874 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
875 array_push ( $tr , true ) ;
876 array_push ( $ltr , '' ) ;
877 array_pop ( $has_opened_tr );
878 array_push ( $has_opened_tr , true ) ;
881 $l = array_pop ( $ltd ) ;
882 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
885 } else if ( $fc == '!' ) {
887 } else if ( $fc == '+' ) {
892 array_push ( $ltd , $l ) ;
895 $y = explode ( '|' , $theline , 2 ) ;
896 # Note that a '|' inside an invalid link should not
897 # be mistaken as delimiting cell parameters
898 if ( strpos( $y[0], '[[' ) !== false ) {
899 $y = array ($theline);
901 if ( count ( $y ) == 1 )
902 $y = "{$z}<{$l}>{$y[0]}" ;
904 $attributes = $this->unstripForHTML( $y[0] );
905 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
908 array_push ( $td , true ) ;
913 # Closing open td, tr && table
914 while ( count ( $td ) > 0 )
916 $l = array_pop ( $ltd ) ;
917 if ( array_pop ( $td ) ) $t[] = '</td>' ;
918 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
919 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
923 $t = implode ( "\n" , $t ) ;
924 # special case: don't return empty table
925 if($t == "<table>\n<tr><td></td></tr>\n</table>")
927 wfProfileOut( $fname );
932 * Helper function for parse() that transforms wiki markup into
933 * HTML. Only called for $mOutputType == OT_HTML.
937 function internalParse( $text ) {
940 $fname = 'Parser::internalParse';
941 wfProfileIn( $fname );
943 # Hook to suspend the parser in this state
944 $x =& $this->mStripState
; // FIXME: Please check that this initialization is correct.
945 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
946 wfProfileOut( $fname );
950 # Remove <noinclude> tags and <includeonly> sections
951 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
952 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
953 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
955 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
957 $text = $this->replaceVariables( $text, $args );
959 // Tables need to come after variable replacement for things to work
960 // properly; putting them before other transformations should keep
961 // exciting things like link expansions from showing up in surprising
963 $text = $this->doTableStuff( $text );
965 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
967 $text = $this->stripToc( $text );
968 $this->stripNoGallery( $text );
969 $text = $this->doHeadings( $text );
970 if($this->mOptions
->getUseDynamicDates()) {
971 $df =& DateFormatter
::getInstance();
972 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
974 $text = $this->doAllQuotes( $text );
975 $text = $this->replaceInternalLinks( $text );
976 $text = $this->replaceExternalLinks( $text );
978 # replaceInternalLinks may sometimes leave behind
979 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
980 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
982 $text = $this->doMagicLinks( $text );
983 $text = $this->formatHeadings( $text, $isMain );
985 wfProfileOut( $fname );
990 * Replace special strings like "ISBN xxx" and "RFC xxx" with
991 * magic external links.
995 function &doMagicLinks( &$text ) {
996 wfProfileIn( __METHOD__
);
997 $text = preg_replace_callback(
999 <a.*?</a> | # Skip link text
1000 <.*?> | # Skip stuff inside HTML elements
1001 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1002 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
1003 )!x', array( &$this, 'magicLinkCallback' ), $text );
1004 wfProfileOut( __METHOD__
);
1008 function magicLinkCallback( $m ) {
1009 if ( substr( $m[0], 0, 1 ) == '<' ) {
1012 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1014 $num = strtr( $isbn, array(
1019 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
1020 $text = '<a href="' .
1021 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1022 "\" class=\"internal\">ISBN $isbn</a>";
1024 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1028 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1030 $urlmsg = 'pubmedurl';
1033 throw new MWException( __METHOD__
.': unrecognised match type "' .
1034 substr($m[0], 0, 20 ) . '"' );
1037 $url = wfMsg( $urlmsg, $id);
1038 $sk =& $this->mOptions
->getSkin();
1039 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1040 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1046 * Parse headers and return html
1050 function doHeadings( $text ) {
1051 $fname = 'Parser::doHeadings';
1052 wfProfileIn( $fname );
1053 for ( $i = 6; $i >= 1; --$i ) {
1054 $h = str_repeat( '=', $i );
1055 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1056 "<h{$i}>\\1</h{$i}>\\2", $text );
1058 wfProfileOut( $fname );
1063 * Replace single quotes with HTML markup
1065 * @return string the altered text
1067 function doAllQuotes( $text ) {
1068 $fname = 'Parser::doAllQuotes';
1069 wfProfileIn( $fname );
1071 $lines = explode( "\n", $text );
1072 foreach ( $lines as $line ) {
1073 $outtext .= $this->doQuotes ( $line ) . "\n";
1075 $outtext = substr($outtext, 0,-1);
1076 wfProfileOut( $fname );
1081 * Helper function for doAllQuotes()
1084 function doQuotes( $text ) {
1085 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1086 if ( count( $arr ) == 1 )
1090 # First, do some preliminary work. This may shift some apostrophes from
1091 # being mark-up to being text. It also counts the number of occurrences
1092 # of bold and italics mark-ups.
1096 foreach ( $arr as $r )
1098 if ( ( $i %
2 ) == 1 )
1100 # If there are ever four apostrophes, assume the first is supposed to
1101 # be text, and the remaining three constitute mark-up for bold text.
1102 if ( strlen( $arr[$i] ) == 4 )
1107 # If there are more than 5 apostrophes in a row, assume they're all
1108 # text except for the last 5.
1109 else if ( strlen( $arr[$i] ) > 5 )
1111 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1114 # Count the number of occurrences of bold and italics mark-ups.
1115 # We are not counting sequences of five apostrophes.
1116 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1117 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1118 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1123 # If there is an odd number of both bold and italics, it is likely
1124 # that one of the bold ones was meant to be an apostrophe followed
1125 # by italics. Which one we cannot know for certain, but it is more
1126 # likely to be one that has a single-letter word before it.
1127 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1130 $firstsingleletterword = -1;
1131 $firstmultiletterword = -1;
1133 foreach ( $arr as $r )
1135 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1137 $x1 = substr ($arr[$i-1], -1);
1138 $x2 = substr ($arr[$i-1], -2, 1);
1140 if ($firstspace == -1) $firstspace = $i;
1141 } else if ($x2 == ' ') {
1142 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1144 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1150 # If there is a single-letter word, use it!
1151 if ($firstsingleletterword > -1)
1153 $arr [ $firstsingleletterword ] = "''";
1154 $arr [ $firstsingleletterword-1 ] .= "'";
1156 # If not, but there's a multi-letter word, use that one.
1157 else if ($firstmultiletterword > -1)
1159 $arr [ $firstmultiletterword ] = "''";
1160 $arr [ $firstmultiletterword-1 ] .= "'";
1162 # ... otherwise use the first one that has neither.
1163 # (notice that it is possible for all three to be -1 if, for example,
1164 # there is only one pentuple-apostrophe in the line)
1165 else if ($firstspace > -1)
1167 $arr [ $firstspace ] = "''";
1168 $arr [ $firstspace-1 ] .= "'";
1172 # Now let's actually convert our apostrophic mush to HTML!
1177 foreach ($arr as $r)
1181 if ($state == 'both')
1188 if (strlen ($r) == 2)
1191 { $output .= '</i>'; $state = ''; }
1192 else if ($state == 'bi')
1193 { $output .= '</i>'; $state = 'b'; }
1194 else if ($state == 'ib')
1195 { $output .= '</b></i><b>'; $state = 'b'; }
1196 else if ($state == 'both')
1197 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1198 else # $state can be 'b' or ''
1199 { $output .= '<i>'; $state .= 'i'; }
1201 else if (strlen ($r) == 3)
1204 { $output .= '</b>'; $state = ''; }
1205 else if ($state == 'bi')
1206 { $output .= '</i></b><i>'; $state = 'i'; }
1207 else if ($state == 'ib')
1208 { $output .= '</b>'; $state = 'i'; }
1209 else if ($state == 'both')
1210 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1211 else # $state can be 'i' or ''
1212 { $output .= '<b>'; $state .= 'b'; }
1214 else if (strlen ($r) == 5)
1217 { $output .= '</b><i>'; $state = 'i'; }
1218 else if ($state == 'i')
1219 { $output .= '</i><b>'; $state = 'b'; }
1220 else if ($state == 'bi')
1221 { $output .= '</i></b>'; $state = ''; }
1222 else if ($state == 'ib')
1223 { $output .= '</b></i>'; $state = ''; }
1224 else if ($state == 'both')
1225 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1226 else # ($state == '')
1227 { $buffer = ''; $state = 'both'; }
1232 # Now close all remaining tags. Notice that the order is important.
1233 if ($state == 'b' ||
$state == 'ib')
1235 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1239 if ($state == 'both')
1240 $output .= '<b><i>'.$buffer.'</i></b>';
1246 * Replace external links
1248 * Note: this is all very hackish and the order of execution matters a lot.
1249 * Make sure to run maintenance/parserTests.php if you change this code.
1253 function replaceExternalLinks( $text ) {
1255 $fname = 'Parser::replaceExternalLinks';
1256 wfProfileIn( $fname );
1258 $sk =& $this->mOptions
->getSkin();
1260 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1262 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1265 while ( $i<count( $bits ) ) {
1267 $protocol = $bits[$i++
];
1268 $text = $bits[$i++
];
1269 $trail = $bits[$i++
];
1271 # The characters '<' and '>' (which were escaped by
1272 # removeHTMLtags()) should not be included in
1273 # URLs, per RFC 2396.
1275 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1276 $text = substr($url, $m2[0][1]) . ' ' . $text;
1277 $url = substr($url, 0, $m2[0][1]);
1280 # If the link text is an image URL, replace it with an <img> tag
1281 # This happened by accident in the original parser, but some people used it extensively
1282 $img = $this->maybeMakeExternalImage( $text );
1283 if ( $img !== false ) {
1289 # Set linktype for CSS - if URL==text, link is essentially free
1290 $linktype = ($text == $url) ?
'free' : 'text';
1292 # No link text, e.g. [http://domain.tld/some.link]
1293 if ( $text == '' ) {
1294 # Autonumber if allowed. See bug #5918
1295 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1296 $text = '[' . ++
$this->mAutonumber
. ']';
1297 $linktype = 'autonumber';
1299 # Otherwise just use the URL
1300 $text = htmlspecialchars( $url );
1304 # Have link text, e.g. [http://domain.tld/some.link text]s
1306 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1309 $text = $wgContLang->markNoConversion($text);
1311 $url = Sanitizer
::cleanUrl( $url );
1313 # Process the trail (i.e. everything after this link up until start of the next link),
1314 # replacing any non-bracketed links
1315 $trail = $this->replaceFreeExternalLinks( $trail );
1317 # Use the encoded URL
1318 # This means that users can paste URLs directly into the text
1319 # Funny characters like ö aren't valid in URLs anyway
1320 # This was changed in August 2004
1321 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1323 # Register link in the output object.
1324 # Replace unnecessary URL escape codes with the referenced character
1325 # This prevents spammers from hiding links from the filters
1326 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1327 $this->mOutput
->addExternalLink( $pasteurized );
1330 wfProfileOut( $fname );
1335 * Replace anything that looks like a URL with a link
1338 function replaceFreeExternalLinks( $text ) {
1340 $fname = 'Parser::replaceFreeExternalLinks';
1341 wfProfileIn( $fname );
1343 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1344 $s = array_shift( $bits );
1347 $sk =& $this->mOptions
->getSkin();
1349 while ( $i < count( $bits ) ){
1350 $protocol = $bits[$i++
];
1351 $remainder = $bits[$i++
];
1354 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1355 # Found some characters after the protocol that look promising
1356 $url = $protocol . $m[1];
1359 # special case: handle urls as url args:
1360 # http://www.example.com/foo?=http://www.example.com/bar
1361 if(strlen($trail) == 0 &&
1363 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1364 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1367 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1372 # The characters '<' and '>' (which were escaped by
1373 # removeHTMLtags()) should not be included in
1374 # URLs, per RFC 2396.
1376 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1377 $trail = substr($url, $m2[0][1]) . $trail;
1378 $url = substr($url, 0, $m2[0][1]);
1381 # Move trailing punctuation to $trail
1383 # If there is no left bracket, then consider right brackets fair game too
1384 if ( strpos( $url, '(' ) === false ) {
1388 $numSepChars = strspn( strrev( $url ), $sep );
1389 if ( $numSepChars ) {
1390 $trail = substr( $url, -$numSepChars ) . $trail;
1391 $url = substr( $url, 0, -$numSepChars );
1394 $url = Sanitizer
::cleanUrl( $url );
1396 # Is this an external image?
1397 $text = $this->maybeMakeExternalImage( $url );
1398 if ( $text === false ) {
1399 # Not an image, make a link
1400 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1401 # Register it in the output object...
1402 # Replace unnecessary URL escape codes with their equivalent characters
1403 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1404 $this->mOutput
->addExternalLink( $pasteurized );
1406 $s .= $text . $trail;
1408 $s .= $protocol . $remainder;
1411 wfProfileOut( $fname );
1416 * Replace unusual URL escape codes with their equivalent characters
1420 * @fixme This can merge genuinely required bits in the path or query string,
1421 * breaking legit URLs. A proper fix would treat the various parts of
1422 * the URL differently; as a workaround, just use the output for
1423 * statistical records, not for actual linking/output.
1425 static function replaceUnusualEscapes( $url ) {
1426 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1427 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1431 * Callback function used in replaceUnusualEscapes().
1432 * Replaces unusual URL escape codes with their equivalent character
1436 private static function replaceUnusualEscapesCallback( $matches ) {
1437 $char = urldecode( $matches[0] );
1438 $ord = ord( $char );
1439 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1440 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1441 // No, shouldn't be escaped
1444 // Yes, leave it escaped
1450 * make an image if it's allowed, either through the global
1451 * option or through the exception
1454 function maybeMakeExternalImage( $url ) {
1455 $sk =& $this->mOptions
->getSkin();
1456 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1457 $imagesexception = !empty($imagesfrom);
1459 if ( $this->mOptions
->getAllowExternalImages()
1460 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1461 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1463 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1470 * Process [[ ]] wikilinks
1474 function replaceInternalLinks( $s ) {
1476 static $fname = 'Parser::replaceInternalLinks' ;
1478 wfProfileIn( $fname );
1480 wfProfileIn( $fname.'-setup' );
1482 # the % is needed to support urlencoded titles as well
1483 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1485 $sk =& $this->mOptions
->getSkin();
1487 #split the entire text string on occurences of [[
1488 $a = explode( '[[', ' ' . $s );
1489 #get the first element (all text up to first [[), and remove the space we added
1490 $s = array_shift( $a );
1491 $s = substr( $s, 1 );
1493 # Match a link having the form [[namespace:link|alternate]]trail
1495 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1496 # Match cases where there is no "]]", which might still be images
1497 static $e1_img = FALSE;
1498 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1499 # Match the end of a line for a word that's not followed by whitespace,
1500 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1501 $e2 = wfMsgForContent( 'linkprefix' );
1503 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1505 if( is_null( $this->mTitle
) ) {
1506 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1508 $nottalk = !$this->mTitle
->isTalkPage();
1510 if ( $useLinkPrefixExtension ) {
1512 if ( preg_match( $e2, $s, $m ) ) {
1513 $first_prefix = $m[2];
1515 $first_prefix = false;
1521 $selflink = $this->mTitle
->getPrefixedText();
1522 $useSubpages = $this->areSubpagesAllowed();
1523 wfProfileOut( $fname.'-setup' );
1525 # Loop for each link
1526 for ($k = 0; isset( $a[$k] ); $k++
) {
1528 if ( $useLinkPrefixExtension ) {
1529 wfProfileIn( $fname.'-prefixhandling' );
1530 if ( preg_match( $e2, $s, $m ) ) {
1538 $prefix = $first_prefix;
1539 $first_prefix = false;
1541 wfProfileOut( $fname.'-prefixhandling' );
1544 $might_be_img = false;
1546 wfProfileIn( "$fname-e1" );
1547 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1549 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1550 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1551 # the real problem is with the $e1 regex
1554 # Still some problems for cases where the ] is meant to be outside punctuation,
1555 # and no image is in sight. See bug 2095.
1558 substr( $m[3], 0, 1 ) === ']' &&
1559 strpos($text, '[') !== false
1562 $text .= ']'; # so that replaceExternalLinks($text) works later
1563 $m[3] = substr( $m[3], 1 );
1565 # fix up urlencoded title texts
1566 if( strpos( $m[1], '%' ) !== false ) {
1567 # Should anchors '#' also be rejected?
1568 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1571 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1572 $might_be_img = true;
1574 if ( strpos( $m[1], '%' ) !== false ) {
1575 $m[1] = urldecode($m[1]);
1578 } else { # Invalid form; output directly
1579 $s .= $prefix . '[[' . $line ;
1580 wfProfileOut( "$fname-e1" );
1583 wfProfileOut( "$fname-e1" );
1584 wfProfileIn( "$fname-misc" );
1586 # Don't allow internal links to pages containing
1587 # PROTO: where PROTO is a valid URL protocol; these
1588 # should be external links.
1589 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1590 $s .= $prefix . '[[' . $line ;
1594 # Make subpage if necessary
1595 if( $useSubpages ) {
1596 $link = $this->maybeDoSubpageLink( $m[1], $text );
1601 $noforce = (substr($m[1], 0, 1) != ':');
1603 # Strip off leading ':'
1604 $link = substr($link, 1);
1607 wfProfileOut( "$fname-misc" );
1608 wfProfileIn( "$fname-title" );
1609 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1611 $s .= $prefix . '[[' . $line;
1612 wfProfileOut( "$fname-title" );
1616 $ns = $nt->getNamespace();
1617 $iw = $nt->getInterWiki();
1618 wfProfileOut( "$fname-title" );
1620 if ($might_be_img) { # if this is actually an invalid link
1621 wfProfileIn( "$fname-might_be_img" );
1622 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1624 while (isset ($a[$k+
1]) ) {
1625 #look at the next 'line' to see if we can close it there
1626 $spliced = array_splice( $a, $k +
1, 1 );
1627 $next_line = array_shift( $spliced );
1628 $m = explode( ']]', $next_line, 3 );
1629 if ( count( $m ) == 3 ) {
1630 # the first ]] closes the inner link, the second the image
1632 $text .= "[[{$m[0]}]]{$m[1]}";
1635 } elseif ( count( $m ) == 2 ) {
1636 #if there's exactly one ]] that's fine, we'll keep looking
1637 $text .= "[[{$m[0]}]]{$m[1]}";
1639 #if $next_line is invalid too, we need look no further
1640 $text .= '[[' . $next_line;
1645 # we couldn't find the end of this imageLink, so output it raw
1646 #but don't ignore what might be perfectly normal links in the text we've examined
1647 $text = $this->replaceInternalLinks($text);
1648 $s .= "{$prefix}[[$link|$text";
1649 # note: no $trail, because without an end, there *is* no trail
1650 wfProfileOut( "$fname-might_be_img" );
1653 } else { #it's not an image, so output it raw
1654 $s .= "{$prefix}[[$link|$text";
1655 # note: no $trail, because without an end, there *is* no trail
1656 wfProfileOut( "$fname-might_be_img" );
1659 wfProfileOut( "$fname-might_be_img" );
1662 $wasblank = ( '' == $text );
1663 if( $wasblank ) $text = $link;
1665 # Link not escaped by : , create the various objects
1669 wfProfileIn( "$fname-interwiki" );
1670 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1671 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1672 $s = rtrim($s . "\n");
1673 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1674 wfProfileOut( "$fname-interwiki" );
1677 wfProfileOut( "$fname-interwiki" );
1679 if ( $ns == NS_IMAGE
) {
1680 wfProfileIn( "$fname-image" );
1681 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1682 # recursively parse links inside the image caption
1683 # actually, this will parse them in any other parameters, too,
1684 # but it might be hard to fix that, and it doesn't matter ATM
1685 $text = $this->replaceExternalLinks($text);
1686 $text = $this->replaceInternalLinks($text);
1688 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1689 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1690 $this->mOutput
->addImage( $nt->getDBkey() );
1692 wfProfileOut( "$fname-image" );
1695 # We still need to record the image's presence on the page
1696 $this->mOutput
->addImage( $nt->getDBkey() );
1698 wfProfileOut( "$fname-image" );
1702 if ( $ns == NS_CATEGORY
) {
1703 wfProfileIn( "$fname-category" );
1704 $s = rtrim($s . "\n"); # bug 87
1707 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1708 $sortkey = $this->mTitle
->getText();
1710 $sortkey = $this->mTitle
->getPrefixedText();
1715 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1716 $sortkey = str_replace( "\n", '', $sortkey );
1717 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1718 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1721 * Strip the whitespace Category links produce, see bug 87
1722 * @todo We might want to use trim($tmp, "\n") here.
1724 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1726 wfProfileOut( "$fname-category" );
1731 if( ( $nt->getPrefixedText() === $selflink ) &&
1732 ( $nt->getFragment() === '' ) ) {
1733 # Self-links are handled specially; generally de-link and change to bold.
1734 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1738 # Special and Media are pseudo-namespaces; no pages actually exist in them
1739 if( $ns == NS_MEDIA
) {
1740 $link = $sk->makeMediaLinkObj( $nt, $text );
1741 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1742 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1743 $this->mOutput
->addImage( $nt->getDBkey() );
1745 } elseif( $ns == NS_SPECIAL
) {
1746 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1748 } elseif( $ns == NS_IMAGE
) {
1749 $img = new Image( $nt );
1750 if( $img->exists() ) {
1751 // Force a blue link if the file exists; may be a remote
1752 // upload on the shared repository, and we want to see its
1753 // auto-generated page.
1754 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1755 $this->mOutput
->addLink( $nt );
1759 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1761 wfProfileOut( $fname );
1766 * Make a link placeholder. The text returned can be later resolved to a real link with
1767 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1768 * parsing of interwiki links, and secondly to allow all existence checks and
1769 * article length checks (for stub links) to be bundled into a single query.
1772 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1773 wfProfileIn( __METHOD__
);
1774 if ( ! is_object($nt) ) {
1776 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1778 # Separate the link trail from the rest of the link
1779 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1781 if ( $nt->isExternal() ) {
1782 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1783 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1784 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1786 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1787 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1788 $this->mLinkHolders
['queries'][] = $query;
1789 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1790 $this->mLinkHolders
['titles'][] = $nt;
1792 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1795 wfProfileOut( __METHOD__
);
1800 * Render a forced-blue link inline; protect against double expansion of
1801 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1802 * Since this little disaster has to split off the trail text to avoid
1803 * breaking URLs in the following text without breaking trails on the
1804 * wiki links, it's been made into a horrible function.
1807 * @param string $text
1808 * @param string $query
1809 * @param string $trail
1810 * @param string $prefix
1811 * @return string HTML-wikitext mix oh yuck
1813 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1814 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1815 $sk =& $this->mOptions
->getSkin();
1816 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1817 return $this->armorLinks( $link ) . $trail;
1821 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1822 * going to go through further parsing steps before inline URL expansion.
1824 * In particular this is important when using action=render, which causes
1825 * full URLs to be included.
1827 * Oh man I hate our multi-layer parser!
1829 * @param string more-or-less HTML
1830 * @return string less-or-more HTML with NOPARSE bits
1832 function armorLinks( $text ) {
1833 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1834 "{$this->mUniqPrefix}NOPARSE$1", $text );
1838 * Return true if subpage links should be expanded on this page.
1841 function areSubpagesAllowed() {
1842 # Some namespaces don't allow subpages
1843 global $wgNamespacesWithSubpages;
1844 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1848 * Handle link to subpage if necessary
1849 * @param string $target the source of the link
1850 * @param string &$text the link text, modified as necessary
1851 * @return string the full name of the link
1854 function maybeDoSubpageLink($target, &$text) {
1857 # :Foobar -- override special treatment of prefix (images, language links)
1858 # /Foobar -- convert to CurrentPage/Foobar
1859 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1860 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1861 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1863 $fname = 'Parser::maybeDoSubpageLink';
1864 wfProfileIn( $fname );
1865 $ret = $target; # default return value is no change
1868 $target = trim( $target );
1870 # Some namespaces don't allow subpages,
1871 # so only perform processing if subpages are allowed
1872 if( $this->areSubpagesAllowed() ) {
1873 # Look at the first character
1874 if( $target != '' && $target{0} == '/' ) {
1875 # / at end means we don't want the slash to be shown
1876 if( substr( $target, -1, 1 ) == '/' ) {
1877 $target = substr( $target, 1, -1 );
1880 $noslash = substr( $target, 1 );
1883 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1884 if( '' === $text ) {
1886 } # this might be changed for ugliness reasons
1888 # check for .. subpage backlinks
1890 $nodotdot = $target;
1891 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1893 $nodotdot = substr( $nodotdot, 3 );
1895 if($dotdotcount > 0) {
1896 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1897 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1898 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1899 # / at the end means don't show full path
1900 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1901 $nodotdot = substr( $nodotdot, 0, -1 );
1902 if( '' === $text ) {
1906 $nodotdot = trim( $nodotdot );
1907 if( $nodotdot != '' ) {
1908 $ret .= '/' . $nodotdot;
1915 wfProfileOut( $fname );
1920 * Used by doBlockLevels()
1923 /* private */ function closeParagraph() {
1925 if ( '' != $this->mLastSection
) {
1926 $result = '</' . $this->mLastSection
. ">\n";
1928 $this->mInPre
= false;
1929 $this->mLastSection
= '';
1932 # getCommon() returns the length of the longest common substring
1933 # of both arguments, starting at the beginning of both.
1935 /* private */ function getCommon( $st1, $st2 ) {
1936 $fl = strlen( $st1 );
1937 $shorter = strlen( $st2 );
1938 if ( $fl < $shorter ) { $shorter = $fl; }
1940 for ( $i = 0; $i < $shorter; ++
$i ) {
1941 if ( $st1{$i} != $st2{$i} ) { break; }
1945 # These next three functions open, continue, and close the list
1946 # element appropriate to the prefix character passed into them.
1948 /* private */ function openList( $char ) {
1949 $result = $this->closeParagraph();
1951 if ( '*' == $char ) { $result .= '<ul><li>'; }
1952 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1953 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1954 else if ( ';' == $char ) {
1955 $result .= '<dl><dt>';
1956 $this->mDTopen
= true;
1958 else { $result = '<!-- ERR 1 -->'; }
1963 /* private */ function nextItem( $char ) {
1964 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1965 else if ( ':' == $char ||
';' == $char ) {
1967 if ( $this->mDTopen
) { $close = '</dt>'; }
1968 if ( ';' == $char ) {
1969 $this->mDTopen
= true;
1970 return $close . '<dt>';
1972 $this->mDTopen
= false;
1973 return $close . '<dd>';
1976 return '<!-- ERR 2 -->';
1979 /* private */ function closeList( $char ) {
1980 if ( '*' == $char ) { $text = '</li></ul>'; }
1981 else if ( '#' == $char ) { $text = '</li></ol>'; }
1982 else if ( ':' == $char ) {
1983 if ( $this->mDTopen
) {
1984 $this->mDTopen
= false;
1985 $text = '</dt></dl>';
1987 $text = '</dd></dl>';
1990 else { return '<!-- ERR 3 -->'; }
1996 * Make lists from lines starting with ':', '*', '#', etc.
1999 * @return string the lists rendered as HTML
2001 function doBlockLevels( $text, $linestart ) {
2002 $fname = 'Parser::doBlockLevels';
2003 wfProfileIn( $fname );
2005 # Parsing through the text line by line. The main thing
2006 # happening here is handling of block-level elements p, pre,
2007 # and making lists from lines starting with * # : etc.
2009 $textLines = explode( "\n", $text );
2011 $lastPrefix = $output = '';
2012 $this->mDTopen
= $inBlockElem = false;
2014 $paragraphStack = false;
2016 if ( !$linestart ) {
2017 $output .= array_shift( $textLines );
2019 foreach ( $textLines as $oLine ) {
2020 $lastPrefixLength = strlen( $lastPrefix );
2021 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2022 $preOpenMatch = preg_match('/<pre/i', $oLine );
2023 if ( !$this->mInPre
) {
2024 # Multiple prefixes may abut each other for nested lists.
2025 $prefixLength = strspn( $oLine, '*#:;' );
2026 $pref = substr( $oLine, 0, $prefixLength );
2029 $pref2 = str_replace( ';', ':', $pref );
2030 $t = substr( $oLine, $prefixLength );
2031 $this->mInPre
= !empty($preOpenMatch);
2033 # Don't interpret any other prefixes in preformatted text
2035 $pref = $pref2 = '';
2040 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2041 # Same as the last item, so no need to deal with nesting or opening stuff
2042 $output .= $this->nextItem( substr( $pref, -1 ) );
2043 $paragraphStack = false;
2045 if ( substr( $pref, -1 ) == ';') {
2046 # The one nasty exception: definition lists work like this:
2047 # ; title : definition text
2048 # So we check for : in the remainder text to split up the
2049 # title and definition, without b0rking links.
2051 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2053 $output .= $term . $this->nextItem( ':' );
2056 } elseif( $prefixLength ||
$lastPrefixLength ) {
2057 # Either open or close a level...
2058 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2059 $paragraphStack = false;
2061 while( $commonPrefixLength < $lastPrefixLength ) {
2062 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2063 --$lastPrefixLength;
2065 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2066 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2068 while ( $prefixLength > $commonPrefixLength ) {
2069 $char = substr( $pref, $commonPrefixLength, 1 );
2070 $output .= $this->openList( $char );
2072 if ( ';' == $char ) {
2073 # FIXME: This is dupe of code above
2074 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2076 $output .= $term . $this->nextItem( ':' );
2079 ++
$commonPrefixLength;
2081 $lastPrefix = $pref2;
2083 if( 0 == $prefixLength ) {
2084 wfProfileIn( "$fname-paragraph" );
2085 # No prefix (not in list)--go to paragraph mode
2086 // XXX: use a stack for nestable elements like span, table and div
2087 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2088 $closematch = preg_match(
2089 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2090 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2091 if ( $openmatch or $closematch ) {
2092 $paragraphStack = false;
2093 #Â TODO bug 5718: paragraph closed
2094 $output .= $this->closeParagraph();
2095 if ( $preOpenMatch and !$preCloseMatch ) {
2096 $this->mInPre
= true;
2098 if ( $closematch ) {
2099 $inBlockElem = false;
2101 $inBlockElem = true;
2103 } else if ( !$inBlockElem && !$this->mInPre
) {
2104 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2106 if ($this->mLastSection
!= 'pre') {
2107 $paragraphStack = false;
2108 $output .= $this->closeParagraph().'<pre>';
2109 $this->mLastSection
= 'pre';
2111 $t = substr( $t, 1 );
2114 if ( '' == trim($t) ) {
2115 if ( $paragraphStack ) {
2116 $output .= $paragraphStack.'<br />';
2117 $paragraphStack = false;
2118 $this->mLastSection
= 'p';
2120 if ($this->mLastSection
!= 'p' ) {
2121 $output .= $this->closeParagraph();
2122 $this->mLastSection
= '';
2123 $paragraphStack = '<p>';
2125 $paragraphStack = '</p><p>';
2129 if ( $paragraphStack ) {
2130 $output .= $paragraphStack;
2131 $paragraphStack = false;
2132 $this->mLastSection
= 'p';
2133 } else if ($this->mLastSection
!= 'p') {
2134 $output .= $this->closeParagraph().'<p>';
2135 $this->mLastSection
= 'p';
2140 wfProfileOut( "$fname-paragraph" );
2142 // somewhere above we forget to get out of pre block (bug 785)
2143 if($preCloseMatch && $this->mInPre
) {
2144 $this->mInPre
= false;
2146 if ($paragraphStack === false) {
2150 while ( $prefixLength ) {
2151 $output .= $this->closeList( $pref2{$prefixLength-1} );
2154 if ( '' != $this->mLastSection
) {
2155 $output .= '</' . $this->mLastSection
. '>';
2156 $this->mLastSection
= '';
2159 wfProfileOut( $fname );
2164 * Split up a string on ':', ignoring any occurences inside tags
2165 * to prevent illegal overlapping.
2166 * @param string $str the string to split
2167 * @param string &$before set to everything before the ':'
2168 * @param string &$after set to everything after the ':'
2169 * return string the position of the ':', or false if none found
2171 function findColonNoLinks($str, &$before, &$after) {
2172 $fname = 'Parser::findColonNoLinks';
2173 wfProfileIn( $fname );
2175 $pos = strpos( $str, ':' );
2176 if( $pos === false ) {
2178 wfProfileOut( $fname );
2182 $lt = strpos( $str, '<' );
2183 if( $lt === false ||
$lt > $pos ) {
2184 // Easy; no tag nesting to worry about
2185 $before = substr( $str, 0, $pos );
2186 $after = substr( $str, $pos+
1 );
2187 wfProfileOut( $fname );
2191 // Ugly state machine to walk through avoiding tags.
2192 $state = MW_COLON_STATE_TEXT
;
2194 $len = strlen( $str );
2195 for( $i = 0; $i < $len; $i++
) {
2199 // (Using the number is a performance hack for common cases)
2200 case 0: // MW_COLON_STATE_TEXT:
2203 // Could be either a <start> tag or an </end> tag
2204 $state = MW_COLON_STATE_TAGSTART
;
2209 $before = substr( $str, 0, $i );
2210 $after = substr( $str, $i +
1 );
2211 wfProfileOut( $fname );
2214 // Embedded in a tag; don't break it.
2217 // Skip ahead looking for something interesting
2218 $colon = strpos( $str, ':', $i );
2219 if( $colon === false ) {
2220 // Nothing else interesting
2221 wfProfileOut( $fname );
2224 $lt = strpos( $str, '<', $i );
2225 if( $stack === 0 ) {
2226 if( $lt === false ||
$colon < $lt ) {
2228 $before = substr( $str, 0, $colon );
2229 $after = substr( $str, $colon +
1 );
2230 wfProfileOut( $fname );
2234 if( $lt === false ) {
2235 // Nothing else interesting to find; abort!
2236 // We're nested, but there's no close tags left. Abort!
2239 // Skip ahead to next tag start
2241 $state = MW_COLON_STATE_TAGSTART
;
2244 case 1: // MW_COLON_STATE_TAG:
2249 $state = MW_COLON_STATE_TEXT
;
2252 // Slash may be followed by >?
2253 $state = MW_COLON_STATE_TAGSLASH
;
2259 case 2: // MW_COLON_STATE_TAGSTART:
2262 $state = MW_COLON_STATE_CLOSETAG
;
2265 $state = MW_COLON_STATE_COMMENT
;
2268 // Illegal early close? This shouldn't happen D:
2269 $state = MW_COLON_STATE_TEXT
;
2272 $state = MW_COLON_STATE_TAG
;
2275 case 3: // MW_COLON_STATE_CLOSETAG:
2280 wfDebug( "Invalid input in $fname; too many close tags\n" );
2281 wfProfileOut( $fname );
2284 $state = MW_COLON_STATE_TEXT
;
2287 case MW_COLON_STATE_TAGSLASH
:
2289 // Yes, a self-closed tag <blah/>
2290 $state = MW_COLON_STATE_TEXT
;
2292 // Probably we're jumping the gun, and this is an attribute
2293 $state = MW_COLON_STATE_TAG
;
2296 case 5: // MW_COLON_STATE_COMMENT:
2298 $state = MW_COLON_STATE_COMMENTDASH
;
2301 case MW_COLON_STATE_COMMENTDASH
:
2303 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2305 $state = MW_COLON_STATE_COMMENT
;
2308 case MW_COLON_STATE_COMMENTDASHDASH
:
2310 $state = MW_COLON_STATE_TEXT
;
2312 $state = MW_COLON_STATE_COMMENT
;
2316 throw new MWException( "State machine error in $fname" );
2320 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2323 wfProfileOut( $fname );
2328 * Return value of a magic variable (like PAGENAME)
2332 function getVariableValue( $index ) {
2333 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2336 * Some of these require message or data lookups and can be
2337 * expensive to check many times.
2339 static $varCache = array();
2340 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2341 if ( isset( $varCache[$index] ) ) {
2342 return $varCache[$index];
2347 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2350 global $wgLocaltimezone;
2351 if ( isset( $wgLocaltimezone ) ) {
2352 $oldtz = getenv( 'TZ' );
2353 putenv( 'TZ='.$wgLocaltimezone );
2355 $localTimestamp = date( 'YmdHis', $ts );
2356 $localMonth = date( 'm', $ts );
2357 $localMonthName = date( 'n', $ts );
2358 $localDay = date( 'j', $ts );
2359 $localDay2 = date( 'd', $ts );
2360 $localDayOfWeek = date( 'w', $ts );
2361 $localWeek = date( 'W', $ts );
2362 $localYear = date( 'Y', $ts );
2363 $localHour = date( 'H', $ts );
2364 if ( isset( $wgLocaltimezone ) ) {
2365 putenv( 'TZ='.$oldtz );
2369 case 'currentmonth':
2370 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2371 case 'currentmonthname':
2372 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2373 case 'currentmonthnamegen':
2374 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2375 case 'currentmonthabbrev':
2376 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2378 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2380 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2382 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2383 case 'localmonthname':
2384 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2385 case 'localmonthnamegen':
2386 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2387 case 'localmonthabbrev':
2388 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2390 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2392 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2394 return $this->mTitle
->getText();
2396 return $this->mTitle
->getPartialURL();
2397 case 'fullpagename':
2398 return $this->mTitle
->getPrefixedText();
2399 case 'fullpagenamee':
2400 return $this->mTitle
->getPrefixedURL();
2402 return $this->mTitle
->getSubpageText();
2403 case 'subpagenamee':
2404 return $this->mTitle
->getSubpageUrlForm();
2405 case 'basepagename':
2406 return $this->mTitle
->getBaseText();
2407 case 'basepagenamee':
2408 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2409 case 'talkpagename':
2410 if( $this->mTitle
->canTalk() ) {
2411 $talkPage = $this->mTitle
->getTalkPage();
2412 return $talkPage->getPrefixedText();
2416 case 'talkpagenamee':
2417 if( $this->mTitle
->canTalk() ) {
2418 $talkPage = $this->mTitle
->getTalkPage();
2419 return $talkPage->getPrefixedUrl();
2423 case 'subjectpagename':
2424 $subjPage = $this->mTitle
->getSubjectPage();
2425 return $subjPage->getPrefixedText();
2426 case 'subjectpagenamee':
2427 $subjPage = $this->mTitle
->getSubjectPage();
2428 return $subjPage->getPrefixedUrl();
2430 return $this->mRevisionId
;
2432 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 ) );
2433 case 'revisionday2':
2434 return substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 );
2435 case 'revisionmonth':
2436 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 4, 2 ) );
2437 case 'revisionyear':
2438 return substr( wfRevisionTimestamp( $this->mRevisionId
), 0, 4 );
2439 case 'revisiontimestamp':
2440 return wfRevisionTimestamp( $this->mRevisionId
);
2442 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2444 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2446 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2448 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2449 case 'subjectspace':
2450 return $this->mTitle
->getSubjectNsText();
2451 case 'subjectspacee':
2452 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2453 case 'currentdayname':
2454 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2456 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2458 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2460 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2462 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2463 // int to remove the padding
2464 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2466 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2467 case 'localdayname':
2468 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2470 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2472 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2474 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2476 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2477 // int to remove the padding
2478 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2480 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2481 case 'numberofarticles':
2482 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2483 case 'numberoffiles':
2484 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2485 case 'numberofusers':
2486 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2487 case 'numberofpages':
2488 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2489 case 'numberofadmins':
2490 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2491 case 'currenttimestamp':
2492 return $varCache[$index] = wfTimestampNow();
2493 case 'localtimestamp':
2494 return $varCache[$index] = $localTimestamp;
2495 case 'currentversion':
2496 return $varCache[$index] = SpecialVersion
::getVersion();
2502 return $wgServerName;
2504 return $wgScriptPath;
2505 case 'directionmark':
2506 return $wgContLang->getDirMark();
2507 case 'contentlanguage':
2508 global $wgContLanguageCode;
2509 return $wgContLanguageCode;
2512 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2520 * initialise the magic variables (like CURRENTMONTHNAME)
2524 function initialiseVariables() {
2525 $fname = 'Parser::initialiseVariables';
2526 wfProfileIn( $fname );
2527 $variableIDs = MagicWord
::getVariableIDs();
2529 $this->mVariables
= array();
2530 foreach ( $variableIDs as $id ) {
2531 $mw =& MagicWord
::get( $id );
2532 $mw->addToArray( $this->mVariables
, $id );
2534 wfProfileOut( $fname );
2538 * parse any parentheses in format ((title|part|part))
2539 * and call callbacks to get a replacement text for any found piece
2541 * @param string $text The text to parse
2542 * @param array $callbacks rules in form:
2543 * '{' => array( # opening parentheses
2544 * 'end' => '}', # closing parentheses
2545 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2546 * 3 => callback # replacement callback to call if {{{..}}} is found
2549 * 'min' => 2, # Minimum parenthesis count in cb
2550 * 'max' => 3, # Maximum parenthesis count in cb
2553 function replace_callback ($text, $callbacks) {
2554 wfProfileIn( __METHOD__
);
2555 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2556 $lastOpeningBrace = -1; # last not closed parentheses
2558 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2561 while ( $i < strlen( $text ) ) {
2562 # Find next opening brace, closing brace or pipe
2563 if ( $lastOpeningBrace == -1 ) {
2564 $currentClosing = '';
2565 $search = $validOpeningBraces;
2567 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2568 $search = $validOpeningBraces . '|' . $currentClosing;
2571 $i +
= strcspn( $text, $search, $i );
2572 if ( $i < strlen( $text ) ) {
2573 if ( $text[$i] == '|' ) {
2575 } elseif ( $text[$i] == $currentClosing ) {
2577 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2579 $rule = $callbacks[$text[$i]];
2581 # Some versions of PHP have a strcspn which stops on null characters
2582 # Ignore and continue
2591 if ( $found == 'open' ) {
2592 # found opening brace, let's add it to parentheses stack
2593 $piece = array('brace' => $text[$i],
2594 'braceEnd' => $rule['end'],
2598 # count opening brace characters
2599 $piece['count'] = strspn( $text, $piece['brace'], $i );
2600 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2601 $i +
= $piece['count'];
2603 # we need to add to stack only if opening brace count is enough for one of the rules
2604 if ( $piece['count'] >= $rule['min'] ) {
2605 $lastOpeningBrace ++
;
2606 $openingBraceStack[$lastOpeningBrace] = $piece;
2608 } elseif ( $found == 'close' ) {
2609 # lets check if it is enough characters for closing brace
2610 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2611 $count = strspn( $text, $text[$i], $i, $maxCount );
2613 # check for maximum matching characters (if there are 5 closing
2614 # characters, we will probably need only 3 - depending on the rules)
2616 $matchingCallback = null;
2617 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2618 if ( $count > $cbType['max'] ) {
2619 # The specified maximum exists in the callback array, unless the caller
2621 $matchingCount = $cbType['max'];
2623 # Count is less than the maximum
2624 # Skip any gaps in the callback array to find the true largest match
2625 # Need to use array_key_exists not isset because the callback can be null
2626 $matchingCount = $count;
2627 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2632 if ($matchingCount <= 0) {
2636 $matchingCallback = $cbType['cb'][$matchingCount];
2638 # let's set a title or last part (if '|' was found)
2639 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2640 $openingBraceStack[$lastOpeningBrace]['title'] =
2641 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2642 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2644 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2645 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2646 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2649 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2650 $pieceEnd = $i +
$matchingCount;
2652 if( is_callable( $matchingCallback ) ) {
2654 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2655 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2656 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2657 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2659 # finally we can call a user callback and replace piece of text
2660 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2661 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2662 $i = $pieceStart +
strlen($replaceWith);
2664 # null value for callback means that parentheses should be parsed, but not replaced
2665 $i +
= $matchingCount;
2668 # reset last opening parentheses, but keep it in case there are unused characters
2669 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2670 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2671 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2674 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2675 $openingBraceStack[$lastOpeningBrace--] = null;
2677 if ($matchingCount < $piece['count']) {
2678 $piece['count'] -= $matchingCount;
2679 $piece['startAt'] -= $matchingCount;
2680 $piece['partStart'] = $piece['startAt'];
2681 # do we still qualify for any callback with remaining count?
2682 $currentCbList = $callbacks[$piece['brace']]['cb'];
2683 while ( $piece['count'] ) {
2684 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2685 $lastOpeningBrace++
;
2686 $openingBraceStack[$lastOpeningBrace] = $piece;
2692 } elseif ( $found == 'pipe' ) {
2693 # lets set a title if it is a first separator, or next part otherwise
2694 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2695 $openingBraceStack[$lastOpeningBrace]['title'] =
2696 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2697 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2698 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2700 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2701 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2702 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2704 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2708 wfProfileOut( __METHOD__
);
2713 * Replace magic variables, templates, and template arguments
2714 * with the appropriate text. Templates are substituted recursively,
2715 * taking care to avoid infinite loops.
2717 * Note that the substitution depends on value of $mOutputType:
2718 * OT_WIKI: only {{subst:}} templates
2719 * OT_MSG: only magic variables
2720 * OT_HTML: all templates and magic variables
2722 * @param string $tex The text to transform
2723 * @param array $args Key-value pairs representing template parameters to substitute
2724 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2727 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2728 # Prevent too big inclusions
2729 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2733 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2734 wfProfileIn( $fname );
2736 # This function is called recursively. To keep track of arguments we need a stack:
2737 array_push( $this->mArgStack
, $args );
2739 $braceCallbacks = array();
2741 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2743 if ( $this->mOutputType
!= OT_MSG
) {
2744 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2746 if ( $braceCallbacks ) {
2750 'cb' => $braceCallbacks,
2751 'min' => $argsOnly ?
3 : 2,
2752 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2756 'cb' => array(2=>null),
2761 $text = $this->replace_callback ($text, $callbacks);
2763 array_pop( $this->mArgStack
);
2765 wfProfileOut( $fname );
2770 * Replace magic variables
2773 function variableSubstitution( $matches ) {
2775 $fname = 'Parser::variableSubstitution';
2776 $varname = $wgContLang->lc($matches[1]);
2777 wfProfileIn( $fname );
2779 if ( $this->mOutputType
== OT_WIKI
) {
2780 # Do only magic variables prefixed by SUBST
2781 $mwSubst =& MagicWord
::get( 'subst' );
2782 if (!$mwSubst->matchStartAndRemove( $varname ))
2784 # Note that if we don't substitute the variable below,
2785 # we don't remove the {{subst:}} magic word, in case
2786 # it is a template rather than a magic variable.
2788 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2789 $id = $this->mVariables
[$varname];
2790 # Now check if we did really match, case sensitive or not
2791 $mw =& MagicWord
::get( $id );
2792 if ($mw->match($matches[1])) {
2793 $text = $this->getVariableValue( $id );
2794 $this->mOutput
->mContainsOldMagic
= true;
2796 $text = $matches[0];
2799 $text = $matches[0];
2801 wfProfileOut( $fname );
2806 * Return the text of a template, after recursively
2807 * replacing any variables or templates within the template.
2809 * @param array $piece The parts of the template
2810 * $piece['text']: matched text
2811 * $piece['title']: the title, i.e. the part before the |
2812 * $piece['parts']: the parameter array
2813 * @return string the text of the template
2816 function braceSubstitution( $piece ) {
2817 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2818 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2819 wfProfileIn( $fname );
2820 wfProfileIn( __METHOD__
.'-setup' );
2823 $found = false; # $text has been filled
2824 $nowiki = false; # wiki markup in $text should be escaped
2825 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2826 $noargs = false; # Don't replace triple-brace arguments in $text
2827 $replaceHeadings = false; # Make the edit section links go to the template not the article
2828 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2829 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2831 # Title object, where $text came from
2837 # $part1 is the bit before the first |, and must contain only title characters
2838 # $args is a list of arguments, starting from index 0, not including $part1
2840 $titleText = $part1 = $piece['title'];
2841 # If the third subpattern matched anything, it will start with |
2843 if (null == $piece['parts']) {
2844 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2845 if ($replaceWith != $piece['text']) {
2846 $text = $replaceWith;
2853 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2854 wfProfileOut( __METHOD__
.'-setup' );
2857 wfProfileIn( __METHOD__
.'-modifiers' );
2859 $mwSubst =& MagicWord
::get( 'subst' );
2860 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2861 # One of two possibilities is true:
2862 # 1) Found SUBST but not in the PST phase
2863 # 2) Didn't find SUBST and in the PST phase
2864 # In either case, return without further processing
2865 $text = $piece['text'];
2872 # MSG, MSGNW and RAW
2875 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2876 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2879 # Remove obsolete MSG:
2880 $mwMsg =& MagicWord
::get( 'msg' );
2881 $mwMsg->matchStartAndRemove( $part1 );
2885 $mwRaw =& MagicWord
::get( 'raw' );
2886 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2887 $forceRawInterwiki = true;
2890 wfProfileOut( __METHOD__
.'-modifiers' );
2894 wfProfileIn( __METHOD__
. '-pfunc' );
2896 $colonPos = strpos( $part1, ':' );
2897 if ( $colonPos !== false ) {
2898 # Case sensitive functions
2899 $function = substr( $part1, 0, $colonPos );
2900 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2901 $function = $this->mFunctionSynonyms
[1][$function];
2903 # Case insensitive functions
2904 $function = strtolower( $function );
2905 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2906 $function = $this->mFunctionSynonyms
[0][$function];
2912 $funcArgs = array_map( 'trim', $args );
2913 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2914 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2917 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2921 if ( is_array( $result ) ) {
2922 if ( isset( $result[0] ) ) {
2923 $text = $linestart . $result[0];
2924 unset( $result[0] );
2927 // Extract flags into the local scope
2928 // This allows callers to set flags such as nowiki, noparse, found, etc.
2931 $text = $linestart . $result;
2935 wfProfileOut( __METHOD__
. '-pfunc' );
2938 # Template table test
2940 # Did we encounter this template already? If yes, it is in the cache
2941 # and we need to check for loops.
2942 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2945 # Infinite loop test
2946 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2950 $text = $linestart .
2951 "[[$part1]]<!-- WARNING: template loop detected -->";
2952 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2954 # set $text to cached message.
2955 $text = $linestart . $this->mTemplates
[$piece['title']];
2959 # Load from database
2960 $lastPathLevel = $this->mTemplatePath
;
2962 wfProfileIn( __METHOD__
. '-loadtpl' );
2964 # declaring $subpage directly in the function call
2965 # does not work correctly with references and breaks
2966 # {{/subpage}}-style inclusions
2968 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2969 if ($subpage !== '') {
2970 $ns = $this->mTitle
->getNamespace();
2972 $title = Title
::newFromText( $part1, $ns );
2975 if ( !is_null( $title ) ) {
2976 $titleText = $title->getPrefixedText();
2977 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2978 # Check for language variants if the template is not found
2979 if($checkVariantLink && $title->getArticleID() == 0){
2980 $wgContLang->findVariantLink($part1, $title);
2983 if ( !$title->isExternal() ) {
2984 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2985 $text = SpecialPage
::capturePath( $title );
2986 if ( is_string( $text ) ) {
2991 $this->disableCache();
2994 $articleContent = $this->fetchTemplate( $title );
2995 if ( $articleContent !== false ) {
2997 $text = $articleContent;
2998 $replaceHeadings = true;
3002 # If the title is valid but undisplayable, make a link to it
3003 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3004 $text = "[[:$titleText]]";
3007 } elseif ( $title->isTrans() ) {
3008 // Interwiki transclusion
3009 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3010 $text = $this->interwikiTransclude( $title, 'render' );
3014 $text = $this->interwikiTransclude( $title, 'raw' );
3015 $replaceHeadings = true;
3020 # Template cache array insertion
3021 # Use the original $piece['title'] not the mangled $part1, so that
3022 # modifiers such as RAW: produce separate cache entries
3025 // A special page; don't store it in the template cache.
3027 $this->mTemplates
[$piece['title']] = $text;
3029 $text = $linestart . $text;
3032 wfProfileOut( __METHOD__
. '-loadtpl' );
3035 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3036 # Error, oversize inclusion
3037 $text = $linestart .
3038 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3043 # Recursive parsing, escaping and link table handling
3044 # Only for HTML output
3045 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3046 $text = wfEscapeWikiText( $text );
3047 } elseif ( !$this->ot
['msg'] && $found ) {
3049 $assocArgs = array();
3051 # Clean up argument array
3052 $assocArgs = array();
3054 foreach( $args as $arg ) {
3055 $eqpos = strpos( $arg, '=' );
3056 if ( $eqpos === false ) {
3057 $assocArgs[$index++
] = $arg;
3059 $name = trim( substr( $arg, 0, $eqpos ) );
3060 $value = trim( substr( $arg, $eqpos+
1 ) );
3061 if ( $value === false ) {
3064 if ( $name !== false ) {
3065 $assocArgs[$name] = $value;
3070 # Add a new element to the templace recursion path
3071 $this->mTemplatePath
[$part1] = 1;
3075 # If there are any <onlyinclude> tags, only include them
3076 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3078 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3080 foreach ($m[1] as $piece)
3083 # Remove <noinclude> sections and <includeonly> tags
3084 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3085 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3087 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3088 # Strip <nowiki>, <pre>, etc.
3089 $text = $this->strip( $text, $this->mStripState
);
3090 if ( $this->ot
['html'] ) {
3091 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3092 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3093 $text = Sanitizer
::removeHTMLcomments( $text );
3096 $text = $this->replaceVariables( $text, $assocArgs );
3098 # If the template begins with a table or block-level
3099 # element, it should be treated as beginning a new line.
3100 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3101 $text = "\n" . $text;
3103 } elseif ( !$noargs ) {
3104 # $noparse and !$noargs
3105 # Just replace the arguments, not any double-brace items
3106 # This is used for rendered interwiki transclusion
3107 $text = $this->replaceVariables( $text, $assocArgs, true );
3110 # Prune lower levels off the recursion check path
3111 $this->mTemplatePath
= $lastPathLevel;
3113 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3114 # Error, oversize inclusion
3115 $text = $linestart .
3116 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3122 wfProfileOut( $fname );
3123 return $piece['text'];
3125 wfProfileIn( __METHOD__
. '-placeholders' );
3127 # Replace raw HTML by a placeholder
3128 # Add a blank line preceding, to prevent it from mucking up
3129 # immediately preceding headings
3130 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3132 # replace ==section headers==
3133 # XXX this needs to go away once we have a better parser.
3134 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3135 if( !is_null( $title ) )
3136 $encodedname = base64_encode($title->getPrefixedDBkey());
3138 $encodedname = base64_encode("");
3139 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3140 PREG_SPLIT_DELIM_CAPTURE
);
3143 for( $i = 0; $i < count($m); $i +
= 2 ) {
3145 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3147 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3152 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3153 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3154 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3160 wfProfileOut( __METHOD__
. '-placeholders' );
3163 # Prune lower levels off the recursion check path
3164 $this->mTemplatePath
= $lastPathLevel;
3167 wfProfileOut( $fname );
3168 return $piece['text'];
3170 wfProfileOut( $fname );
3176 * Fetch the unparsed text of a template and register a reference to it.
3178 function fetchTemplate( $title ) {
3180 // Loop to fetch the article, with up to 1 redirect
3181 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3182 $rev = Revision
::newFromTitle( $title );
3183 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3187 $text = $rev->getText();
3188 if ( $text === false ) {
3192 $title = Title
::newFromRedirect( $text );
3198 * Transclude an interwiki link.
3200 function interwikiTransclude( $title, $action ) {
3201 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3203 if (!$wgEnableScaryTranscluding)
3204 return wfMsg('scarytranscludedisabled');
3206 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3207 // But we'll handle it generally anyway
3208 if ( $title->getNamespace() ) {
3209 // Use the canonical namespace, which should work anywhere
3210 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3212 $articleName = $title->getDBkey();
3215 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3216 $url .= "?action=$action";
3217 if (strlen($url) > 255)
3218 return wfMsg('scarytranscludetoolong');
3219 return $this->fetchScaryTemplateMaybeFromCache($url);
3222 function fetchScaryTemplateMaybeFromCache($url) {
3223 global $wgTranscludeCacheExpiry;
3224 $dbr =& wfGetDB(DB_SLAVE
);
3225 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3226 array('tc_url' => $url));
3228 $time = $obj->tc_time
;
3229 $text = $obj->tc_contents
;
3230 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3235 $text = Http
::get($url);
3237 return wfMsg('scarytranscludefailed', $url);
3239 $dbw =& wfGetDB(DB_MASTER
);
3240 $dbw->replace('transcache', array('tc_url'), array(
3242 'tc_time' => time(),
3243 'tc_contents' => $text));
3249 * Triple brace replacement -- used for template arguments
3252 function argSubstitution( $matches ) {
3253 $arg = trim( $matches['title'] );
3254 $text = $matches['text'];
3255 $inputArgs = end( $this->mArgStack
);
3257 if ( array_key_exists( $arg, $inputArgs ) ) {
3258 $text = $inputArgs[$arg];
3259 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3260 null != $matches['parts'] && count($matches['parts']) > 0) {
3261 $text = $matches['parts'][0];
3263 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3264 $text = $matches['text'] .
3265 '<!-- WARNING: argument omitted, expansion size too large -->';
3272 * Increment an include size counter
3274 * @param string $type The type of expansion
3275 * @param integer $size The size of the text
3276 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3278 function incrementIncludeSize( $type, $size ) {
3279 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3282 $this->mIncludeSizes
[$type] +
= $size;
3288 * Detect __NOGALLERY__ magic word and set a placeholder
3290 function stripNoGallery( &$text ) {
3291 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3293 $mw = MagicWord
::get( 'nogallery' );
3294 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3298 * Detect __TOC__ magic word and set a placeholder
3300 function stripToc( $text ) {
3301 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3303 $mw = MagicWord
::get( 'notoc' );
3304 if( $mw->matchAndRemove( $text ) ) {
3305 $this->mShowToc
= false;
3308 $mw = MagicWord
::get( 'toc' );
3309 if( $mw->match( $text ) ) {
3310 $this->mShowToc
= true;
3311 $this->mForceTocPosition
= true;
3313 // Set a placeholder. At the end we'll fill it in with the TOC.
3314 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3316 // Only keep the first one.
3317 $text = $mw->replace( '', $text );
3323 * This function accomplishes several tasks:
3324 * 1) Auto-number headings if that option is enabled
3325 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3326 * 3) Add a Table of contents on the top for users who have enabled the option
3327 * 4) Auto-anchor headings
3329 * It loops through all headlines, collects the necessary data, then splits up the
3330 * string and re-inserts the newly formatted headlines.
3332 * @param string $text
3333 * @param boolean $isMain
3336 function formatHeadings( $text, $isMain=true ) {
3337 global $wgMaxTocLevel, $wgContLang;
3339 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3340 if( !$this->mTitle
->userCanEdit() ) {
3343 $showEditLink = $this->mOptions
->getEditSection();
3346 # Inhibit editsection links if requested in the page
3347 $esw =& MagicWord
::get( 'noeditsection' );
3348 if( $esw->matchAndRemove( $text ) ) {
3352 # Get all headlines for numbering them and adding funky stuff like [edit]
3353 # links - this is for later, but we need the number of headlines right now
3355 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3357 # if there are fewer than 4 headlines in the article, do not show TOC
3358 # unless it's been explicitly enabled.
3359 $enoughToc = $this->mShowToc
&&
3360 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3362 # Allow user to stipulate that a page should have a "new section"
3363 # link added via __NEWSECTIONLINK__
3364 $mw =& MagicWord
::get( 'newsectionlink' );
3365 if( $mw->matchAndRemove( $text ) )
3366 $this->mOutput
->setNewSection( true );
3368 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3369 # override above conditions and always show TOC above first header
3370 $mw =& MagicWord
::get( 'forcetoc' );
3371 if ($mw->matchAndRemove( $text ) ) {
3372 $this->mShowToc
= true;
3376 # Never ever show TOC if no headers
3377 if( $numMatches < 1 ) {
3381 # We need this to perform operations on the HTML
3382 $sk =& $this->mOptions
->getSkin();
3386 $sectionCount = 0; # headlineCount excluding template sections
3388 # Ugh .. the TOC should have neat indentation levels which can be
3389 # passed to the skin functions. These are determined here
3393 $sublevelCount = array();
3394 $levelCount = array();
3401 foreach( $matches[3] as $headline ) {
3403 $templatetitle = '';
3404 $templatesection = 0;
3407 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3409 $templatetitle = base64_decode($mat[1]);
3410 $templatesection = 1 +
(int)base64_decode($mat[2]);
3411 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3415 $prevlevel = $level;
3416 $prevtoclevel = $toclevel;
3418 $level = $matches[1][$headlineCount];
3420 if( $doNumberHeadings ||
$enoughToc ) {
3422 if ( $level > $prevlevel ) {
3423 # Increase TOC level
3425 $sublevelCount[$toclevel] = 0;
3426 if( $toclevel<$wgMaxTocLevel ) {
3427 $toc .= $sk->tocIndent();
3430 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3431 # Decrease TOC level, find level to jump to
3433 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3434 # Can only go down to level 1
3437 for ($i = $toclevel; $i > 0; $i--) {
3438 if ( $levelCount[$i] == $level ) {
3439 # Found last matching level
3443 elseif ( $levelCount[$i] < $level ) {
3444 # Found first matching level below current level
3450 if( $toclevel<$wgMaxTocLevel ) {
3451 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3455 # No change in level, end TOC line
3456 if( $toclevel<$wgMaxTocLevel ) {
3457 $toc .= $sk->tocLineEnd();
3461 $levelCount[$toclevel] = $level;
3463 # count number of headlines for each level
3464 @$sublevelCount[$toclevel]++
;
3466 for( $i = 1; $i <= $toclevel; $i++
) {
3467 if( !empty( $sublevelCount[$i] ) ) {
3471 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3477 # The canonized header is a version of the header text safe to use for links
3478 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3479 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3480 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3482 # Remove link placeholders by the link text.
3483 # <!--LINK number-->
3485 # link text with suffix
3486 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3487 "\$this->mLinkHolders['texts'][\$1]",
3488 $canonized_headline );
3489 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3490 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3491 $canonized_headline );
3494 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3495 $tocline = trim( $canonized_headline );
3496 # Save headline for section edit hint before it's escaped
3497 $headline_hint = trim( $canonized_headline );
3498 $canonized_headline = Sanitizer
::escapeId( $tocline );
3499 $refers[$headlineCount] = $canonized_headline;
3501 # count how many in assoc. array so we can track dupes in anchors
3502 @$refers[$canonized_headline]++
;
3503 $refcount[$headlineCount]=$refers[$canonized_headline];
3505 # Don't number the heading if it is the only one (looks silly)
3506 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3507 # the two are different if the line contains a link
3508 $headline=$numbering . ' ' . $headline;
3511 # Create the anchor for linking from the TOC to the section
3512 $anchor = $canonized_headline;
3513 if($refcount[$headlineCount] > 1 ) {
3514 $anchor .= '_' . $refcount[$headlineCount];
3516 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3517 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3519 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3520 if ( empty( $head[$headlineCount] ) ) {
3521 $head[$headlineCount] = '';
3524 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3526 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3529 # give headline the correct <h#> tag
3530 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3538 if( $toclevel<$wgMaxTocLevel ) {
3539 $toc .= $sk->tocUnindent( $toclevel - 1 );
3541 $toc = $sk->tocList( $toc );
3544 # split up and insert constructed headlines
3546 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3549 foreach( $blocks as $block ) {
3550 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3551 # This is the [edit] link that appears for the top block of text when
3552 # section editing is enabled
3554 # Disabled because it broke block formatting
3555 # For example, a bullet point in the top line
3556 # $full .= $sk->editSectionLink(0);
3559 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3560 # Top anchor now in skin
3564 if( !empty( $head[$i] ) ) {
3569 if( $this->mForceTocPosition
) {
3570 return str_replace( '<!--MWTOC-->', $toc, $full );
3577 * Transform wiki markup when saving a page by doing \r\n -> \n
3578 * conversion, substitting signatures, {{subst:}} templates, etc.
3580 * @param string $text the text to transform
3581 * @param Title &$title the Title object for the current article
3582 * @param User &$user the User object describing the current user
3583 * @param ParserOptions $options parsing options
3584 * @param bool $clearState whether to clear the parser state first
3585 * @return string the altered wiki markup
3588 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3589 $this->mOptions
= $options;
3590 $this->mTitle
=& $title;
3591 $this->setOutputType( OT_WIKI
);
3593 if ( $clearState ) {
3594 $this->clearState();
3597 $stripState = false;
3601 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3602 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3603 $text = $this->pstPass2( $text, $stripState, $user );
3604 $text = $this->unstrip( $text, $stripState );
3605 $text = $this->unstripNoWiki( $text, $stripState );
3610 * Pre-save transform helper function
3613 function pstPass2( $text, &$stripState, $user ) {
3614 global $wgContLang, $wgLocaltimezone;
3616 /* Note: This is the timestamp saved as hardcoded wikitext to
3617 * the database, we use $wgContLang here in order to give
3618 * everyone the same signature and use the default one rather
3619 * than the one selected in each user's preferences.
3621 if ( isset( $wgLocaltimezone ) ) {
3622 $oldtz = getenv( 'TZ' );
3623 putenv( 'TZ='.$wgLocaltimezone );
3625 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3626 ' (' . date( 'T' ) . ')';
3627 if ( isset( $wgLocaltimezone ) ) {
3628 putenv( 'TZ='.$oldtz );
3631 # Variable replacement
3632 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3633 $text = $this->replaceVariables( $text );
3635 # Strip out <nowiki> etc. added via replaceVariables
3636 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3639 $sigText = $this->getUserSig( $user );
3640 $text = strtr( $text, array(
3642 '~~~~' => "$sigText $d",
3646 # Context links: [[|name]] and [[name (context)|]]
3648 global $wgLegalTitleChars;
3649 $tc = "[$wgLegalTitleChars]";
3650 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3652 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3653 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3654 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3656 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3657 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3658 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3660 $t = $this->mTitle
->getText();
3662 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3663 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3664 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3665 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3667 # if there's no context, don't bother duplicating the title
3668 $text = preg_replace( $p2, '[[\\1]]', $text );
3671 # Trim trailing whitespace
3672 # __END__ tag allows for trailing
3673 # whitespace to be deliberately included
3674 $text = rtrim( $text );
3675 $mw =& MagicWord
::get( 'end' );
3676 $mw->matchAndRemove( $text );
3682 * Fetch the user's signature text, if any, and normalize to
3683 * validated, ready-to-insert wikitext.
3689 function getUserSig( &$user ) {
3690 $username = $user->getName();
3691 $nickname = $user->getOption( 'nickname' );
3692 $nickname = $nickname === '' ?
$username : $nickname;
3694 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3695 # Sig. might contain markup; validate this
3696 if( $this->validateSig( $nickname ) !== false ) {
3697 # Validated; clean up (if needed) and return it
3698 return $this->cleanSig( $nickname, true );
3700 # Failed to validate; fall back to the default
3701 $nickname = $username;
3702 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3706 // Make sure nickname doesnt get a sig in a sig
3707 $nickname = $this->cleanSigInSig( $nickname );
3709 # If we're still here, make it a link to the user page
3710 $userpage = $user->getUserPage();
3711 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3715 * Check that the user's signature contains no bad XML
3717 * @param string $text
3718 * @return mixed An expanded string, or false if invalid.
3720 function validateSig( $text ) {
3721 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3725 * Clean up signature text
3727 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3728 * 2) Substitute all transclusions
3730 * @param string $text
3731 * @param $parsing Whether we're cleaning (preferences save) or parsing
3732 * @return string Signature text
3734 function cleanSig( $text, $parsing = false ) {
3736 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3738 $substWord = MagicWord
::get( 'subst' );
3739 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3740 $substText = '{{' . $substWord->getSynonym( 0 );
3742 $text = preg_replace( $substRegex, $substText, $text );
3743 $text = $this->cleanSigInSig( $text );
3744 $text = $this->replaceVariables( $text );
3746 $this->clearState();
3751 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3752 * @param string $text
3753 * @return string Signature text with /~{3,5}/ removed
3755 function cleanSigInSig( $text ) {
3756 $text = preg_replace( '/~{3,5}/', '', $text );
3761 * Set up some variables which are usually set up in parse()
3762 * so that an external function can call some class members with confidence
3765 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3766 $this->mTitle
=& $title;
3767 $this->mOptions
= $options;
3768 $this->setOutputType( $outputType );
3769 if ( $clearState ) {
3770 $this->clearState();
3775 * Transform a MediaWiki message by replacing magic variables.
3777 * @param string $text the text to transform
3778 * @param ParserOptions $options options
3779 * @return string the text with variables substituted
3782 function transformMsg( $text, $options ) {
3784 static $executing = false;
3786 $fname = "Parser::transformMsg";
3788 # Guard against infinite recursion
3794 wfProfileIn($fname);
3797 $this->mTitle
= $wgTitle;
3799 $this->mTitle
= Title
::newFromText('msg');
3801 $this->mOptions
= $options;
3802 $this->setOutputType( OT_MSG
);
3803 $this->clearState();
3804 $text = $this->replaceVariables( $text );
3807 wfProfileOut($fname);
3812 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3813 * The callback should have the following form:
3814 * function myParserHook( $text, $params, &$parser ) { ... }
3816 * Transform and return $text. Use $parser for any required context, e.g. use
3817 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3821 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3822 * @param mixed $callback The callback function (and object) to use for the tag
3824 * @return The old value of the mTagHooks array associated with the hook
3826 function setHook( $tag, $callback ) {
3827 $tag = strtolower( $tag );
3828 $oldVal = @$this->mTagHooks
[$tag];
3829 $this->mTagHooks
[$tag] = $callback;
3835 * Create a function, e.g. {{sum:1|2|3}}
3836 * The callback function should have the form:
3837 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3839 * The callback may either return the text result of the function, or an array with the text
3840 * in element 0, and a number of flags in the other elements. The names of the flags are
3841 * specified in the keys. Valid flags are:
3842 * found The text returned is valid, stop processing the template. This
3844 * nowiki Wiki markup in the return value should be escaped
3845 * noparse Unsafe HTML tags should not be stripped, etc.
3846 * noargs Don't replace triple-brace arguments in the return value
3847 * isHTML The returned text is HTML, armour it against wikitext transformation
3851 * @param string $id The magic word ID
3852 * @param mixed $callback The callback function (and object) to use
3853 * @param integer $flags a combination of the following flags:
3854 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3856 * @return The old callback function for this name, if any
3858 function setFunctionHook( $id, $callback, $flags = 0 ) {
3859 $oldVal = @$this->mFunctionHooks
[$id];
3860 $this->mFunctionHooks
[$id] = $callback;
3862 # Add to function cache
3863 $mw = MagicWord
::get( $id );
3865 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3867 $synonyms = $mw->getSynonyms();
3868 $sensitive = intval( $mw->isCaseSensitive() );
3870 foreach ( $synonyms as $syn ) {
3872 if ( !$sensitive ) {
3873 $syn = strtolower( $syn );
3876 if ( !( $flags & SFH_NO_HASH
) ) {
3879 # Remove trailing colon
3880 if ( substr( $syn, -1, 1 ) == ':' ) {
3881 $syn = substr( $syn, 0, -1 );
3883 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3889 * Get all registered function hook identifiers
3893 function getFunctionHooks() {
3894 return array_keys( $this->mFunctionHooks
);
3898 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3899 * Placeholders created in Skin::makeLinkObj()
3900 * Returns an array of links found, indexed by PDBK:
3904 * $options is a bit field, RLH_FOR_UPDATE to select for update
3906 function replaceLinkHolders( &$text, $options = 0 ) {
3908 global $wgOutputReplace;
3911 $fname = 'Parser::replaceLinkHolders';
3912 wfProfileIn( $fname );
3916 $sk =& $this->mOptions
->getSkin();
3917 $linkCache =& LinkCache
::singleton();
3919 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3920 wfProfileIn( $fname.'-check' );
3921 $dbr =& wfGetDB( DB_SLAVE
);
3922 $page = $dbr->tableName( 'page' );
3923 $threshold = $wgUser->getOption('stubthreshold');
3926 asort( $this->mLinkHolders
['namespaces'] );
3931 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3933 $title = $this->mLinkHolders
['titles'][$key];
3935 # Skip invalid entries.
3936 # Result will be ugly, but prevents crash.
3937 if ( is_null( $title ) ) {
3940 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3942 # Check if it's a static known link, e.g. interwiki
3943 if ( $title->isAlwaysKnown() ) {
3944 $colours[$pdbk] = 1;
3945 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3946 $colours[$pdbk] = 1;
3947 $this->mOutput
->addLink( $title, $id );
3948 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3949 $colours[$pdbk] = 0;
3951 # Not in the link cache, add it to the query
3952 if ( !isset( $current ) ) {
3954 $query = "SELECT page_id, page_namespace, page_title";
3955 if ( $threshold > 0 ) {
3956 $query .= ', page_len, page_is_redirect';
3958 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3959 } elseif ( $current != $ns ) {
3961 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3966 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3971 if ( $options & RLH_FOR_UPDATE
) {
3972 $query .= ' FOR UPDATE';
3975 $res = $dbr->query( $query, $fname );
3977 # Fetch data and form into an associative array
3978 # non-existent = broken
3981 while ( $s = $dbr->fetchObject($res) ) {
3982 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3983 $pdbk = $title->getPrefixedDBkey();
3984 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3985 $this->mOutput
->addLink( $title, $s->page_id
);
3987 if ( $threshold > 0 ) {
3988 $size = $s->page_len
;
3989 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3990 $colours[$pdbk] = 1;
3992 $colours[$pdbk] = 2;
3995 $colours[$pdbk] = 1;
3999 wfProfileOut( $fname.'-check' );
4001 # Do a second query for different language variants of links (if needed)
4002 if($wgContLang->hasVariants()){
4003 $linkBatch = new LinkBatch();
4004 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
4006 // Add variants of links to link batch
4007 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4008 $title = $this->mLinkHolders
['titles'][$key];
4009 if ( is_null( $title ) )
4012 $pdbk = $title->getPrefixedDBkey();
4014 // generate all variants of the link title text
4015 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4017 // if link was not found (in first query), add all variants to query
4018 if ( !isset($colours[$pdbk]) ){
4019 foreach($allTextVariants as $textVariant){
4020 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4021 if(is_null($variantTitle)) continue;
4022 $linkBatch->addObj( $variantTitle );
4023 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4029 if(!$linkBatch->isEmpty()){
4031 $titleClause = $linkBatch->constructSet('page', $dbr);
4033 $variantQuery = "SELECT page_id, page_namespace, page_title";
4034 if ( $threshold > 0 ) {
4035 $variantQuery .= ', page_len, page_is_redirect';
4038 $variantQuery .= " FROM $page WHERE $titleClause";
4039 if ( $options & RLH_FOR_UPDATE
) {
4040 $variantQuery .= ' FOR UPDATE';
4043 $varRes = $dbr->query( $variantQuery, $fname );
4045 // for each found variants, figure out link holders and replace
4046 while ( $s = $dbr->fetchObject($varRes) ) {
4048 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4049 $varPdbk = $variantTitle->getPrefixedDBkey();
4050 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4051 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4053 $holderKeys = $variantMap[$varPdbk];
4055 // loop over link holders
4056 foreach($holderKeys as $key){
4057 $title = $this->mLinkHolders
['titles'][$key];
4058 if ( is_null( $title ) ) continue;
4060 $pdbk = $title->getPrefixedDBkey();
4062 if(!isset($colours[$pdbk])){
4063 // found link in some of the variants, replace the link holder data
4064 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4065 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4067 // set pdbk and colour
4068 $pdbks[$key] = $varPdbk;
4069 if ( $threshold > 0 ) {
4070 $size = $s->page_len
;
4071 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4072 $colours[$varPdbk] = 1;
4074 $colours[$varPdbk] = 2;
4078 $colours[$varPdbk] = 1;
4086 # Construct search and replace arrays
4087 wfProfileIn( $fname.'-construct' );
4088 $wgOutputReplace = array();
4089 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4090 $pdbk = $pdbks[$key];
4091 $searchkey = "<!--LINK $key-->";
4092 $title = $this->mLinkHolders
['titles'][$key];
4093 if ( empty( $colours[$pdbk] ) ) {
4094 $linkCache->addBadLinkObj( $title );
4095 $colours[$pdbk] = 0;
4096 $this->mOutput
->addLink( $title, 0 );
4097 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4098 $this->mLinkHolders
['texts'][$key],
4099 $this->mLinkHolders
['queries'][$key] );
4100 } elseif ( $colours[$pdbk] == 1 ) {
4101 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4102 $this->mLinkHolders
['texts'][$key],
4103 $this->mLinkHolders
['queries'][$key] );
4104 } elseif ( $colours[$pdbk] == 2 ) {
4105 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4106 $this->mLinkHolders
['texts'][$key],
4107 $this->mLinkHolders
['queries'][$key] );
4110 wfProfileOut( $fname.'-construct' );
4113 wfProfileIn( $fname.'-replace' );
4115 $text = preg_replace_callback(
4116 '/(<!--LINK .*?-->)/',
4117 "wfOutputReplaceMatches",
4120 wfProfileOut( $fname.'-replace' );
4123 # Now process interwiki link holders
4124 # This is quite a bit simpler than internal links
4125 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4126 wfProfileIn( $fname.'-interwiki' );
4127 # Make interwiki link HTML
4128 $wgOutputReplace = array();
4129 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4130 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4131 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4134 $text = preg_replace_callback(
4135 '/<!--IWLINK (.*?)-->/',
4136 "wfOutputReplaceMatches",
4138 wfProfileOut( $fname.'-interwiki' );
4141 wfProfileOut( $fname );
4146 * Replace <!--LINK--> link placeholders with plain text of links
4147 * (not HTML-formatted).
4148 * @param string $text
4151 function replaceLinkHoldersText( $text ) {
4152 $fname = 'Parser::replaceLinkHoldersText';
4153 wfProfileIn( $fname );
4155 $text = preg_replace_callback(
4156 '/<!--(LINK|IWLINK) (.*?)-->/',
4157 array( &$this, 'replaceLinkHoldersTextCallback' ),
4160 wfProfileOut( $fname );
4165 * @param array $matches
4169 function replaceLinkHoldersTextCallback( $matches ) {
4170 $type = $matches[1];
4172 if( $type == 'LINK' ) {
4173 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4174 return $this->mLinkHolders
['texts'][$key];
4176 } elseif( $type == 'IWLINK' ) {
4177 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4178 return $this->mInterwikiLinkHolders
['texts'][$key];
4185 * Tag hook handler for 'pre'.
4187 function renderPreTag( $text, $attribs ) {
4188 // Backwards-compatibility hack
4189 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4191 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4192 return wfOpenElement( 'pre', $attribs ) .
4193 wfEscapeHTMLTagsOnly( $content ) .
4198 * Renders an image gallery from a text with one line per image.
4199 * text labels may be given by using |-style alternative text. E.g.
4200 * Image:one.jpg|The number "1"
4201 * Image:tree.jpg|A tree
4202 * given as text will return the HTML of a gallery with two images,
4203 * labeled 'The number "1"' and
4206 function renderImageGallery( $text, $params ) {
4207 $ig = new ImageGallery();
4208 $ig->setShowBytes( false );
4209 $ig->setShowFilename( false );
4211 $ig->useSkin( $this->mOptions
->getSkin() );
4213 if( isset( $params['caption'] ) )
4214 $ig->setCaption( $params['caption'] );
4216 $lines = explode( "\n", $text );
4217 foreach ( $lines as $line ) {
4218 # match lines like these:
4219 # Image:someimage.jpg|This is some image
4221 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4223 if ( count( $matches ) == 0 ) {
4226 $tp = Title
::newFromText( $matches[1] );
4228 if( is_null( $nt ) ) {
4229 # Bogus title. Ignore these so we don't bomb out later.
4232 if ( isset( $matches[3] ) ) {
4233 $label = $matches[3];
4238 $pout = $this->parse( $label,
4241 false, // Strip whitespace...?
4242 false // Don't clear state!
4244 $html = $pout->getText();
4246 $ig->add( new Image( $nt ), $html );
4248 # Only add real images (bug #5586)
4249 if ( $nt->getNamespace() == NS_IMAGE
) {
4250 $this->mOutput
->addImage( $nt->getDBkey() );
4253 return $ig->toHTML();
4257 * Parse image options text and use it to make an image
4259 function makeImage( $nt, $options ) {
4260 global $wgUseImageResize, $wgDjvuRenderer;
4264 # Check if the options text is of the form "options|alt text"
4266 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4267 # * left no resizing, just left align. label is used for alt= only
4268 # * right same, but right aligned
4269 # * none same, but not aligned
4270 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4271 # * center center the image
4272 # * framed Keep original image size, no magnify-button.
4274 $part = explode( '|', $options);
4276 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4277 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4278 $mwLeft =& MagicWord
::get( 'img_left' );
4279 $mwRight =& MagicWord
::get( 'img_right' );
4280 $mwNone =& MagicWord
::get( 'img_none' );
4281 $mwWidth =& MagicWord
::get( 'img_width' );
4282 $mwCenter =& MagicWord
::get( 'img_center' );
4283 $mwFramed =& MagicWord
::get( 'img_framed' );
4284 $mwPage =& MagicWord
::get( 'img_page' );
4287 $width = $height = $framed = $thumb = false;
4289 $manual_thumb = '' ;
4291 foreach( $part as $val ) {
4292 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4294 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4295 # use manually specified thumbnail
4297 $manual_thumb = $match;
4298 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4299 # remember to set an alignment, don't render immediately
4301 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4302 # remember to set an alignment, don't render immediately
4304 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4305 # remember to set an alignment, don't render immediately
4307 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4308 # remember to set an alignment, don't render immediately
4310 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4311 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4312 # Select a page in a multipage document
4314 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4315 wfDebug( "img_width match: $match\n" );
4316 # $match is the image width in pixels
4318 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4319 $width = intval( $m[1] );
4320 $height = intval( $m[2] );
4322 $width = intval($match);
4324 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4330 # Strip bad stuff out of the alt text
4331 $alt = $this->replaceLinkHoldersText( $caption );
4333 # make sure there are no placeholders in thumbnail attributes
4334 # that are later expanded to html- so expand them now and
4336 $alt = $this->unstrip($alt, $this->mStripState
);
4337 $alt = Sanitizer
::stripAllTags( $alt );
4339 # Linker does the rest
4340 $sk =& $this->mOptions
->getSkin();
4341 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4345 * Set a flag in the output object indicating that the content is dynamic and
4346 * shouldn't be cached.
4348 function disableCache() {
4349 wfDebug( "Parser output marked as uncacheable.\n" );
4350 $this->mOutput
->mCacheTime
= -1;
4354 * Callback from the Sanitizer for expanding items found in HTML attribute
4355 * values, so they can be safely tested and escaped.
4356 * @param string $text
4357 * @param array $args
4361 function attributeStripCallback( &$text, $args ) {
4362 $text = $this->replaceVariables( $text, $args );
4363 $text = $this->unstripForHTML( $text );
4367 function unstripForHTML( $text ) {
4368 $text = $this->unstrip( $text, $this->mStripState
);
4369 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4377 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4378 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4379 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4385 function getTags() { return array_keys( $this->mTagHooks
); }
4390 * Break wikitext input into sections, and either pull or replace
4391 * some particular section's text.
4393 * External callers should use the getSection and replaceSection methods.
4395 * @param $text Page wikitext
4396 * @param $section Numbered section. 0 pulls the text before the first
4397 * heading; other numbers will pull the given section
4398 * along with its lower-level subsections.
4399 * @param $mode One of "get" or "replace"
4400 * @param $newtext Replacement text for section data.
4401 * @return string for "get", the extracted section text.
4402 * for "replace", the whole page with the section replaced.
4404 private function extractSections( $text, $section, $mode, $newtext='' ) {
4405 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4406 # comments to be stripped as well)
4407 $striparray = array();
4409 $oldOutputType = $this->mOutputType
;
4410 $oldOptions = $this->mOptions
;
4411 $this->mOptions
= new ParserOptions();
4412 $this->setOutputType( OT_WIKI
);
4414 $striptext = $this->strip( $text, $striparray, true );
4416 $this->setOutputType( $oldOutputType );
4417 $this->mOptions
= $oldOptions;
4419 # now that we can be sure that no pseudo-sections are in the source,
4420 # split it up by section
4421 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4422 $comment = "(?:$uniq-!--.*?QINU)";
4427 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4429 (=+) # Should this be limited to 6?
4430 .+? # Section title...
4431 \\2 # Ending = count must match start
4438 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4445 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4446 (=+) # Should this be limited to 6?
4447 .+? # Section title...
4448 \\2 # Ending = count must match start
4449 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4458 PREG_SPLIT_DELIM_CAPTURE
);
4460 if( $mode == "get" ) {
4461 if( $section == 0 ) {
4462 // "Section 0" returns the content before any other section.
4467 } elseif( $mode == "replace" ) {
4468 if( $section == 0 ) {
4469 $rv = $newtext . "\n\n";
4478 for( $index = 1; $index < count( $secs ); ) {
4479 $headerLine = $secs[$index++
];
4480 if( $secs[$index] ) {
4482 $headerLevel = strlen( $secs[$index++
] );
4486 $headerLevel = intval( $secs[$index++
] );
4488 $content = $secs[$index++
];
4491 if( $mode == "get" ) {
4492 if( $count == $section ) {
4493 $rv = $headerLine . $content;
4494 $sectionLevel = $headerLevel;
4495 } elseif( $count > $section ) {
4496 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4497 $rv .= $headerLine . $content;
4499 // Broke out to a higher-level section
4503 } elseif( $mode == "replace" ) {
4504 if( $count < $section ) {
4505 $rv .= $headerLine . $content;
4506 } elseif( $count == $section ) {
4507 $rv .= $newtext . "\n\n";
4508 $sectionLevel = $headerLevel;
4509 } elseif( $count > $section ) {
4510 if( $headerLevel <= $sectionLevel ) {
4511 // Passed the section's sub-parts.
4515 $rv .= $headerLine . $content;
4520 # reinsert stripped tags
4521 $rv = $this->unstrip( $rv, $striparray );
4522 $rv = $this->unstripNoWiki( $rv, $striparray );
4528 * This function returns the text of a section, specified by a number ($section).
4529 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4530 * the first section before any such heading (section 0).
4532 * If a section contains subsections, these are also returned.
4534 * @param $text String: text to look in
4535 * @param $section Integer: section number
4536 * @return string text of the requested section
4538 function getSection( $text, $section ) {
4539 return $this->extractSections( $text, $section, "get" );
4542 function replaceSection( $oldtext, $section, $text ) {
4543 return $this->extractSections( $oldtext, $section, "replace", $text );
4550 * @package MediaWiki
4554 var $mText, # The output text
4555 $mLanguageLinks, # List of the full text of language links, in the order they appear
4556 $mCategories, # Map of category names to sort keys
4557 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4558 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4559 $mVersion, # Compatibility check
4560 $mTitleText, # title text of the chosen language variant
4561 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4562 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4563 $mImages, # DB keys of the images used, in the array key only
4564 $mExternalLinks, # External link URLs, in the key only
4565 $mHTMLtitle, # Display HTML title
4566 $mSubtitle, # Additional subtitle
4567 $mNewSection, # Show a new section link?
4568 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4570 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4571 $containsOldMagic = false, $titletext = '' )
4573 $this->mText
= $text;
4574 $this->mLanguageLinks
= $languageLinks;
4575 $this->mCategories
= $categoryLinks;
4576 $this->mContainsOldMagic
= $containsOldMagic;
4577 $this->mCacheTime
= '';
4578 $this->mVersion
= MW_PARSER_VERSION
;
4579 $this->mTitleText
= $titletext;
4580 $this->mLinks
= array();
4581 $this->mTemplates
= array();
4582 $this->mImages
= array();
4583 $this->mExternalLinks
= array();
4584 $this->mHTMLtitle
= "" ;
4585 $this->mSubtitle
= "" ;
4586 $this->mNewSection
= false;
4587 $this->mNoGallery
= false;
4590 function getText() { return $this->mText
; }
4591 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4592 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4593 function &getCategories() { return $this->mCategories
; }
4594 function getCacheTime() { return $this->mCacheTime
; }
4595 function getTitleText() { return $this->mTitleText
; }
4596 function &getLinks() { return $this->mLinks
; }
4597 function &getTemplates() { return $this->mTemplates
; }
4598 function &getImages() { return $this->mImages
; }
4599 function &getExternalLinks() { return $this->mExternalLinks
; }
4600 function getNoGallery() { return $this->mNoGallery
; }
4601 function getSubtitle() { return $this->mSubtitle
; }
4603 function containsOldMagic() { return $this->mContainsOldMagic
; }
4604 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4605 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4606 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4607 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4608 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4609 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4610 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4612 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4613 function addImage( $name ) { $this->mImages
[$name] = 1; }
4614 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4615 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4617 function setNewSection( $value ) {
4618 $this->mNewSection
= (bool)$value;
4620 function getNewSection() {
4621 return (bool)$this->mNewSection
;
4624 function addLink( $title, $id = null ) {
4625 $ns = $title->getNamespace();
4626 $dbk = $title->getDBkey();
4627 if ( !isset( $this->mLinks
[$ns] ) ) {
4628 $this->mLinks
[$ns] = array();
4630 if ( is_null( $id ) ) {
4631 $id = $title->getArticleID();
4633 $this->mLinks
[$ns][$dbk] = $id;
4636 function addTemplate( $title, $id ) {
4637 $ns = $title->getNamespace();
4638 $dbk = $title->getDBkey();
4639 if ( !isset( $this->mTemplates
[$ns] ) ) {
4640 $this->mTemplates
[$ns] = array();
4642 $this->mTemplates
[$ns][$dbk] = $id;
4646 * Return true if this cached output object predates the global or
4647 * per-article cache invalidation timestamps, or if it comes from
4648 * an incompatible older version.
4650 * @param string $touched the affected article's last touched timestamp
4654 function expired( $touched ) {
4655 global $wgCacheEpoch;
4656 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4657 $this->getCacheTime() < $touched ||
4658 $this->getCacheTime() <= $wgCacheEpoch ||
4659 !isset( $this->mVersion
) ||
4660 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4665 * Set options of the Parser
4667 * @package MediaWiki
4671 # All variables are supposed to be private in theory, although in practise this is not the case.
4672 var $mUseTeX; # Use texvc to expand <math> tags
4673 var $mUseDynamicDates; # Use DateFormatter to format dates
4674 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4675 var $mAllowExternalImages; # Allow external images inline
4676 var $mAllowExternalImagesFrom; # If not, any exception?
4677 var $mSkin; # Reference to the preferred skin
4678 var $mDateFormat; # Date format index
4679 var $mEditSection; # Create "edit section" links
4680 var $mNumberHeadings; # Automatically number headings
4681 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4682 var $mTidy; # Ask for tidy cleanup
4683 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4684 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4685 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4687 var $mUser; # Stored user object, just used to initialise the skin
4689 function getUseTeX() { return $this->mUseTeX
; }
4690 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4691 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4692 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4693 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4694 function getEditSection() { return $this->mEditSection
; }
4695 function getNumberHeadings() { return $this->mNumberHeadings
; }
4696 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4697 function getTidy() { return $this->mTidy
; }
4698 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4699 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4700 function getRemoveComments() { return $this->mRemoveComments
; }
4702 function &getSkin() {
4703 if ( !isset( $this->mSkin
) ) {
4704 $this->mSkin
= $this->mUser
->getSkin();
4706 return $this->mSkin
;
4709 function getDateFormat() {
4710 if ( !isset( $this->mDateFormat
) ) {
4711 $this->mDateFormat
= $this->mUser
->getDatePreference();
4713 return $this->mDateFormat
;
4716 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4717 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4718 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4719 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4720 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4721 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4722 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4723 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4724 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4725 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4726 function setSkin( $x ) { $this->mSkin
= $x; }
4727 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4728 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4729 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4731 function ParserOptions( $user = null ) {
4732 $this->initialiseFromUser( $user );
4736 * Get parser options
4739 static function newFromUser( $user ) {
4740 return new ParserOptions( $user );
4743 /** Get user options */
4744 function initialiseFromUser( $userInput ) {
4745 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4746 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4747 $fname = 'ParserOptions::initialiseFromUser';
4748 wfProfileIn( $fname );
4749 if ( !$userInput ) {
4751 if ( isset( $wgUser ) ) {
4757 $user =& $userInput;
4760 $this->mUser
= $user;
4762 $this->mUseTeX
= $wgUseTeX;
4763 $this->mUseDynamicDates
= $wgUseDynamicDates;
4764 $this->mInterwikiMagic
= $wgInterwikiMagic;
4765 $this->mAllowExternalImages
= $wgAllowExternalImages;
4766 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4767 $this->mSkin
= null; # Deferred
4768 $this->mDateFormat
= null; # Deferred
4769 $this->mEditSection
= true;
4770 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4771 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4772 $this->mTidy
= false;
4773 $this->mInterfaceMessage
= false;
4774 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4775 $this->mRemoveComments
= true;
4776 wfProfileOut( $fname );
4781 * Callback function used by Parser::replaceLinkHolders()
4782 * to substitute link placeholders.
4784 function &wfOutputReplaceMatches( $matches ) {
4785 global $wgOutputReplace;
4786 return $wgOutputReplace[$matches[1]];
4790 * Return the total number of articles
4792 function wfNumberOfArticles() {
4793 global $wgNumberOfArticles;
4796 return $wgNumberOfArticles;
4800 * Return the number of files
4802 function wfNumberOfFiles() {
4803 $fname = 'wfNumberOfFiles';
4805 wfProfileIn( $fname );
4806 $dbr =& wfGetDB( DB_SLAVE
);
4807 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4808 wfProfileOut( $fname );
4814 * Return the number of user accounts
4817 function wfNumberOfUsers() {
4818 wfProfileIn( 'wfNumberOfUsers' );
4819 $dbr =& wfGetDB( DB_SLAVE
);
4820 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4821 wfProfileOut( 'wfNumberOfUsers' );
4826 * Return the total number of pages
4829 function wfNumberOfPages() {
4830 wfProfileIn( 'wfNumberOfPages' );
4831 $dbr =& wfGetDB( DB_SLAVE
);
4832 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4833 wfProfileOut( 'wfNumberOfPages' );
4838 * Return the total number of admins
4842 function wfNumberOfAdmins() {
4843 static $admins = -1;
4844 wfProfileIn( 'wfNumberOfAdmins' );
4845 if( $admins == -1 ) {
4846 $dbr =& wfGetDB( DB_SLAVE
);
4847 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4849 wfProfileOut( 'wfNumberOfAdmins' );
4850 return (int)$admins;
4854 * Count the number of pages in a particular namespace
4856 * @param $ns Namespace
4859 function wfPagesInNs( $ns ) {
4860 static $pageCount = array();
4861 wfProfileIn( 'wfPagesInNs' );
4862 if( !isset( $pageCount[$ns] ) ) {
4863 $dbr =& wfGetDB( DB_SLAVE
);
4864 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4866 wfProfileOut( 'wfPagesInNs' );
4867 return (int)$pageCount[$ns];
4871 * Get various statistics from the database
4874 function wfLoadSiteStats() {
4875 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4876 $fname = 'wfLoadSiteStats';
4878 if ( -1 != $wgNumberOfArticles ) return;
4879 $dbr =& wfGetDB( DB_SLAVE
);
4880 $s = $dbr->selectRow( 'site_stats',
4881 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4882 array( 'ss_row_id' => 1 ), $fname
4885 if ( $s === false ) {
4888 $wgTotalViews = $s->ss_total_views
;
4889 $wgTotalEdits = $s->ss_total_edits
;
4890 $wgNumberOfArticles = $s->ss_good_articles
;
4895 * Get revision timestamp from the database considering timecorrection
4897 * @param $id Int: page revision id
4900 function wfRevisionTimestamp( $id ) {
4902 $fname = 'wfRevisionTimestamp';
4904 wfProfileIn( $fname );
4905 $dbr =& wfGetDB( DB_SLAVE
);
4906 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4907 array( 'rev_id' => $id ), __METHOD__
);
4908 $timestamp = $wgContLang->userAdjust( $timestamp );
4909 wfProfileOut( $fname );
4916 * Basically replacing " > and < with HTML entities ( ", >, <)
4918 * @param $in String: text that might contain HTML tags.
4919 * @return string Escaped string
4921 function wfEscapeHTMLTagsOnly( $in ) {
4923 array( '"', '>', '<' ),
4924 array( '"', '>', '<' ),