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( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
143 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
144 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
165 if ( $wgAllowDisplayTitle ) {
166 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
168 if ( $wgAllowSlowParserFunctions ) {
169 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
172 $this->initialiseVariables();
174 $this->mFirstCall
= false;
175 wfProfileOut( __METHOD__
);
183 function clearState() {
184 wfProfileIn( __METHOD__
);
185 if ( $this->mFirstCall
) {
186 $this->firstCallInit();
188 $this->mOutput
= new ParserOutput
;
189 $this->mAutonumber
= 0;
190 $this->mLastSection
= '';
191 $this->mDTopen
= false;
192 $this->mIncludeCount
= array();
193 $this->mStripState
= array();
194 $this->mArgStack
= array();
195 $this->mInPre
= false;
196 $this->mInterwikiLinkHolders
= array(
200 $this->mLinkHolders
= array(
201 'namespaces' => array(),
203 'queries' => array(),
207 $this->mRevisionId
= null;
210 * Prefix for temporary replacement strings for the multipass parser.
211 * \x07 should never appear in input as it's disallowed in XML.
212 * Using it at the front also gives us a little extra robustness
213 * since it shouldn't match when butted up against identifier-like
216 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTemplates
= array();
220 $this->mTemplatePath
= array();
222 $this->mShowToc
= true;
223 $this->mForceTocPosition
= false;
224 $this->mIncludeSizes
= array(
230 wfRunHooks( 'ParserClearState', array( &$this ) );
231 wfProfileOut( __METHOD__
);
234 function setOutputType( $ot ) {
235 $this->mOutputType
= $ot;
238 'html' => $ot == OT_HTML
,
239 'wiki' => $ot == OT_WIKI
,
240 'msg' => $ot == OT_MSG
,
241 'pre' => $ot == OT_PREPROCESS
,
246 * Accessor for mUniqPrefix.
250 function uniqPrefix() {
251 return $this->mUniqPrefix
;
255 * Convert wikitext to HTML
256 * Do not call this function recursively.
259 * @param string $text Text we want to parse
260 * @param Title &$title A title object
261 * @param array $options
262 * @param boolean $linestart
263 * @param boolean $clearState
264 * @param int $revid number to pass in {{REVISIONID}}
265 * @return ParserOutput a ParserOutput
267 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
269 * First pass--just handle <nowiki> sections, pass the rest off
270 * to internalParse() which does all the real work.
273 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
274 $fname = 'Parser::parse';
275 wfProfileIn( $fname );
281 $this->mOptions
= $options;
282 $this->mTitle
=& $title;
283 $oldRevisionId = $this->mRevisionId
;
284 if( $revid !== null ) {
285 $this->mRevisionId
= $revid;
287 $this->setOutputType( OT_HTML
);
289 //$text = $this->strip( $text, $this->mStripState );
290 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
291 $x =& $this->mStripState
;
293 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
294 $text = $this->strip( $text, $x );
295 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
297 $text = $this->internalParse( $text );
299 $text = $this->unstrip( $text, $this->mStripState
);
301 # Clean up special characters, only run once, next-to-last before doBlockLevels
303 # french spaces, last one Guillemet-left
304 # only if there is something before the space
305 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
306 # french spaces, Guillemet-right
307 '/(\\302\\253) /' => '\\1 ',
309 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
312 $text = $this->doBlockLevels( $text, $linestart );
314 $this->replaceLinkHolders( $text );
316 # the position of the parserConvert() call should not be changed. it
317 # assumes that the links are all replaced and the only thing left
318 # is the <nowiki> mark.
319 # Side-effects: this calls $this->mOutput->setTitleText()
320 $text = $wgContLang->parserConvert( $text, $this );
322 $text = $this->unstripNoWiki( $text, $this->mStripState
);
324 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
326 $text = Sanitizer
::normalizeCharReferences( $text );
328 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
329 $text = Parser
::tidy($text);
331 # attempt to sanitize at least some nesting problems
332 # (bug #2702 and quite a few others)
334 # ''Something [http://www.cool.com cool''] -->
335 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
336 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
337 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
338 # fix up an anchor inside another anchor, only
339 # at least for a single single nested link (bug 3695)
340 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
341 '\\1\\2</a>\\3</a>\\1\\4</a>',
342 # fix div inside inline elements- doBlockLevels won't wrap a line which
343 # contains a div, so fix it up here; replace
344 # div with escaped text
345 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
346 '\\1\\3<div\\5>\\6</div>\\8\\9',
347 # remove empty italic or bold tag pairs, some
348 # introduced by rules above
349 '/<([bi])><\/\\1>/' => '',
352 $text = preg_replace(
353 array_keys( $tidyregs ),
354 array_values( $tidyregs ),
358 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
360 # Information on include size limits, for the benefit of users who try to skirt them
361 if ( max( $this->mIncludeSizes
) > 1000 ) {
362 $max = $this->mOptions
->getMaxIncludeSize();
364 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
365 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
366 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
367 "Maximum: $max bytes\n" .
370 $this->mOutput
->setText( $text );
371 $this->mRevisionId
= $oldRevisionId;
372 wfProfileOut( $fname );
374 return $this->mOutput
;
378 * Recursive parser entry point that can be called from an extension tag
381 function recursiveTagParse( $text ) {
382 wfProfileIn( __METHOD__
);
383 $x =& $this->mStripState
;
384 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
385 $text = $this->strip( $text, $x );
386 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
387 $text = $this->internalParse( $text );
388 wfProfileOut( __METHOD__
);
393 * Expand templates and variables in the text, producing valid, static wikitext.
394 * Also removes comments.
396 function preprocess( $text, $title, $options ) {
397 wfProfileIn( __METHOD__
);
399 $this->setOutputType( OT_PREPROCESS
);
400 $this->mOptions
= $options;
401 $this->mTitle
= $title;
402 $x =& $this->mStripState
;
403 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
404 $text = $this->strip( $text, $x );
405 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
406 if ( $this->mOptions
->getRemoveComments() ) {
407 $text = Sanitizer
::removeHTMLcomments( $text );
409 $text = $this->replaceVariables( $text );
410 $text = $this->unstrip( $text, $x );
411 $text = $this->unstripNowiki( $text, $x );
412 wfProfileOut( __METHOD__
);
417 * Get a random string
422 function getRandomString() {
423 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
426 function &getTitle() { return $this->mTitle
; }
427 function getOptions() { return $this->mOptions
; }
429 function getFunctionLang() {
430 global $wgLang, $wgContLang;
431 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
435 * Replaces all occurrences of HTML-style comments and the given tags
436 * in the text with a random marker and returns teh next text. The output
437 * parameter $matches will be an associative array filled with data in
439 * 'UNIQ-xxxxx' => array(
442 * array( 'param' => 'x' ),
443 * '<element param="x">tag content</element>' ) )
445 * @param $elements list of element names. Comments are always extracted.
446 * @param $text Source text string.
447 * @param $uniq_prefix
452 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
457 $taglist = implode( '|', $elements );
458 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
460 while ( '' != $text ) {
461 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
463 if( count( $p ) < 5 ) {
466 if( count( $p ) > 5 ) {
480 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
481 $stripped .= $marker;
483 if ( $close === '/>' ) {
484 // Empty element tag, <tag />
489 if( $element == '!--' ) {
492 $end = "/(<\\/$element\\s*>)/i";
494 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
496 if( count( $q ) < 3 ) {
497 # No end tag -- let it run out to the end of the text.
506 $matches[$marker] = array( $element,
508 Sanitizer
::decodeTagAttributes( $attributes ),
509 "<$element$attributes$close$content$tail" );
515 * Strips and renders nowiki, pre, math, hiero
516 * If $render is set, performs necessary rendering operations on plugins
517 * Returns the text, and fills an array with data needed in unstrip()
518 * If the $state is already a valid strip state, it adds to the state
520 * @param bool $stripcomments when set, HTML comments <!-- like this -->
521 * will be stripped in addition to other tags. This is important
522 * for section editing, where these comments cause confusion when
523 * counting the sections in the wikisource
525 * @param array dontstrip contains tags which should not be stripped;
526 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
530 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
531 wfProfileIn( __METHOD__
);
532 $render = ($this->mOutputType
== OT_HTML
);
534 $uniq_prefix = $this->mUniqPrefix
;
535 $commentState = array();
537 $elements = array_merge(
538 array( 'nowiki', 'gallery' ),
539 array_keys( $this->mTagHooks
) );
542 $elements[] = 'html';
544 if( $this->mOptions
->getUseTeX() ) {
545 $elements[] = 'math';
548 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
549 foreach ( $elements AS $k => $v ) {
550 if ( !in_array ( $v , $dontstrip ) ) continue;
551 unset ( $elements[$k] );
555 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
557 foreach( $matches as $marker => $data ) {
558 list( $element, $content, $params, $tag ) = $data;
560 $tagName = strtolower( $element );
561 wfProfileIn( __METHOD__
."-render-$tagName" );
565 if( substr( $tag, -3 ) == '-->' ) {
568 // Unclosed comment in input.
569 // Close it so later stripping can remove it
578 // Shouldn't happen otherwise. :)
580 $output = wfEscapeHTMLTagsOnly( $content );
583 $output = MathRenderer
::renderMath( $content );
586 $output = $this->renderImageGallery( $content, $params );
589 if( isset( $this->mTagHooks
[$tagName] ) ) {
590 $output = call_user_func_array( $this->mTagHooks
[$tagName],
591 array( $content, $params, $this ) );
593 throw new MWException( "Invalid call hook $element" );
596 wfProfileOut( __METHOD__
."-render-$tagName" );
598 // Just stripping tags; keep the source
602 // Unstrip the output, because unstrip() is no longer recursive so
603 // it won't do it itself
604 $output = $this->unstrip( $output, $state );
606 if( !$stripcomments && $element == '!--' ) {
607 $commentState[$marker] = $output;
608 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
609 $state['nowiki'][$marker] = $output;
611 $state['general'][$marker] = $output;
615 # Unstrip comments unless explicitly told otherwise.
616 # (The comments are always stripped prior to this point, so as to
617 # not invoke any extension tags / parser hooks contained within
619 if ( !$stripcomments ) {
620 // Put them all back and forget them
621 $text = strtr( $text, $commentState );
624 wfProfileOut( __METHOD__
);
629 * Restores pre, math, and other extensions removed by strip()
631 * always call unstripNoWiki() after this one
634 function unstrip( $text, &$state ) {
635 if ( !isset( $state['general'] ) ) {
639 wfProfileIn( __METHOD__
);
640 # TODO: good candidate for FSS
641 $text = strtr( $text, $state['general'] );
642 wfProfileOut( __METHOD__
);
647 * Always call this after unstrip() to preserve the order
651 function unstripNoWiki( $text, &$state ) {
652 if ( !isset( $state['nowiki'] ) ) {
656 wfProfileIn( __METHOD__
);
657 # TODO: good candidate for FSS
658 $text = strtr( $text, $state['nowiki'] );
659 wfProfileOut( __METHOD__
);
665 * Add an item to the strip state
666 * Returns the unique tag which must be inserted into the stripped text
667 * The tag will be replaced with the original text in unstrip()
671 function insertStripItem( $text, &$state ) {
672 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
676 $state['general'][$rnd] = $text;
681 * Interface with html tidy, used if $wgUseTidy = true.
682 * If tidy isn't able to correct the markup, the original will be
683 * returned in all its glory with a warning comment appended.
685 * Either the external tidy program or the in-process tidy extension
686 * will be used depending on availability. Override the default
687 * $wgTidyInternal setting to disable the internal if it's not working.
689 * @param string $text Hideous HTML input
690 * @return string Corrected HTML output
694 function tidy( $text ) {
695 global $wgTidyInternal;
696 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
697 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
698 '<head><title>test</title></head><body>'.$text.'</body></html>';
699 if( $wgTidyInternal ) {
700 $correctedtext = Parser
::internalTidy( $wrappedtext );
702 $correctedtext = Parser
::externalTidy( $wrappedtext );
704 if( is_null( $correctedtext ) ) {
705 wfDebug( "Tidy error detected!\n" );
706 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
708 return $correctedtext;
712 * Spawn an external HTML tidy process and get corrected markup back from it.
717 function externalTidy( $text ) {
718 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
719 $fname = 'Parser::externalTidy';
720 wfProfileIn( $fname );
725 $descriptorspec = array(
726 0 => array('pipe', 'r'),
727 1 => array('pipe', 'w'),
728 2 => array('file', '/dev/null', 'a')
731 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
732 if (is_resource($process)) {
733 // Theoretically, this style of communication could cause a deadlock
734 // here. If the stdout buffer fills up, then writes to stdin could
735 // block. This doesn't appear to happen with tidy, because tidy only
736 // writes to stdout after it's finished reading from stdin. Search
737 // for tidyParseStdin and tidySaveStdout in console/tidy.c
738 fwrite($pipes[0], $text);
740 while (!feof($pipes[1])) {
741 $cleansource .= fgets($pipes[1], 1024);
744 proc_close($process);
747 wfProfileOut( $fname );
749 if( $cleansource == '' && $text != '') {
750 // Some kind of error happened, so we couldn't get the corrected text.
751 // Just give up; we'll use the source text and append a warning.
759 * Use the HTML tidy PECL extension to use the tidy library in-process,
760 * saving the overhead of spawning a new process. Currently written to
761 * the PHP 4.3.x version of the extension, may not work on PHP 5.
763 * 'pear install tidy' should be able to compile the extension module.
768 function internalTidy( $text ) {
770 $fname = 'Parser::internalTidy';
771 wfProfileIn( $fname );
773 tidy_load_config( $wgTidyConf );
774 tidy_set_encoding( 'utf8' );
775 tidy_parse_string( $text );
777 if( tidy_get_status() == 2 ) {
778 // 2 is magic number for fatal error
779 // http://www.php.net/manual/en/function.tidy-get-status.php
782 $cleansource = tidy_get_output();
784 wfProfileOut( $fname );
789 * parse the wiki syntax used to render tables
793 function doTableStuff ( $t ) {
794 $fname = 'Parser::doTableStuff';
795 wfProfileIn( $fname );
797 $t = explode ( "\n" , $t ) ;
798 $td = array () ; # Is currently a td tag open?
799 $ltd = array () ; # Was it TD or TH?
800 $tr = array () ; # Is currently a tr tag open?
801 $ltr = array () ; # tr attributes
802 $has_opened_tr = array(); # Did this table open a <tr> element?
803 $indent_level = 0; # indent level of the table
804 foreach ( $t AS $k => $x )
807 $fc = substr ( $x , 0 , 1 ) ;
808 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
809 $indent_level = strlen( $matches[1] );
811 $attributes = $this->unstripForHTML( $matches[2] );
813 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
814 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
815 array_push ( $td , false ) ;
816 array_push ( $ltd , '' ) ;
817 array_push ( $tr , false ) ;
818 array_push ( $ltr , '' ) ;
819 array_push ( $has_opened_tr, false );
821 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
822 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
823 $z = "</table>" . substr ( $x , 2);
824 $l = array_pop ( $ltd ) ;
825 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
826 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
827 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
829 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
831 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
832 $x = substr ( $x , 1 ) ;
833 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
835 $l = array_pop ( $ltd ) ;
836 array_pop ( $has_opened_tr );
837 array_push ( $has_opened_tr , true ) ;
838 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
839 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
842 array_push ( $tr , false ) ;
843 array_push ( $td , false ) ;
844 array_push ( $ltd , '' ) ;
845 $attributes = $this->unstripForHTML( $x );
846 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
848 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
850 if ( '|+' == substr ( $x , 0 , 2 ) ) {
852 $x = substr ( $x , 1 ) ;
854 $after = substr ( $x , 1 ) ;
855 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
857 // Split up multiple cells on the same line.
858 // FIXME: This can result in improper nesting of tags processed
859 // by earlier parser steps, but should avoid splitting up eg
860 // attribute values containing literal "||".
861 $after = wfExplodeMarkup( '||', $after );
865 # Loop through each table cell
866 foreach ( $after AS $theline )
871 $tra = array_pop ( $ltr ) ;
872 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
873 array_push ( $tr , true ) ;
874 array_push ( $ltr , '' ) ;
875 array_pop ( $has_opened_tr );
876 array_push ( $has_opened_tr , true ) ;
879 $l = array_pop ( $ltd ) ;
880 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
881 if ( $fc == '|' ) $l = 'td' ;
882 else if ( $fc == '!' ) $l = 'th' ;
883 else if ( $fc == '+' ) $l = 'caption' ;
885 array_push ( $ltd , $l ) ;
888 $y = explode ( '|' , $theline , 2 ) ;
889 # Note that a '|' inside an invalid link should not
890 # be mistaken as delimiting cell parameters
891 if ( strpos( $y[0], '[[' ) !== false ) {
892 $y = array ($theline);
894 if ( count ( $y ) == 1 )
895 $y = "{$z}<{$l}>{$y[0]}" ;
897 $attributes = $this->unstripForHTML( $y[0] );
898 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
901 array_push ( $td , true ) ;
906 # Closing open td, tr && table
907 while ( count ( $td ) > 0 )
909 $l = array_pop ( $ltd ) ;
910 if ( array_pop ( $td ) ) $t[] = '</td>' ;
911 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
912 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
916 $t = implode ( "\n" , $t ) ;
917 # special case: don't return empty table
918 if($t == "<table>\n<tr><td></td></tr>\n</table>")
920 wfProfileOut( $fname );
925 * Helper function for parse() that transforms wiki markup into
926 * HTML. Only called for $mOutputType == OT_HTML.
930 function internalParse( $text ) {
933 $fname = 'Parser::internalParse';
934 wfProfileIn( $fname );
936 # Hook to suspend the parser in this state
937 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
938 wfProfileOut( $fname );
942 # Remove <noinclude> tags and <includeonly> sections
943 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
944 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
945 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
947 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
949 $text = $this->replaceVariables( $text, $args );
951 // Tables need to come after variable replacement for things to work
952 // properly; putting them before other transformations should keep
953 // exciting things like link expansions from showing up in surprising
955 $text = $this->doTableStuff( $text );
957 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
959 $text = $this->stripToc( $text );
960 $this->stripNoGallery( $text );
961 $text = $this->doHeadings( $text );
962 if($this->mOptions
->getUseDynamicDates()) {
963 $df =& DateFormatter
::getInstance();
964 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
966 $text = $this->doAllQuotes( $text );
967 $text = $this->replaceInternalLinks( $text );
968 $text = $this->replaceExternalLinks( $text );
970 # replaceInternalLinks may sometimes leave behind
971 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
972 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
974 $text = $this->doMagicLinks( $text );
975 $text = $this->formatHeadings( $text, $isMain );
977 wfProfileOut( $fname );
982 * Replace special strings like "ISBN xxx" and "RFC xxx" with
983 * magic external links.
987 function &doMagicLinks( &$text ) {
988 wfProfileIn( __METHOD__
);
989 $text = preg_replace_callback(
991 <a.*?</a> | # Skip link text
992 <.*?> | # Skip stuff inside HTML elements
993 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
994 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
995 )!x', array( &$this, 'magicLinkCallback' ), $text );
996 wfProfileOut( __METHOD__
);
1000 function magicLinkCallback( $m ) {
1001 if ( substr( $m[0], 0, 1 ) == '<' ) {
1004 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1006 $num = strtr( $isbn, array(
1011 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
1012 $text = '<a href="' .
1013 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1014 "\" class=\"internal\">ISBN $isbn</a>";
1016 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1020 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1022 $urlmsg = 'pubmedurl';
1025 throw new MWException( __METHOD__
.': unrecognised match type "' .
1026 substr($m[0], 0, 20 ) . '"' );
1029 $url = wfMsg( $urlmsg, $id);
1030 $sk =& $this->mOptions
->getSkin();
1031 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1032 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1038 * Parse headers and return html
1042 function doHeadings( $text ) {
1043 $fname = 'Parser::doHeadings';
1044 wfProfileIn( $fname );
1045 for ( $i = 6; $i >= 1; --$i ) {
1046 $h = str_repeat( '=', $i );
1047 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1048 "<h{$i}>\\1</h{$i}>\\2", $text );
1050 wfProfileOut( $fname );
1055 * Replace single quotes with HTML markup
1057 * @return string the altered text
1059 function doAllQuotes( $text ) {
1060 $fname = 'Parser::doAllQuotes';
1061 wfProfileIn( $fname );
1063 $lines = explode( "\n", $text );
1064 foreach ( $lines as $line ) {
1065 $outtext .= $this->doQuotes ( $line ) . "\n";
1067 $outtext = substr($outtext, 0,-1);
1068 wfProfileOut( $fname );
1073 * Helper function for doAllQuotes()
1076 function doQuotes( $text ) {
1077 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1078 if ( count( $arr ) == 1 )
1082 # First, do some preliminary work. This may shift some apostrophes from
1083 # being mark-up to being text. It also counts the number of occurrences
1084 # of bold and italics mark-ups.
1088 foreach ( $arr as $r )
1090 if ( ( $i %
2 ) == 1 )
1092 # If there are ever four apostrophes, assume the first is supposed to
1093 # be text, and the remaining three constitute mark-up for bold text.
1094 if ( strlen( $arr[$i] ) == 4 )
1099 # If there are more than 5 apostrophes in a row, assume they're all
1100 # text except for the last 5.
1101 else if ( strlen( $arr[$i] ) > 5 )
1103 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1106 # Count the number of occurrences of bold and italics mark-ups.
1107 # We are not counting sequences of five apostrophes.
1108 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1109 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1110 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1115 # If there is an odd number of both bold and italics, it is likely
1116 # that one of the bold ones was meant to be an apostrophe followed
1117 # by italics. Which one we cannot know for certain, but it is more
1118 # likely to be one that has a single-letter word before it.
1119 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1122 $firstsingleletterword = -1;
1123 $firstmultiletterword = -1;
1125 foreach ( $arr as $r )
1127 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1129 $x1 = substr ($arr[$i-1], -1);
1130 $x2 = substr ($arr[$i-1], -2, 1);
1132 if ($firstspace == -1) $firstspace = $i;
1133 } else if ($x2 == ' ') {
1134 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1136 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1142 # If there is a single-letter word, use it!
1143 if ($firstsingleletterword > -1)
1145 $arr [ $firstsingleletterword ] = "''";
1146 $arr [ $firstsingleletterword-1 ] .= "'";
1148 # If not, but there's a multi-letter word, use that one.
1149 else if ($firstmultiletterword > -1)
1151 $arr [ $firstmultiletterword ] = "''";
1152 $arr [ $firstmultiletterword-1 ] .= "'";
1154 # ... otherwise use the first one that has neither.
1155 # (notice that it is possible for all three to be -1 if, for example,
1156 # there is only one pentuple-apostrophe in the line)
1157 else if ($firstspace > -1)
1159 $arr [ $firstspace ] = "''";
1160 $arr [ $firstspace-1 ] .= "'";
1164 # Now let's actually convert our apostrophic mush to HTML!
1169 foreach ($arr as $r)
1173 if ($state == 'both')
1180 if (strlen ($r) == 2)
1183 { $output .= '</i>'; $state = ''; }
1184 else if ($state == 'bi')
1185 { $output .= '</i>'; $state = 'b'; }
1186 else if ($state == 'ib')
1187 { $output .= '</b></i><b>'; $state = 'b'; }
1188 else if ($state == 'both')
1189 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1190 else # $state can be 'b' or ''
1191 { $output .= '<i>'; $state .= 'i'; }
1193 else if (strlen ($r) == 3)
1196 { $output .= '</b>'; $state = ''; }
1197 else if ($state == 'bi')
1198 { $output .= '</i></b><i>'; $state = 'i'; }
1199 else if ($state == 'ib')
1200 { $output .= '</b>'; $state = 'i'; }
1201 else if ($state == 'both')
1202 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1203 else # $state can be 'i' or ''
1204 { $output .= '<b>'; $state .= 'b'; }
1206 else if (strlen ($r) == 5)
1209 { $output .= '</b><i>'; $state = 'i'; }
1210 else if ($state == 'i')
1211 { $output .= '</i><b>'; $state = 'b'; }
1212 else if ($state == 'bi')
1213 { $output .= '</i></b>'; $state = ''; }
1214 else if ($state == 'ib')
1215 { $output .= '</b></i>'; $state = ''; }
1216 else if ($state == 'both')
1217 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1218 else # ($state == '')
1219 { $buffer = ''; $state = 'both'; }
1224 # Now close all remaining tags. Notice that the order is important.
1225 if ($state == 'b' ||
$state == 'ib')
1227 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1231 if ($state == 'both')
1232 $output .= '<b><i>'.$buffer.'</i></b>';
1238 * Replace external links
1240 * Note: this is all very hackish and the order of execution matters a lot.
1241 * Make sure to run maintenance/parserTests.php if you change this code.
1245 function replaceExternalLinks( $text ) {
1247 $fname = 'Parser::replaceExternalLinks';
1248 wfProfileIn( $fname );
1250 $sk =& $this->mOptions
->getSkin();
1252 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1254 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1257 while ( $i<count( $bits ) ) {
1259 $protocol = $bits[$i++
];
1260 $text = $bits[$i++
];
1261 $trail = $bits[$i++
];
1263 # The characters '<' and '>' (which were escaped by
1264 # removeHTMLtags()) should not be included in
1265 # URLs, per RFC 2396.
1266 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1267 $text = substr($url, $m2[0][1]) . ' ' . $text;
1268 $url = substr($url, 0, $m2[0][1]);
1271 # If the link text is an image URL, replace it with an <img> tag
1272 # This happened by accident in the original parser, but some people used it extensively
1273 $img = $this->maybeMakeExternalImage( $text );
1274 if ( $img !== false ) {
1280 # Set linktype for CSS - if URL==text, link is essentially free
1281 $linktype = ($text == $url) ?
'free' : 'text';
1283 # No link text, e.g. [http://domain.tld/some.link]
1284 if ( $text == '' ) {
1285 # Autonumber if allowed. See bug #5918
1286 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1287 $text = '[' . ++
$this->mAutonumber
. ']';
1288 $linktype = 'autonumber';
1290 # Otherwise just use the URL
1291 $text = htmlspecialchars( $url );
1295 # Have link text, e.g. [http://domain.tld/some.link text]s
1297 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1300 $text = $wgContLang->markNoConversion($text);
1302 $url = Sanitizer
::cleanUrl( $url );
1304 # Process the trail (i.e. everything after this link up until start of the next link),
1305 # replacing any non-bracketed links
1306 $trail = $this->replaceFreeExternalLinks( $trail );
1308 # Use the encoded URL
1309 # This means that users can paste URLs directly into the text
1310 # Funny characters like ö aren't valid in URLs anyway
1311 # This was changed in August 2004
1312 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1314 # Register link in the output object.
1315 # Replace unnecessary URL escape codes with the referenced character
1316 # This prevents spammers from hiding links from the filters
1317 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1318 $this->mOutput
->addExternalLink( $pasteurized );
1321 wfProfileOut( $fname );
1326 * Replace anything that looks like a URL with a link
1329 function replaceFreeExternalLinks( $text ) {
1331 $fname = 'Parser::replaceFreeExternalLinks';
1332 wfProfileIn( $fname );
1334 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1335 $s = array_shift( $bits );
1338 $sk =& $this->mOptions
->getSkin();
1340 while ( $i < count( $bits ) ){
1341 $protocol = $bits[$i++
];
1342 $remainder = $bits[$i++
];
1344 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1345 # Found some characters after the protocol that look promising
1346 $url = $protocol . $m[1];
1349 # special case: handle urls as url args:
1350 # http://www.example.com/foo?=http://www.example.com/bar
1351 if(strlen($trail) == 0 &&
1353 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1354 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1357 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1362 # The characters '<' and '>' (which were escaped by
1363 # removeHTMLtags()) should not be included in
1364 # URLs, per RFC 2396.
1365 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1366 $trail = substr($url, $m2[0][1]) . $trail;
1367 $url = substr($url, 0, $m2[0][1]);
1370 # Move trailing punctuation to $trail
1372 # If there is no left bracket, then consider right brackets fair game too
1373 if ( strpos( $url, '(' ) === false ) {
1377 $numSepChars = strspn( strrev( $url ), $sep );
1378 if ( $numSepChars ) {
1379 $trail = substr( $url, -$numSepChars ) . $trail;
1380 $url = substr( $url, 0, -$numSepChars );
1383 $url = Sanitizer
::cleanUrl( $url );
1385 # Is this an external image?
1386 $text = $this->maybeMakeExternalImage( $url );
1387 if ( $text === false ) {
1388 # Not an image, make a link
1389 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1390 # Register it in the output object...
1391 # Replace unnecessary URL escape codes with their equivalent characters
1392 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1393 $this->mOutput
->addExternalLink( $pasteurized );
1395 $s .= $text . $trail;
1397 $s .= $protocol . $remainder;
1400 wfProfileOut( $fname );
1405 * Replace unusual URL escape codes with their equivalent characters
1409 * @fixme This can merge genuinely required bits in the path or query string,
1410 * breaking legit URLs. A proper fix would treat the various parts of
1411 * the URL differently; as a workaround, just use the output for
1412 * statistical records, not for actual linking/output.
1414 static function replaceUnusualEscapes( $url ) {
1415 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1416 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1420 * Callback function used in replaceUnusualEscapes().
1421 * Replaces unusual URL escape codes with their equivalent character
1425 private static function replaceUnusualEscapesCallback( $matches ) {
1426 $char = urldecode( $matches[0] );
1427 $ord = ord( $char );
1428 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1429 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1430 // No, shouldn't be escaped
1433 // Yes, leave it escaped
1439 * make an image if it's allowed, either through the global
1440 * option or through the exception
1443 function maybeMakeExternalImage( $url ) {
1444 $sk =& $this->mOptions
->getSkin();
1445 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1446 $imagesexception = !empty($imagesfrom);
1448 if ( $this->mOptions
->getAllowExternalImages()
1449 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1450 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1452 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1459 * Process [[ ]] wikilinks
1463 function replaceInternalLinks( $s ) {
1465 static $fname = 'Parser::replaceInternalLinks' ;
1467 wfProfileIn( $fname );
1469 wfProfileIn( $fname.'-setup' );
1471 # the % is needed to support urlencoded titles as well
1472 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1474 $sk =& $this->mOptions
->getSkin();
1476 #split the entire text string on occurences of [[
1477 $a = explode( '[[', ' ' . $s );
1478 #get the first element (all text up to first [[), and remove the space we added
1479 $s = array_shift( $a );
1480 $s = substr( $s, 1 );
1482 # Match a link having the form [[namespace:link|alternate]]trail
1484 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1485 # Match cases where there is no "]]", which might still be images
1486 static $e1_img = FALSE;
1487 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1488 # Match the end of a line for a word that's not followed by whitespace,
1489 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1490 $e2 = wfMsgForContent( 'linkprefix' );
1492 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1494 if( is_null( $this->mTitle
) ) {
1495 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1497 $nottalk = !$this->mTitle
->isTalkPage();
1499 if ( $useLinkPrefixExtension ) {
1500 if ( preg_match( $e2, $s, $m ) ) {
1501 $first_prefix = $m[2];
1503 $first_prefix = false;
1509 $selflink = $this->mTitle
->getPrefixedText();
1510 $useSubpages = $this->areSubpagesAllowed();
1511 wfProfileOut( $fname.'-setup' );
1513 # Loop for each link
1514 for ($k = 0; isset( $a[$k] ); $k++
) {
1516 if ( $useLinkPrefixExtension ) {
1517 wfProfileIn( $fname.'-prefixhandling' );
1518 if ( preg_match( $e2, $s, $m ) ) {
1526 $prefix = $first_prefix;
1527 $first_prefix = false;
1529 wfProfileOut( $fname.'-prefixhandling' );
1532 $might_be_img = false;
1534 wfProfileIn( "$fname-e1" );
1535 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1537 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1538 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1539 # the real problem is with the $e1 regex
1542 # Still some problems for cases where the ] is meant to be outside punctuation,
1543 # and no image is in sight. See bug 2095.
1546 substr( $m[3], 0, 1 ) === ']' &&
1547 strpos($text, '[') !== false
1550 $text .= ']'; # so that replaceExternalLinks($text) works later
1551 $m[3] = substr( $m[3], 1 );
1553 # fix up urlencoded title texts
1554 if( strpos( $m[1], '%' ) !== false ) {
1555 # Should anchors '#' also be rejected?
1556 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1559 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1560 $might_be_img = true;
1562 if ( strpos( $m[1], '%' ) !== false ) {
1563 $m[1] = urldecode($m[1]);
1566 } else { # Invalid form; output directly
1567 $s .= $prefix . '[[' . $line ;
1568 wfProfileOut( "$fname-e1" );
1571 wfProfileOut( "$fname-e1" );
1572 wfProfileIn( "$fname-misc" );
1574 # Don't allow internal links to pages containing
1575 # PROTO: where PROTO is a valid URL protocol; these
1576 # should be external links.
1577 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1578 $s .= $prefix . '[[' . $line ;
1582 # Make subpage if necessary
1583 if( $useSubpages ) {
1584 $link = $this->maybeDoSubpageLink( $m[1], $text );
1589 $noforce = (substr($m[1], 0, 1) != ':');
1591 # Strip off leading ':'
1592 $link = substr($link, 1);
1595 wfProfileOut( "$fname-misc" );
1596 wfProfileIn( "$fname-title" );
1597 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1599 $s .= $prefix . '[[' . $line;
1600 wfProfileOut( "$fname-title" );
1604 $ns = $nt->getNamespace();
1605 $iw = $nt->getInterWiki();
1606 wfProfileOut( "$fname-title" );
1608 if ($might_be_img) { # if this is actually an invalid link
1609 wfProfileIn( "$fname-might_be_img" );
1610 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1612 while (isset ($a[$k+
1]) ) {
1613 #look at the next 'line' to see if we can close it there
1614 $spliced = array_splice( $a, $k +
1, 1 );
1615 $next_line = array_shift( $spliced );
1616 $m = explode( ']]', $next_line, 3 );
1617 if ( count( $m ) == 3 ) {
1618 # the first ]] closes the inner link, the second the image
1620 $text .= "[[{$m[0]}]]{$m[1]}";
1623 } elseif ( count( $m ) == 2 ) {
1624 #if there's exactly one ]] that's fine, we'll keep looking
1625 $text .= "[[{$m[0]}]]{$m[1]}";
1627 #if $next_line is invalid too, we need look no further
1628 $text .= '[[' . $next_line;
1633 # we couldn't find the end of this imageLink, so output it raw
1634 #but don't ignore what might be perfectly normal links in the text we've examined
1635 $text = $this->replaceInternalLinks($text);
1636 $s .= "{$prefix}[[$link|$text";
1637 # note: no $trail, because without an end, there *is* no trail
1638 wfProfileOut( "$fname-might_be_img" );
1641 } else { #it's not an image, so output it raw
1642 $s .= "{$prefix}[[$link|$text";
1643 # note: no $trail, because without an end, there *is* no trail
1644 wfProfileOut( "$fname-might_be_img" );
1647 wfProfileOut( "$fname-might_be_img" );
1650 $wasblank = ( '' == $text );
1651 if( $wasblank ) $text = $link;
1653 # Link not escaped by : , create the various objects
1657 wfProfileIn( "$fname-interwiki" );
1658 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1659 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1660 $s = rtrim($s . "\n");
1661 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1662 wfProfileOut( "$fname-interwiki" );
1665 wfProfileOut( "$fname-interwiki" );
1667 if ( $ns == NS_IMAGE
) {
1668 wfProfileIn( "$fname-image" );
1669 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1670 # recursively parse links inside the image caption
1671 # actually, this will parse them in any other parameters, too,
1672 # but it might be hard to fix that, and it doesn't matter ATM
1673 $text = $this->replaceExternalLinks($text);
1674 $text = $this->replaceInternalLinks($text);
1676 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1677 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1678 $this->mOutput
->addImage( $nt->getDBkey() );
1680 wfProfileOut( "$fname-image" );
1683 # We still need to record the image's presence on the page
1684 $this->mOutput
->addImage( $nt->getDBkey() );
1686 wfProfileOut( "$fname-image" );
1690 if ( $ns == NS_CATEGORY
) {
1691 wfProfileIn( "$fname-category" );
1692 $s = rtrim($s . "\n"); # bug 87
1695 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1696 $sortkey = $this->mTitle
->getText();
1698 $sortkey = $this->mTitle
->getPrefixedText();
1703 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1704 $sortkey = str_replace( "\n", '', $sortkey );
1705 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1706 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1709 * Strip the whitespace Category links produce, see bug 87
1710 * @todo We might want to use trim($tmp, "\n") here.
1712 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1714 wfProfileOut( "$fname-category" );
1719 if( ( $nt->getPrefixedText() === $selflink ) &&
1720 ( $nt->getFragment() === '' ) ) {
1721 # Self-links are handled specially; generally de-link and change to bold.
1722 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1726 # Special and Media are pseudo-namespaces; no pages actually exist in them
1727 if( $ns == NS_MEDIA
) {
1728 $link = $sk->makeMediaLinkObj( $nt, $text );
1729 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1730 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1731 $this->mOutput
->addImage( $nt->getDBkey() );
1733 } elseif( $ns == NS_SPECIAL
) {
1734 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1736 } elseif( $ns == NS_IMAGE
) {
1737 $img = new Image( $nt );
1738 if( $img->exists() ) {
1739 // Force a blue link if the file exists; may be a remote
1740 // upload on the shared repository, and we want to see its
1741 // auto-generated page.
1742 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1743 $this->mOutput
->addLink( $nt );
1747 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1749 wfProfileOut( $fname );
1754 * Make a link placeholder. The text returned can be later resolved to a real link with
1755 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1756 * parsing of interwiki links, and secondly to allow all existence checks and
1757 * article length checks (for stub links) to be bundled into a single query.
1760 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1761 wfProfileIn( __METHOD__
);
1762 if ( ! is_object($nt) ) {
1764 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1766 # Separate the link trail from the rest of the link
1767 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1769 if ( $nt->isExternal() ) {
1770 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1771 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1772 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1774 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1775 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1776 $this->mLinkHolders
['queries'][] = $query;
1777 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1778 $this->mLinkHolders
['titles'][] = $nt;
1780 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1783 wfProfileOut( __METHOD__
);
1788 * Render a forced-blue link inline; protect against double expansion of
1789 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1790 * Since this little disaster has to split off the trail text to avoid
1791 * breaking URLs in the following text without breaking trails on the
1792 * wiki links, it's been made into a horrible function.
1795 * @param string $text
1796 * @param string $query
1797 * @param string $trail
1798 * @param string $prefix
1799 * @return string HTML-wikitext mix oh yuck
1801 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1802 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1803 $sk =& $this->mOptions
->getSkin();
1804 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1805 return $this->armorLinks( $link ) . $trail;
1809 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1810 * going to go through further parsing steps before inline URL expansion.
1812 * In particular this is important when using action=render, which causes
1813 * full URLs to be included.
1815 * Oh man I hate our multi-layer parser!
1817 * @param string more-or-less HTML
1818 * @return string less-or-more HTML with NOPARSE bits
1820 function armorLinks( $text ) {
1821 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1822 "{$this->mUniqPrefix}NOPARSE$1", $text );
1826 * Return true if subpage links should be expanded on this page.
1829 function areSubpagesAllowed() {
1830 # Some namespaces don't allow subpages
1831 global $wgNamespacesWithSubpages;
1832 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1836 * Handle link to subpage if necessary
1837 * @param string $target the source of the link
1838 * @param string &$text the link text, modified as necessary
1839 * @return string the full name of the link
1842 function maybeDoSubpageLink($target, &$text) {
1845 # :Foobar -- override special treatment of prefix (images, language links)
1846 # /Foobar -- convert to CurrentPage/Foobar
1847 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1848 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1849 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1851 $fname = 'Parser::maybeDoSubpageLink';
1852 wfProfileIn( $fname );
1853 $ret = $target; # default return value is no change
1855 # Some namespaces don't allow subpages,
1856 # so only perform processing if subpages are allowed
1857 if( $this->areSubpagesAllowed() ) {
1858 # Look at the first character
1859 if( $target != '' && $target{0} == '/' ) {
1860 # / at end means we don't want the slash to be shown
1861 if( substr( $target, -1, 1 ) == '/' ) {
1862 $target = substr( $target, 1, -1 );
1865 $noslash = substr( $target, 1 );
1868 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1869 if( '' === $text ) {
1871 } # this might be changed for ugliness reasons
1873 # check for .. subpage backlinks
1875 $nodotdot = $target;
1876 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1878 $nodotdot = substr( $nodotdot, 3 );
1880 if($dotdotcount > 0) {
1881 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1882 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1883 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1884 # / at the end means don't show full path
1885 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1886 $nodotdot = substr( $nodotdot, 0, -1 );
1887 if( '' === $text ) {
1891 $nodotdot = trim( $nodotdot );
1892 if( $nodotdot != '' ) {
1893 $ret .= '/' . $nodotdot;
1900 wfProfileOut( $fname );
1905 * Used by doBlockLevels()
1908 /* private */ function closeParagraph() {
1910 if ( '' != $this->mLastSection
) {
1911 $result = '</' . $this->mLastSection
. ">\n";
1913 $this->mInPre
= false;
1914 $this->mLastSection
= '';
1917 # getCommon() returns the length of the longest common substring
1918 # of both arguments, starting at the beginning of both.
1920 /* private */ function getCommon( $st1, $st2 ) {
1921 $fl = strlen( $st1 );
1922 $shorter = strlen( $st2 );
1923 if ( $fl < $shorter ) { $shorter = $fl; }
1925 for ( $i = 0; $i < $shorter; ++
$i ) {
1926 if ( $st1{$i} != $st2{$i} ) { break; }
1930 # These next three functions open, continue, and close the list
1931 # element appropriate to the prefix character passed into them.
1933 /* private */ function openList( $char ) {
1934 $result = $this->closeParagraph();
1936 if ( '*' == $char ) { $result .= '<ul><li>'; }
1937 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1938 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1939 else if ( ';' == $char ) {
1940 $result .= '<dl><dt>';
1941 $this->mDTopen
= true;
1943 else { $result = '<!-- ERR 1 -->'; }
1948 /* private */ function nextItem( $char ) {
1949 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1950 else if ( ':' == $char ||
';' == $char ) {
1952 if ( $this->mDTopen
) { $close = '</dt>'; }
1953 if ( ';' == $char ) {
1954 $this->mDTopen
= true;
1955 return $close . '<dt>';
1957 $this->mDTopen
= false;
1958 return $close . '<dd>';
1961 return '<!-- ERR 2 -->';
1964 /* private */ function closeList( $char ) {
1965 if ( '*' == $char ) { $text = '</li></ul>'; }
1966 else if ( '#' == $char ) { $text = '</li></ol>'; }
1967 else if ( ':' == $char ) {
1968 if ( $this->mDTopen
) {
1969 $this->mDTopen
= false;
1970 $text = '</dt></dl>';
1972 $text = '</dd></dl>';
1975 else { return '<!-- ERR 3 -->'; }
1981 * Make lists from lines starting with ':', '*', '#', etc.
1984 * @return string the lists rendered as HTML
1986 function doBlockLevels( $text, $linestart ) {
1987 $fname = 'Parser::doBlockLevels';
1988 wfProfileIn( $fname );
1990 # Parsing through the text line by line. The main thing
1991 # happening here is handling of block-level elements p, pre,
1992 # and making lists from lines starting with * # : etc.
1994 $textLines = explode( "\n", $text );
1996 $lastPrefix = $output = '';
1997 $this->mDTopen
= $inBlockElem = false;
1999 $paragraphStack = false;
2001 if ( !$linestart ) {
2002 $output .= array_shift( $textLines );
2004 foreach ( $textLines as $oLine ) {
2005 $lastPrefixLength = strlen( $lastPrefix );
2006 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2007 $preOpenMatch = preg_match('/<pre/i', $oLine );
2008 if ( !$this->mInPre
) {
2009 # Multiple prefixes may abut each other for nested lists.
2010 $prefixLength = strspn( $oLine, '*#:;' );
2011 $pref = substr( $oLine, 0, $prefixLength );
2014 $pref2 = str_replace( ';', ':', $pref );
2015 $t = substr( $oLine, $prefixLength );
2016 $this->mInPre
= !empty($preOpenMatch);
2018 # Don't interpret any other prefixes in preformatted text
2020 $pref = $pref2 = '';
2025 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2026 # Same as the last item, so no need to deal with nesting or opening stuff
2027 $output .= $this->nextItem( substr( $pref, -1 ) );
2028 $paragraphStack = false;
2030 if ( substr( $pref, -1 ) == ';') {
2031 # The one nasty exception: definition lists work like this:
2032 # ; title : definition text
2033 # So we check for : in the remainder text to split up the
2034 # title and definition, without b0rking links.
2036 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2038 $output .= $term . $this->nextItem( ':' );
2041 } elseif( $prefixLength ||
$lastPrefixLength ) {
2042 # Either open or close a level...
2043 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2044 $paragraphStack = false;
2046 while( $commonPrefixLength < $lastPrefixLength ) {
2047 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2048 --$lastPrefixLength;
2050 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2051 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2053 while ( $prefixLength > $commonPrefixLength ) {
2054 $char = substr( $pref, $commonPrefixLength, 1 );
2055 $output .= $this->openList( $char );
2057 if ( ';' == $char ) {
2058 # FIXME: This is dupe of code above
2059 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2061 $output .= $term . $this->nextItem( ':' );
2064 ++
$commonPrefixLength;
2066 $lastPrefix = $pref2;
2068 if( 0 == $prefixLength ) {
2069 wfProfileIn( "$fname-paragraph" );
2070 # No prefix (not in list)--go to paragraph mode
2071 // XXX: use a stack for nestable elements like span, table and div
2072 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2073 $closematch = preg_match(
2074 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2075 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2076 if ( $openmatch or $closematch ) {
2077 $paragraphStack = false;
2078 #Â TODO bug 5718: paragraph closed
2079 $output .= $this->closeParagraph();
2080 if ( $preOpenMatch and !$preCloseMatch ) {
2081 $this->mInPre
= true;
2083 if ( $closematch ) {
2084 $inBlockElem = false;
2086 $inBlockElem = true;
2088 } else if ( !$inBlockElem && !$this->mInPre
) {
2089 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2091 if ($this->mLastSection
!= 'pre') {
2092 $paragraphStack = false;
2093 $output .= $this->closeParagraph().'<pre>';
2094 $this->mLastSection
= 'pre';
2096 $t = substr( $t, 1 );
2099 if ( '' == trim($t) ) {
2100 if ( $paragraphStack ) {
2101 $output .= $paragraphStack.'<br />';
2102 $paragraphStack = false;
2103 $this->mLastSection
= 'p';
2105 if ($this->mLastSection
!= 'p' ) {
2106 $output .= $this->closeParagraph();
2107 $this->mLastSection
= '';
2108 $paragraphStack = '<p>';
2110 $paragraphStack = '</p><p>';
2114 if ( $paragraphStack ) {
2115 $output .= $paragraphStack;
2116 $paragraphStack = false;
2117 $this->mLastSection
= 'p';
2118 } else if ($this->mLastSection
!= 'p') {
2119 $output .= $this->closeParagraph().'<p>';
2120 $this->mLastSection
= 'p';
2125 wfProfileOut( "$fname-paragraph" );
2127 // somewhere above we forget to get out of pre block (bug 785)
2128 if($preCloseMatch && $this->mInPre
) {
2129 $this->mInPre
= false;
2131 if ($paragraphStack === false) {
2135 while ( $prefixLength ) {
2136 $output .= $this->closeList( $pref2{$prefixLength-1} );
2139 if ( '' != $this->mLastSection
) {
2140 $output .= '</' . $this->mLastSection
. '>';
2141 $this->mLastSection
= '';
2144 wfProfileOut( $fname );
2149 * Split up a string on ':', ignoring any occurences inside tags
2150 * to prevent illegal overlapping.
2151 * @param string $str the string to split
2152 * @param string &$before set to everything before the ':'
2153 * @param string &$after set to everything after the ':'
2154 * return string the position of the ':', or false if none found
2156 function findColonNoLinks($str, &$before, &$after) {
2157 $fname = 'Parser::findColonNoLinks';
2158 wfProfileIn( $fname );
2160 $pos = strpos( $str, ':' );
2161 if( $pos === false ) {
2163 wfProfileOut( $fname );
2167 $lt = strpos( $str, '<' );
2168 if( $lt === false ||
$lt > $pos ) {
2169 // Easy; no tag nesting to worry about
2170 $before = substr( $str, 0, $pos );
2171 $after = substr( $str, $pos+
1 );
2172 wfProfileOut( $fname );
2176 // Ugly state machine to walk through avoiding tags.
2177 $state = MW_COLON_STATE_TEXT
;
2179 $len = strlen( $str );
2180 for( $i = 0; $i < $len; $i++
) {
2184 // (Using the number is a performance hack for common cases)
2185 case 0: // MW_COLON_STATE_TEXT:
2188 // Could be either a <start> tag or an </end> tag
2189 $state = MW_COLON_STATE_TAGSTART
;
2194 $before = substr( $str, 0, $i );
2195 $after = substr( $str, $i +
1 );
2196 wfProfileOut( $fname );
2199 // Embedded in a tag; don't break it.
2202 // Skip ahead looking for something interesting
2203 $colon = strpos( $str, ':', $i );
2204 if( $colon === false ) {
2205 // Nothing else interesting
2206 wfProfileOut( $fname );
2209 $lt = strpos( $str, '<', $i );
2210 if( $stack === 0 ) {
2211 if( $lt === false ||
$colon < $lt ) {
2213 $before = substr( $str, 0, $colon );
2214 $after = substr( $str, $colon +
1 );
2215 wfProfileOut( $fname );
2219 if( $lt === false ) {
2220 // Nothing else interesting to find; abort!
2221 // We're nested, but there's no close tags left. Abort!
2224 // Skip ahead to next tag start
2226 $state = MW_COLON_STATE_TAGSTART
;
2229 case 1: // MW_COLON_STATE_TAG:
2234 $state = MW_COLON_STATE_TEXT
;
2237 // Slash may be followed by >?
2238 $state = MW_COLON_STATE_TAGSLASH
;
2244 case 2: // MW_COLON_STATE_TAGSTART:
2247 $state = MW_COLON_STATE_CLOSETAG
;
2250 $state = MW_COLON_STATE_COMMENT
;
2253 // Illegal early close? This shouldn't happen D:
2254 $state = MW_COLON_STATE_TEXT
;
2257 $state = MW_COLON_STATE_TAG
;
2260 case 3: // MW_COLON_STATE_CLOSETAG:
2265 wfDebug( "Invalid input in $fname; too many close tags\n" );
2266 wfProfileOut( $fname );
2269 $state = MW_COLON_STATE_TEXT
;
2272 case MW_COLON_STATE_TAGSLASH
:
2274 // Yes, a self-closed tag <blah/>
2275 $state = MW_COLON_STATE_TEXT
;
2277 // Probably we're jumping the gun, and this is an attribute
2278 $state = MW_COLON_STATE_TAG
;
2281 case 5: // MW_COLON_STATE_COMMENT:
2283 $state = MW_COLON_STATE_COMMENTDASH
;
2286 case MW_COLON_STATE_COMMENTDASH
:
2288 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2290 $state = MW_COLON_STATE_COMMENT
;
2293 case MW_COLON_STATE_COMMENTDASHDASH
:
2295 $state = MW_COLON_STATE_TEXT
;
2297 $state = MW_COLON_STATE_COMMENT
;
2301 throw new MWException( "State machine error in $fname" );
2305 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2308 wfProfileOut( $fname );
2313 * Return value of a magic variable (like PAGENAME)
2317 function getVariableValue( $index ) {
2318 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2321 * Some of these require message or data lookups and can be
2322 * expensive to check many times.
2324 static $varCache = array();
2325 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2326 if ( isset( $varCache[$index] ) )
2327 return $varCache[$index];
2330 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2333 global $wgLocaltimezone;
2334 if ( isset( $wgLocaltimezone ) ) {
2335 $oldtz = getenv( 'TZ' );
2336 putenv( 'TZ='.$wgLocaltimezone );
2338 $localTimestamp = date( 'YmdHis', $ts );
2339 $localMonth = date( 'm', $ts );
2340 $localMonthName = date( 'n', $ts );
2341 $localDay = date( 'j', $ts );
2342 $localDay2 = date( 'd', $ts );
2343 $localDayOfWeek = date( 'w', $ts );
2344 $localWeek = date( 'W', $ts );
2345 $localYear = date( 'Y', $ts );
2346 $localHour = date( 'H', $ts );
2347 if ( isset( $wgLocaltimezone ) ) {
2348 putenv( 'TZ='.$oldtz );
2352 case 'currentmonth':
2353 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2354 case 'currentmonthname':
2355 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2356 case 'currentmonthnamegen':
2357 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2358 case 'currentmonthabbrev':
2359 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2361 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2363 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2365 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2366 case 'localmonthname':
2367 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2368 case 'localmonthnamegen':
2369 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2370 case 'localmonthabbrev':
2371 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2373 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2375 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2377 return $this->mTitle
->getText();
2379 return $this->mTitle
->getPartialURL();
2380 case 'fullpagename':
2381 return $this->mTitle
->getPrefixedText();
2382 case 'fullpagenamee':
2383 return $this->mTitle
->getPrefixedURL();
2385 return $this->mTitle
->getSubpageText();
2386 case 'subpagenamee':
2387 return $this->mTitle
->getSubpageUrlForm();
2388 case 'basepagename':
2389 return $this->mTitle
->getBaseText();
2390 case 'basepagenamee':
2391 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2392 case 'talkpagename':
2393 if( $this->mTitle
->canTalk() ) {
2394 $talkPage = $this->mTitle
->getTalkPage();
2395 return $talkPage->getPrefixedText();
2399 case 'talkpagenamee':
2400 if( $this->mTitle
->canTalk() ) {
2401 $talkPage = $this->mTitle
->getTalkPage();
2402 return $talkPage->getPrefixedUrl();
2406 case 'subjectpagename':
2407 $subjPage = $this->mTitle
->getSubjectPage();
2408 return $subjPage->getPrefixedText();
2409 case 'subjectpagenamee':
2410 $subjPage = $this->mTitle
->getSubjectPage();
2411 return $subjPage->getPrefixedUrl();
2413 return $this->mRevisionId
;
2415 return intval( substr( $this->mTitle
->getTouched(), 6, 2 ) );
2416 case 'revisionday2':
2417 return substr( $this->mTitle
->getTouched(), 6, 2 );
2418 case 'revisionmonth':
2419 return intval( substr( $this->mTitle
->getTouched(), 4, 2 ) );
2420 case 'revisionyear':
2421 return substr( $this->mTitle
->getTouched(), 0, 4 );
2422 case 'revisiontimestamp':
2423 return $this->mTitle
->getTouched();
2425 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2427 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2429 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2431 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2432 case 'subjectspace':
2433 return $this->mTitle
->getSubjectNsText();
2434 case 'subjectspacee':
2435 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2436 case 'currentdayname':
2437 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2439 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2441 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2443 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2445 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2446 // int to remove the padding
2447 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2449 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2450 case 'localdayname':
2451 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2453 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2455 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2457 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2459 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2460 // int to remove the padding
2461 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2463 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2464 case 'numberofarticles':
2465 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2466 case 'numberoffiles':
2467 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2468 case 'numberofusers':
2469 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2470 case 'numberofpages':
2471 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2472 case 'numberofadmins':
2473 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2474 case 'currenttimestamp':
2475 return $varCache[$index] = wfTimestampNow();
2476 case 'localtimestamp':
2477 return $varCache[$index] = $localTimestamp;
2478 case 'currentversion':
2479 return $varCache[$index] = SpecialVersion
::getVersion();
2485 return $wgServerName;
2487 return $wgScriptPath;
2488 case 'directionmark':
2489 return $wgContLang->getDirMark();
2490 case 'contentlanguage':
2491 global $wgContLanguageCode;
2492 return $wgContLanguageCode;
2495 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2503 * initialise the magic variables (like CURRENTMONTHNAME)
2507 function initialiseVariables() {
2508 $fname = 'Parser::initialiseVariables';
2509 wfProfileIn( $fname );
2510 $variableIDs = MagicWord
::getVariableIDs();
2512 $this->mVariables
= array();
2513 foreach ( $variableIDs as $id ) {
2514 $mw =& MagicWord
::get( $id );
2515 $mw->addToArray( $this->mVariables
, $id );
2517 wfProfileOut( $fname );
2521 * parse any parentheses in format ((title|part|part))
2522 * and call callbacks to get a replacement text for any found piece
2524 * @param string $text The text to parse
2525 * @param array $callbacks rules in form:
2526 * '{' => array( # opening parentheses
2527 * 'end' => '}', # closing parentheses
2528 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2529 * 3 => callback # replacement callback to call if {{{..}}} is found
2532 * 'min' => 2, # Minimum parenthesis count in cb
2533 * 'max' => 3, # Maximum parenthesis count in cb
2536 function replace_callback ($text, $callbacks) {
2537 wfProfileIn( __METHOD__
);
2538 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2539 $lastOpeningBrace = -1; # last not closed parentheses
2541 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2544 while ( $i < strlen( $text ) ) {
2545 # Find next opening brace, closing brace or pipe
2546 if ( $lastOpeningBrace == -1 ) {
2547 $currentClosing = '';
2548 $search = $validOpeningBraces;
2550 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2551 $search = $validOpeningBraces . '|' . $currentClosing;
2554 $i +
= strcspn( $text, $search, $i );
2555 if ( $i < strlen( $text ) ) {
2556 if ( $text[$i] == '|' ) {
2558 } elseif ( $text[$i] == $currentClosing ) {
2562 $rule = $callbacks[$text[$i]];
2569 if ( $found == 'open' ) {
2570 # found opening brace, let's add it to parentheses stack
2571 $piece = array('brace' => $text[$i],
2572 'braceEnd' => $rule['end'],
2576 # count opening brace characters
2577 $piece['count'] = strspn( $text, $piece['brace'], $i );
2578 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2579 $i +
= $piece['count'];
2581 # we need to add to stack only if opening brace count is enough for one of the rules
2582 if ( $piece['count'] >= $rule['min'] ) {
2583 $lastOpeningBrace ++
;
2584 $openingBraceStack[$lastOpeningBrace] = $piece;
2586 } elseif ( $found == 'close' ) {
2587 # lets check if it is enough characters for closing brace
2588 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2589 $count = strspn( $text, $text[$i], $i, $maxCount );
2591 # check for maximum matching characters (if there are 5 closing
2592 # characters, we will probably need only 3 - depending on the rules)
2594 $matchingCallback = null;
2595 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2596 if ( $count > $cbType['max'] ) {
2597 # The specified maximum exists in the callback array, unless the caller
2599 $matchingCount = $cbType['max'];
2601 # Count is less than the maximum
2602 # Skip any gaps in the callback array to find the true largest match
2603 # Need to use array_key_exists not isset because the callback can be null
2604 $matchingCount = $count;
2605 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2610 if ($matchingCount <= 0) {
2614 $matchingCallback = $cbType['cb'][$matchingCount];
2616 # let's set a title or last part (if '|' was found)
2617 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2618 $openingBraceStack[$lastOpeningBrace]['title'] =
2619 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2620 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2622 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2623 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2624 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2627 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2628 $pieceEnd = $i +
$matchingCount;
2630 if( is_callable( $matchingCallback ) ) {
2632 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2633 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2634 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2635 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2637 # finally we can call a user callback and replace piece of text
2638 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2639 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2640 $i = $pieceStart +
strlen($replaceWith);
2642 # null value for callback means that parentheses should be parsed, but not replaced
2643 $i +
= $matchingCount;
2646 # reset last opening parentheses, but keep it in case there are unused characters
2647 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2648 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2649 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2652 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2653 $openingBraceStack[$lastOpeningBrace--] = null;
2655 if ($matchingCount < $piece['count']) {
2656 $piece['count'] -= $matchingCount;
2657 $piece['startAt'] -= $matchingCount;
2658 $piece['partStart'] = $piece['startAt'];
2659 # do we still qualify for any callback with remaining count?
2660 $currentCbList = $callbacks[$piece['brace']]['cb'];
2661 while ( $piece['count'] ) {
2662 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2663 $lastOpeningBrace++
;
2664 $openingBraceStack[$lastOpeningBrace] = $piece;
2670 } elseif ( $found == 'pipe' ) {
2671 # lets set a title if it is a first separator, or next part otherwise
2672 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2673 $openingBraceStack[$lastOpeningBrace]['title'] =
2674 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2675 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2676 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2678 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2679 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2680 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2682 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2686 wfProfileOut( __METHOD__
);
2691 * Replace magic variables, templates, and template arguments
2692 * with the appropriate text. Templates are substituted recursively,
2693 * taking care to avoid infinite loops.
2695 * Note that the substitution depends on value of $mOutputType:
2696 * OT_WIKI: only {{subst:}} templates
2697 * OT_MSG: only magic variables
2698 * OT_HTML: all templates and magic variables
2700 * @param string $tex The text to transform
2701 * @param array $args Key-value pairs representing template parameters to substitute
2702 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2705 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2706 # Prevent too big inclusions
2707 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2711 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2712 wfProfileIn( $fname );
2714 # This function is called recursively. To keep track of arguments we need a stack:
2715 array_push( $this->mArgStack
, $args );
2717 $braceCallbacks = array();
2719 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2721 if ( $this->mOutputType
!= OT_MSG
) {
2722 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2724 if ( $braceCallbacks ) {
2728 'cb' => $braceCallbacks,
2729 'min' => $argsOnly ?
3 : 2,
2730 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2734 'cb' => array(2=>null),
2739 $text = $this->replace_callback ($text, $callbacks);
2741 array_pop( $this->mArgStack
);
2743 wfProfileOut( $fname );
2748 * Replace magic variables
2751 function variableSubstitution( $matches ) {
2752 $fname = 'Parser::variableSubstitution';
2753 $varname = $matches[1];
2754 wfProfileIn( $fname );
2756 if ( $this->mOutputType
== OT_WIKI
) {
2757 # Do only magic variables prefixed by SUBST
2758 $mwSubst =& MagicWord
::get( 'subst' );
2759 if (!$mwSubst->matchStartAndRemove( $varname ))
2761 # Note that if we don't substitute the variable below,
2762 # we don't remove the {{subst:}} magic word, in case
2763 # it is a template rather than a magic variable.
2765 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2766 $id = $this->mVariables
[$varname];
2767 $text = $this->getVariableValue( $id );
2768 $this->mOutput
->mContainsOldMagic
= true;
2770 $text = $matches[0];
2772 wfProfileOut( $fname );
2776 # Split template arguments
2777 function getTemplateArgs( $argsString ) {
2778 if ( $argsString === '' ) {
2782 $args = explode( '|', substr( $argsString, 1 ) );
2784 # If any of the arguments contains a '[[' but no ']]', it needs to be
2785 # merged with the next arg because the '|' character between belongs
2786 # to the link syntax and not the template parameter syntax.
2787 $argc = count($args);
2789 for ( $i = 0; $i < $argc-1; $i++
) {
2790 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2791 $args[$i] .= '|'.$args[$i+
1];
2792 array_splice($args, $i+
1, 1);
2802 * Return the text of a template, after recursively
2803 * replacing any variables or templates within the template.
2805 * @param array $piece The parts of the template
2806 * $piece['text']: matched text
2807 * $piece['title']: the title, i.e. the part before the |
2808 * $piece['parts']: the parameter array
2809 * @return string the text of the template
2812 function braceSubstitution( $piece ) {
2813 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2814 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2815 wfProfileIn( $fname );
2816 wfProfileIn( __METHOD__
.'-setup' );
2819 $found = false; # $text has been filled
2820 $nowiki = false; # wiki markup in $text should be escaped
2821 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2822 $noargs = false; # Don't replace triple-brace arguments in $text
2823 $replaceHeadings = false; # Make the edit section links go to the template not the article
2824 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2825 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2827 # Title object, where $text came from
2833 # $part1 is the bit before the first |, and must contain only title characters
2834 # $args is a list of arguments, starting from index 0, not including $part1
2836 $titleText = $part1 = $piece['title'];
2837 # If the third subpattern matched anything, it will start with |
2839 if (null == $piece['parts']) {
2840 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2841 if ($replaceWith != $piece['text']) {
2842 $text = $replaceWith;
2849 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2850 $argc = count( $args );
2851 wfProfileOut( __METHOD__
.'-setup' );
2854 wfProfileIn( __METHOD__
.'-modifiers' );
2856 $mwSubst =& MagicWord
::get( 'subst' );
2857 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2858 # One of two possibilities is true:
2859 # 1) Found SUBST but not in the PST phase
2860 # 2) Didn't find SUBST and in the PST phase
2861 # In either case, return without further processing
2862 $text = $piece['text'];
2869 # MSG, MSGNW, INT and RAW
2872 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2873 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2876 # Remove obsolete MSG:
2877 $mwMsg =& MagicWord
::get( 'msg' );
2878 $mwMsg->matchStartAndRemove( $part1 );
2882 $mwRaw =& MagicWord
::get( 'raw' );
2883 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2884 $forceRawInterwiki = true;
2887 # Check if it is an internal message
2888 $mwInt =& MagicWord
::get( 'int' );
2889 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2890 $text = $linestart . wfMsgReal( $part1, $args, true );
2894 wfProfileOut( __METHOD__
.'-modifiers' );
2898 wfProfileIn( __METHOD__
. '-pfunc' );
2900 $colonPos = strpos( $part1, ':' );
2901 if ( $colonPos !== false ) {
2902 # Case sensitive functions
2903 $function = substr( $part1, 0, $colonPos );
2904 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2905 $function = $this->mFunctionSynonyms
[1][$function];
2907 # Case insensitive functions
2908 $function = strtolower( $function );
2909 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2910 $function = $this->mFunctionSynonyms
[0][$function];
2916 $funcArgs = array_map( 'trim', $args );
2917 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2918 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2921 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2925 if ( is_array( $result ) ) {
2926 if ( isset( $result[0] ) ) {
2927 $text = $linestart . $result[0];
2928 unset( $result[0] );
2931 // Extract flags into the local scope
2932 // This allows callers to set flags such as nowiki, noparse, found, etc.
2935 $text = $linestart . $result;
2939 wfProfileOut( __METHOD__
. '-pfunc' );
2942 # Template table test
2944 # Did we encounter this template already? If yes, it is in the cache
2945 # and we need to check for loops.
2946 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2949 # Infinite loop test
2950 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2954 $text = $linestart .
2955 "[[$part1]]<!-- WARNING: template loop detected -->";
2956 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2958 # set $text to cached message.
2959 $text = $linestart . $this->mTemplates
[$piece['title']];
2963 # Load from database
2964 $lastPathLevel = $this->mTemplatePath
;
2966 wfProfileIn( __METHOD__
. '-loadtpl' );
2968 # declaring $subpage directly in the function call
2969 # does not work correctly with references and breaks
2970 # {{/subpage}}-style inclusions
2972 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2973 if ($subpage !== '') {
2974 $ns = $this->mTitle
->getNamespace();
2976 $title = Title
::newFromText( $part1, $ns );
2979 if ( !is_null( $title ) ) {
2980 $titleText = $title->getPrefixedText();
2981 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2982 # Check for language variants if the template is not found
2983 if($checkVariantLink && $title->getArticleID() == 0){
2984 $wgContLang->findVariantLink($part1, $title);
2987 if ( !$title->isExternal() ) {
2988 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2989 $text = SpecialPage
::capturePath( $title );
2990 if ( is_string( $text ) ) {
2995 $this->disableCache();
2998 $articleContent = $this->fetchTemplate( $title );
2999 if ( $articleContent !== false ) {
3001 $text = $articleContent;
3002 $replaceHeadings = true;
3006 # If the title is valid but undisplayable, make a link to it
3007 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3008 $text = "[[$titleText]]";
3011 } elseif ( $title->isTrans() ) {
3012 // Interwiki transclusion
3013 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3014 $text = $this->interwikiTransclude( $title, 'render' );
3018 $text = $this->interwikiTransclude( $title, 'raw' );
3019 $replaceHeadings = true;
3024 # Template cache array insertion
3025 # Use the original $piece['title'] not the mangled $part1, so that
3026 # modifiers such as RAW: produce separate cache entries
3029 // A special page; don't store it in the template cache.
3031 $this->mTemplates
[$piece['title']] = $text;
3033 $text = $linestart . $text;
3036 wfProfileOut( __METHOD__
. '-loadtpl' );
3039 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3040 # Error, oversize inclusion
3041 $text = $linestart .
3042 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3047 # Recursive parsing, escaping and link table handling
3048 # Only for HTML output
3049 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3050 $text = wfEscapeWikiText( $text );
3051 } elseif ( !$this->ot
['msg'] && $found ) {
3053 $assocArgs = array();
3055 # Clean up argument array
3056 $assocArgs = array();
3058 foreach( $args as $arg ) {
3059 $eqpos = strpos( $arg, '=' );
3060 if ( $eqpos === false ) {
3061 $assocArgs[$index++
] = $arg;
3063 $name = trim( substr( $arg, 0, $eqpos ) );
3064 $value = trim( substr( $arg, $eqpos+
1 ) );
3065 if ( $value === false ) {
3068 if ( $name !== false ) {
3069 $assocArgs[$name] = $value;
3074 # Add a new element to the templace recursion path
3075 $this->mTemplatePath
[$part1] = 1;
3079 # If there are any <onlyinclude> tags, only include them
3080 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3081 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3083 foreach ($m[1] as $piece)
3086 # Remove <noinclude> sections and <includeonly> tags
3087 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3088 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3090 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3091 # Strip <nowiki>, <pre>, etc.
3092 $text = $this->strip( $text, $this->mStripState
);
3093 if ( $this->ot
['html'] ) {
3094 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3095 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3096 $text = Sanitizer
::removeHTMLcomments( $text );
3099 $text = $this->replaceVariables( $text, $assocArgs );
3101 # If the template begins with a table or block-level
3102 # element, it should be treated as beginning a new line.
3103 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3104 $text = "\n" . $text;
3106 } elseif ( !$noargs ) {
3107 # $noparse and !$noargs
3108 # Just replace the arguments, not any double-brace items
3109 # This is used for rendered interwiki transclusion
3110 $text = $this->replaceVariables( $text, $assocArgs, true );
3113 # Prune lower levels off the recursion check path
3114 $this->mTemplatePath
= $lastPathLevel;
3116 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3117 # Error, oversize inclusion
3118 $text = $linestart .
3119 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3125 wfProfileOut( $fname );
3126 return $piece['text'];
3128 wfProfileIn( __METHOD__
. '-placeholders' );
3130 # Replace raw HTML by a placeholder
3131 # Add a blank line preceding, to prevent it from mucking up
3132 # immediately preceding headings
3133 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3135 # replace ==section headers==
3136 # XXX this needs to go away once we have a better parser.
3137 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3138 if( !is_null( $title ) )
3139 $encodedname = base64_encode($title->getPrefixedDBkey());
3141 $encodedname = base64_encode("");
3142 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3143 PREG_SPLIT_DELIM_CAPTURE
);
3146 for( $i = 0; $i < count($m); $i +
= 2 ) {
3148 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3150 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3154 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3155 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3156 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3162 wfProfileOut( __METHOD__
. '-placeholders' );
3165 # Prune lower levels off the recursion check path
3166 $this->mTemplatePath
= $lastPathLevel;
3169 wfProfileOut( $fname );
3170 return $piece['text'];
3172 wfProfileOut( $fname );
3178 * Fetch the unparsed text of a template and register a reference to it.
3180 function fetchTemplate( $title ) {
3182 // Loop to fetch the article, with up to 1 redirect
3183 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3184 $rev = Revision
::newFromTitle( $title );
3185 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3189 $text = $rev->getText();
3190 if ( $text === false ) {
3194 $title = Title
::newFromRedirect( $text );
3200 * Transclude an interwiki link.
3202 function interwikiTransclude( $title, $action ) {
3203 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3205 if (!$wgEnableScaryTranscluding)
3206 return wfMsg('scarytranscludedisabled');
3208 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3209 // But we'll handle it generally anyway
3210 if ( $title->getNamespace() ) {
3211 // Use the canonical namespace, which should work anywhere
3212 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3214 $articleName = $title->getDBkey();
3217 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3218 $url .= "?action=$action";
3219 if (strlen($url) > 255)
3220 return wfMsg('scarytranscludetoolong');
3221 return $this->fetchScaryTemplateMaybeFromCache($url);
3224 function fetchScaryTemplateMaybeFromCache($url) {
3225 global $wgTranscludeCacheExpiry;
3226 $dbr =& wfGetDB(DB_SLAVE
);
3227 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3228 array('tc_url' => $url));
3230 $time = $obj->tc_time
;
3231 $text = $obj->tc_contents
;
3232 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3237 $text = Http
::get($url);
3239 return wfMsg('scarytranscludefailed', $url);
3241 $dbw =& wfGetDB(DB_MASTER
);
3242 $dbw->replace('transcache', array('tc_url'), array(
3244 'tc_time' => time(),
3245 'tc_contents' => $text));
3251 * Triple brace replacement -- used for template arguments
3254 function argSubstitution( $matches ) {
3255 $arg = trim( $matches['title'] );
3256 $text = $matches['text'];
3257 $inputArgs = end( $this->mArgStack
);
3259 if ( array_key_exists( $arg, $inputArgs ) ) {
3260 $text = $inputArgs[$arg];
3261 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3262 null != $matches['parts'] && count($matches['parts']) > 0) {
3263 $text = $matches['parts'][0];
3265 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3266 $text = $matches['text'] .
3267 '<!-- WARNING: argument omitted, expansion size too large -->';
3274 * Increment an include size counter
3276 * @param string $type The type of expansion
3277 * @param integer $size The size of the text
3278 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3280 function incrementIncludeSize( $type, $size ) {
3281 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3284 $this->mIncludeSizes
[$type] +
= $size;
3290 * Detect __NOGALLERY__ magic word and set a placeholder
3292 function stripNoGallery( &$text ) {
3293 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3295 $mw = MagicWord
::get( 'nogallery' );
3296 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3300 * Detect __TOC__ magic word and set a placeholder
3302 function stripToc( $text ) {
3303 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3305 $mw = MagicWord
::get( 'notoc' );
3306 if( $mw->matchAndRemove( $text ) ) {
3307 $this->mShowToc
= false;
3310 $mw = MagicWord
::get( 'toc' );
3311 if( $mw->match( $text ) ) {
3312 $this->mShowToc
= true;
3313 $this->mForceTocPosition
= true;
3315 // Set a placeholder. At the end we'll fill it in with the TOC.
3316 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3318 // Only keep the first one.
3319 $text = $mw->replace( '', $text );
3325 * This function accomplishes several tasks:
3326 * 1) Auto-number headings if that option is enabled
3327 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3328 * 3) Add a Table of contents on the top for users who have enabled the option
3329 * 4) Auto-anchor headings
3331 * It loops through all headlines, collects the necessary data, then splits up the
3332 * string and re-inserts the newly formatted headlines.
3334 * @param string $text
3335 * @param boolean $isMain
3338 function formatHeadings( $text, $isMain=true ) {
3339 global $wgMaxTocLevel, $wgContLang;
3341 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3342 if( !$this->mTitle
->userCanEdit() ) {
3345 $showEditLink = $this->mOptions
->getEditSection();
3348 # Inhibit editsection links if requested in the page
3349 $esw =& MagicWord
::get( 'noeditsection' );
3350 if( $esw->matchAndRemove( $text ) ) {
3354 # Get all headlines for numbering them and adding funky stuff like [edit]
3355 # links - this is for later, but we need the number of headlines right now
3356 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3358 # if there are fewer than 4 headlines in the article, do not show TOC
3359 # unless it's been explicitly enabled.
3360 $enoughToc = $this->mShowToc
&&
3361 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3363 # Allow user to stipulate that a page should have a "new section"
3364 # link added via __NEWSECTIONLINK__
3365 $mw =& MagicWord
::get( 'newsectionlink' );
3366 if( $mw->matchAndRemove( $text ) )
3367 $this->mOutput
->setNewSection( true );
3369 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3370 # override above conditions and always show TOC above first header
3371 $mw =& MagicWord
::get( 'forcetoc' );
3372 if ($mw->matchAndRemove( $text ) ) {
3373 $this->mShowToc
= true;
3377 # Never ever show TOC if no headers
3378 if( $numMatches < 1 ) {
3382 # We need this to perform operations on the HTML
3383 $sk =& $this->mOptions
->getSkin();
3387 $sectionCount = 0; # headlineCount excluding template sections
3389 # Ugh .. the TOC should have neat indentation levels which can be
3390 # passed to the skin functions. These are determined here
3394 $sublevelCount = array();
3395 $levelCount = array();
3402 foreach( $matches[3] as $headline ) {
3404 $templatetitle = '';
3405 $templatesection = 0;
3408 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3410 $templatetitle = base64_decode($mat[1]);
3411 $templatesection = 1 +
(int)base64_decode($mat[2]);
3412 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3416 $prevlevel = $level;
3417 $prevtoclevel = $toclevel;
3419 $level = $matches[1][$headlineCount];
3421 if( $doNumberHeadings ||
$enoughToc ) {
3423 if ( $level > $prevlevel ) {
3424 # Increase TOC level
3426 $sublevelCount[$toclevel] = 0;
3427 if( $toclevel<$wgMaxTocLevel ) {
3428 $toc .= $sk->tocIndent();
3431 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3432 # Decrease TOC level, find level to jump to
3434 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3435 # Can only go down to level 1
3438 for ($i = $toclevel; $i > 0; $i--) {
3439 if ( $levelCount[$i] == $level ) {
3440 # Found last matching level
3444 elseif ( $levelCount[$i] < $level ) {
3445 # Found first matching level below current level
3451 if( $toclevel<$wgMaxTocLevel ) {
3452 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3456 # No change in level, end TOC line
3457 if( $toclevel<$wgMaxTocLevel ) {
3458 $toc .= $sk->tocLineEnd();
3462 $levelCount[$toclevel] = $level;
3464 # count number of headlines for each level
3465 @$sublevelCount[$toclevel]++
;
3467 for( $i = 1; $i <= $toclevel; $i++
) {
3468 if( !empty( $sublevelCount[$i] ) ) {
3472 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3478 # The canonized header is a version of the header text safe to use for links
3479 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3480 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3481 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3483 # Remove link placeholders by the link text.
3484 # <!--LINK number-->
3486 # link text with suffix
3487 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3488 "\$this->mLinkHolders['texts'][\$1]",
3489 $canonized_headline );
3490 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3491 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3492 $canonized_headline );
3495 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3496 $tocline = trim( $canonized_headline );
3497 # Save headline for section edit hint before it's escaped
3498 $headline_hint = trim( $canonized_headline );
3499 $canonized_headline = Sanitizer
::escapeId( $tocline );
3500 $refers[$headlineCount] = $canonized_headline;
3502 # count how many in assoc. array so we can track dupes in anchors
3503 @$refers[$canonized_headline]++
;
3504 $refcount[$headlineCount]=$refers[$canonized_headline];
3506 # Don't number the heading if it is the only one (looks silly)
3507 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3508 # the two are different if the line contains a link
3509 $headline=$numbering . ' ' . $headline;
3512 # Create the anchor for linking from the TOC to the section
3513 $anchor = $canonized_headline;
3514 if($refcount[$headlineCount] > 1 ) {
3515 $anchor .= '_' . $refcount[$headlineCount];
3517 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3518 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3520 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3521 if ( empty( $head[$headlineCount] ) ) {
3522 $head[$headlineCount] = '';
3525 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3527 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3530 # give headline the correct <h#> tag
3531 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3539 if( $toclevel<$wgMaxTocLevel ) {
3540 $toc .= $sk->tocUnindent( $toclevel - 1 );
3542 $toc = $sk->tocList( $toc );
3545 # split up and insert constructed headlines
3547 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3550 foreach( $blocks as $block ) {
3551 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3552 # This is the [edit] link that appears for the top block of text when
3553 # section editing is enabled
3555 # Disabled because it broke block formatting
3556 # For example, a bullet point in the top line
3557 # $full .= $sk->editSectionLink(0);
3560 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3561 # Top anchor now in skin
3565 if( !empty( $head[$i] ) ) {
3570 if( $this->mForceTocPosition
) {
3571 return str_replace( '<!--MWTOC-->', $toc, $full );
3578 * Transform wiki markup when saving a page by doing \r\n -> \n
3579 * conversion, substitting signatures, {{subst:}} templates, etc.
3581 * @param string $text the text to transform
3582 * @param Title &$title the Title object for the current article
3583 * @param User &$user the User object describing the current user
3584 * @param ParserOptions $options parsing options
3585 * @param bool $clearState whether to clear the parser state first
3586 * @return string the altered wiki markup
3589 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3590 $this->mOptions
= $options;
3591 $this->mTitle
=& $title;
3592 $this->setOutputType( OT_WIKI
);
3594 if ( $clearState ) {
3595 $this->clearState();
3598 $stripState = false;
3602 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3603 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3604 $text = $this->pstPass2( $text, $stripState, $user );
3605 $text = $this->unstrip( $text, $stripState );
3606 $text = $this->unstripNoWiki( $text, $stripState );
3611 * Pre-save transform helper function
3614 function pstPass2( $text, &$stripState, &$user ) {
3615 global $wgContLang, $wgLocaltimezone;
3617 /* Note: This is the timestamp saved as hardcoded wikitext to
3618 * the database, we use $wgContLang here in order to give
3619 * everyone the same signature and use the default one rather
3620 * than the one selected in each user's preferences.
3622 if ( isset( $wgLocaltimezone ) ) {
3623 $oldtz = getenv( 'TZ' );
3624 putenv( 'TZ='.$wgLocaltimezone );
3626 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3627 ' (' . date( 'T' ) . ')';
3628 if ( isset( $wgLocaltimezone ) ) {
3629 putenv( 'TZ='.$oldtz );
3632 # Variable replacement
3633 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3634 $text = $this->replaceVariables( $text );
3636 # Strip out <nowiki> etc. added via replaceVariables
3637 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3640 $sigText = $this->getUserSig( $user );
3641 $text = strtr( $text, array(
3643 '~~~~' => "$sigText $d",
3647 # Context links: [[|name]] and [[name (context)|]]
3649 global $wgLegalTitleChars;
3650 $tc = "[$wgLegalTitleChars]";
3652 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3653 $conpat = "/^{$tc}+?( \\({$tc}+\\)|)$/";
3655 $p1 = "/\[\[(:?$namespacechar+:|:|)({$tc}+?)( \\({$tc}+\\)|)\\|]]/"; # [[ns:page (context)|]]
3656 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3658 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3660 $t = $this->mTitle
->getText();
3661 if ( preg_match( $conpat, $t, $m ) && '' != $m[1] ) {
3662 $text = preg_replace( $p2, "[[\\1{$m[1]}|\\1]]", $text );
3664 # if $m[1] is empty, don't bother duplicating the title
3665 $text = preg_replace( $p2, '[[\\1]]', $text );
3668 # Trim trailing whitespace
3669 # __END__ tag allows for trailing
3670 # whitespace to be deliberately included
3671 $text = rtrim( $text );
3672 $mw =& MagicWord
::get( 'end' );
3673 $mw->matchAndRemove( $text );
3679 * Fetch the user's signature text, if any, and normalize to
3680 * validated, ready-to-insert wikitext.
3686 function getUserSig( &$user ) {
3687 $username = $user->getName();
3688 $nickname = $user->getOption( 'nickname' );
3689 $nickname = $nickname === '' ?
$username : $nickname;
3691 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3692 # Sig. might contain markup; validate this
3693 if( $this->validateSig( $nickname ) !== false ) {
3694 # Validated; clean up (if needed) and return it
3695 return $this->cleanSig( $nickname, true );
3697 # Failed to validate; fall back to the default
3698 $nickname = $username;
3699 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3703 // Make sure nickname doesnt get a sig in a sig
3704 $nickname = $this->cleanSigInSig( $nickname );
3706 # If we're still here, make it a link to the user page
3707 $userpage = $user->getUserPage();
3708 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3712 * Check that the user's signature contains no bad XML
3714 * @param string $text
3715 * @return mixed An expanded string, or false if invalid.
3717 function validateSig( $text ) {
3718 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3722 * Clean up signature text
3724 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3725 * 2) Substitute all transclusions
3727 * @param string $text
3728 * @param $parsing Whether we're cleaning (preferences save) or parsing
3729 * @return string Signature text
3731 function cleanSig( $text, $parsing = false ) {
3733 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3735 $substWord = MagicWord
::get( 'subst' );
3736 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3737 $substText = '{{' . $substWord->getSynonym( 0 );
3739 $text = preg_replace( $substRegex, $substText, $text );
3740 $text = $this->cleanSigInSig( $text );
3741 $text = $this->replaceVariables( $text );
3743 $this->clearState();
3748 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3749 * @param string $text
3750 * @return string Signature text with /~{3,5}/ removed
3752 function cleanSigInSig( $text ) {
3753 $text = preg_replace( '/~{3,5}/', '', $text );
3758 * Set up some variables which are usually set up in parse()
3759 * so that an external function can call some class members with confidence
3762 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3763 $this->mTitle
=& $title;
3764 $this->mOptions
= $options;
3765 $this->setOutputType( $outputType );
3766 if ( $clearState ) {
3767 $this->clearState();
3772 * Transform a MediaWiki message by replacing magic variables.
3774 * @param string $text the text to transform
3775 * @param ParserOptions $options options
3776 * @return string the text with variables substituted
3779 function transformMsg( $text, $options ) {
3781 static $executing = false;
3783 $fname = "Parser::transformMsg";
3785 # Guard against infinite recursion
3791 wfProfileIn($fname);
3793 $this->mTitle
= $wgTitle;
3794 $this->mOptions
= $options;
3795 $this->setOutputType( OT_MSG
);
3796 $this->clearState();
3797 $text = $this->replaceVariables( $text );
3800 wfProfileOut($fname);
3805 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3806 * The callback should have the following form:
3807 * function myParserHook( $text, $params, &$parser ) { ... }
3809 * Transform and return $text. Use $parser for any required context, e.g. use
3810 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3814 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3815 * @param mixed $callback The callback function (and object) to use for the tag
3817 * @return The old value of the mTagHooks array associated with the hook
3819 function setHook( $tag, $callback ) {
3820 $tag = strtolower( $tag );
3821 $oldVal = @$this->mTagHooks
[$tag];
3822 $this->mTagHooks
[$tag] = $callback;
3828 * Create a function, e.g. {{sum:1|2|3}}
3829 * The callback function should have the form:
3830 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3832 * The callback may either return the text result of the function, or an array with the text
3833 * in element 0, and a number of flags in the other elements. The names of the flags are
3834 * specified in the keys. Valid flags are:
3835 * found The text returned is valid, stop processing the template. This
3837 * nowiki Wiki markup in the return value should be escaped
3838 * noparse Unsafe HTML tags should not be stripped, etc.
3839 * noargs Don't replace triple-brace arguments in the return value
3840 * isHTML The returned text is HTML, armour it against wikitext transformation
3844 * @param string $id The magic word ID
3845 * @param mixed $callback The callback function (and object) to use
3846 * @param integer $flags a combination of the following flags:
3847 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3849 * @return The old callback function for this name, if any
3851 function setFunctionHook( $id, $callback, $flags = 0 ) {
3852 $oldVal = @$this->mFunctionHooks
[$id];
3853 $this->mFunctionHooks
[$id] = $callback;
3855 # Add to function cache
3856 $mw = MagicWord
::get( $id );
3858 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3860 $synonyms = $mw->getSynonyms();
3861 $sensitive = intval( $mw->isCaseSensitive() );
3863 foreach ( $synonyms as $syn ) {
3865 if ( !$sensitive ) {
3866 $syn = strtolower( $syn );
3869 if ( !( $flags & SFH_NO_HASH
) ) {
3872 # Remove trailing colon
3873 if ( substr( $syn, -1, 1 ) == ':' ) {
3874 $syn = substr( $syn, 0, -1 );
3876 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3882 * Get all registered function hook identifiers
3886 function getFunctionHooks() {
3887 return array_keys( $this->mFunctionHooks
);
3891 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3892 * Placeholders created in Skin::makeLinkObj()
3893 * Returns an array of links found, indexed by PDBK:
3897 * $options is a bit field, RLH_FOR_UPDATE to select for update
3899 function replaceLinkHolders( &$text, $options = 0 ) {
3901 global $wgOutputReplace;
3902 global $wgContLang, $wgLanguageCode;
3904 $fname = 'Parser::replaceLinkHolders';
3905 wfProfileIn( $fname );
3909 $sk =& $this->mOptions
->getSkin();
3910 $linkCache =& LinkCache
::singleton();
3912 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3913 wfProfileIn( $fname.'-check' );
3914 $dbr =& wfGetDB( DB_SLAVE
);
3915 $page = $dbr->tableName( 'page' );
3916 $threshold = $wgUser->getOption('stubthreshold');
3919 asort( $this->mLinkHolders
['namespaces'] );
3923 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3925 $title = $this->mLinkHolders
['titles'][$key];
3927 # Skip invalid entries.
3928 # Result will be ugly, but prevents crash.
3929 if ( is_null( $title ) ) {
3932 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3934 # Check if it's a static known link, e.g. interwiki
3935 if ( $title->isAlwaysKnown() ) {
3936 $colours[$pdbk] = 1;
3937 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3938 $colours[$pdbk] = 1;
3939 $this->mOutput
->addLink( $title, $id );
3940 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3941 $colours[$pdbk] = 0;
3943 # Not in the link cache, add it to the query
3944 if ( !isset( $current ) ) {
3946 $query = "SELECT page_id, page_namespace, page_title";
3947 if ( $threshold > 0 ) {
3948 $query .= ', page_len, page_is_redirect';
3950 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3951 } elseif ( $current != $ns ) {
3953 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3958 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3963 if ( $options & RLH_FOR_UPDATE
) {
3964 $query .= ' FOR UPDATE';
3967 $res = $dbr->query( $query, $fname );
3969 # Fetch data and form into an associative array
3970 # non-existent = broken
3973 while ( $s = $dbr->fetchObject($res) ) {
3974 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3975 $pdbk = $title->getPrefixedDBkey();
3976 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3977 $this->mOutput
->addLink( $title, $s->page_id
);
3979 if ( $threshold > 0 ) {
3980 $size = $s->page_len
;
3981 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3982 $colours[$pdbk] = 1;
3984 $colours[$pdbk] = 2;
3987 $colours[$pdbk] = 1;
3991 wfProfileOut( $fname.'-check' );
3993 # Do a second query for different language variants of links (if needed)
3994 if($wgContLang->hasVariants()){
3995 $linkBatch = new LinkBatch();
3996 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
3998 // Add variants of links to link batch
3999 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4000 $title = $this->mLinkHolders
['titles'][$key];
4001 if ( is_null( $title ) )
4004 $pdbk = $title->getPrefixedDBkey();
4006 // generate all variants of the link title text
4007 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4009 // if link was not found (in first query), add all variants to query
4010 if ( !isset($colours[$pdbk]) ){
4011 foreach($allTextVariants as $textVariant){
4012 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4013 if(is_null($variantTitle)) continue;
4014 $linkBatch->addObj( $variantTitle );
4015 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4021 if(!$linkBatch->isEmpty()){
4023 $titleClause = $linkBatch->constructSet('page', $dbr);
4025 $variantQuery = "SELECT page_id, page_namespace, page_title";
4026 if ( $threshold > 0 ) {
4027 $variantQuery .= ', page_len, page_is_redirect';
4030 $variantQuery .= " FROM $page WHERE $titleClause";
4031 if ( $options & RLH_FOR_UPDATE
) {
4032 $variantQuery .= ' FOR UPDATE';
4035 $varRes = $dbr->query( $variantQuery, $fname );
4037 // for each found variants, figure out link holders and replace
4038 while ( $s = $dbr->fetchObject($varRes) ) {
4040 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4041 $varPdbk = $variantTitle->getPrefixedDBkey();
4042 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4043 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4045 $holderKeys = $variantMap[$varPdbk];
4047 // loop over link holders
4048 foreach($holderKeys as $key){
4049 $title = $this->mLinkHolders
['titles'][$key];
4050 if ( is_null( $title ) ) continue;
4052 $pdbk = $title->getPrefixedDBkey();
4054 if(!isset($colours[$pdbk])){
4055 // found link in some of the variants, replace the link holder data
4056 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4057 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4059 // set pdbk and colour
4060 $pdbks[$key] = $varPdbk;
4061 if ( $threshold > 0 ) {
4062 $size = $s->page_len
;
4063 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4064 $colours[$varPdbk] = 1;
4066 $colours[$varPdbk] = 2;
4070 $colours[$varPdbk] = 1;
4078 # Construct search and replace arrays
4079 wfProfileIn( $fname.'-construct' );
4080 $wgOutputReplace = array();
4081 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4082 $pdbk = $pdbks[$key];
4083 $searchkey = "<!--LINK $key-->";
4084 $title = $this->mLinkHolders
['titles'][$key];
4085 if ( empty( $colours[$pdbk] ) ) {
4086 $linkCache->addBadLinkObj( $title );
4087 $colours[$pdbk] = 0;
4088 $this->mOutput
->addLink( $title, 0 );
4089 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4090 $this->mLinkHolders
['texts'][$key],
4091 $this->mLinkHolders
['queries'][$key] );
4092 } elseif ( $colours[$pdbk] == 1 ) {
4093 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4094 $this->mLinkHolders
['texts'][$key],
4095 $this->mLinkHolders
['queries'][$key] );
4096 } elseif ( $colours[$pdbk] == 2 ) {
4097 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4098 $this->mLinkHolders
['texts'][$key],
4099 $this->mLinkHolders
['queries'][$key] );
4102 wfProfileOut( $fname.'-construct' );
4105 wfProfileIn( $fname.'-replace' );
4107 $text = preg_replace_callback(
4108 '/(<!--LINK .*?-->)/',
4109 "wfOutputReplaceMatches",
4112 wfProfileOut( $fname.'-replace' );
4115 # Now process interwiki link holders
4116 # This is quite a bit simpler than internal links
4117 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4118 wfProfileIn( $fname.'-interwiki' );
4119 # Make interwiki link HTML
4120 $wgOutputReplace = array();
4121 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4122 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4123 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4126 $text = preg_replace_callback(
4127 '/<!--IWLINK (.*?)-->/',
4128 "wfOutputReplaceMatches",
4130 wfProfileOut( $fname.'-interwiki' );
4133 wfProfileOut( $fname );
4138 * Replace <!--LINK--> link placeholders with plain text of links
4139 * (not HTML-formatted).
4140 * @param string $text
4143 function replaceLinkHoldersText( $text ) {
4144 $fname = 'Parser::replaceLinkHoldersText';
4145 wfProfileIn( $fname );
4147 $text = preg_replace_callback(
4148 '/<!--(LINK|IWLINK) (.*?)-->/',
4149 array( &$this, 'replaceLinkHoldersTextCallback' ),
4152 wfProfileOut( $fname );
4157 * @param array $matches
4161 function replaceLinkHoldersTextCallback( $matches ) {
4162 $type = $matches[1];
4164 if( $type == 'LINK' ) {
4165 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4166 return $this->mLinkHolders
['texts'][$key];
4168 } elseif( $type == 'IWLINK' ) {
4169 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4170 return $this->mInterwikiLinkHolders
['texts'][$key];
4177 * Tag hook handler for 'pre'.
4179 function renderPreTag( $text, $attribs, $parser ) {
4180 // Backwards-compatibility hack
4181 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4183 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4184 return wfOpenElement( 'pre', $attribs ) .
4185 wfEscapeHTMLTagsOnly( $content ) .
4190 * Renders an image gallery from a text with one line per image.
4191 * text labels may be given by using |-style alternative text. E.g.
4192 * Image:one.jpg|The number "1"
4193 * Image:tree.jpg|A tree
4194 * given as text will return the HTML of a gallery with two images,
4195 * labeled 'The number "1"' and
4198 function renderImageGallery( $text, $params ) {
4199 $ig = new ImageGallery();
4200 $ig->setShowBytes( false );
4201 $ig->setShowFilename( false );
4203 $ig->useSkin( $this->mOptions
->getSkin() );
4205 if( isset( $params['caption'] ) )
4206 $ig->setCaption( $params['caption'] );
4208 $lines = explode( "\n", $text );
4209 foreach ( $lines as $line ) {
4210 # match lines like these:
4211 # Image:someimage.jpg|This is some image
4212 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4214 if ( count( $matches ) == 0 ) {
4217 $tp = Title
::newFromText( $matches[1] );
4219 if( is_null( $nt ) ) {
4220 # Bogus title. Ignore these so we don't bomb out later.
4223 if ( isset( $matches[3] ) ) {
4224 $label = $matches[3];
4229 $pout = $this->parse( $label,
4232 false, // Strip whitespace...?
4233 false // Don't clear state!
4235 $html = $pout->getText();
4237 $ig->add( new Image( $nt ), $html );
4239 # Only add real images (bug #5586)
4240 if ( $nt->getNamespace() == NS_IMAGE
) {
4241 $this->mOutput
->addImage( $nt->getDBkey() );
4244 return $ig->toHTML();
4248 * Parse image options text and use it to make an image
4250 function makeImage( &$nt, $options ) {
4251 global $wgUseImageResize, $wgDjvuRenderer;
4255 # Check if the options text is of the form "options|alt text"
4257 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4258 # * left no resizing, just left align. label is used for alt= only
4259 # * right same, but right aligned
4260 # * none same, but not aligned
4261 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4262 # * center center the image
4263 # * framed Keep original image size, no magnify-button.
4265 $part = explode( '|', $options);
4267 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4268 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4269 $mwLeft =& MagicWord
::get( 'img_left' );
4270 $mwRight =& MagicWord
::get( 'img_right' );
4271 $mwNone =& MagicWord
::get( 'img_none' );
4272 $mwWidth =& MagicWord
::get( 'img_width' );
4273 $mwCenter =& MagicWord
::get( 'img_center' );
4274 $mwFramed =& MagicWord
::get( 'img_framed' );
4275 $mwPage =& MagicWord
::get( 'img_page' );
4278 $width = $height = $framed = $thumb = false;
4280 $manual_thumb = '' ;
4282 foreach( $part as $key => $val ) {
4283 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4285 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4286 # use manually specified thumbnail
4288 $manual_thumb = $match;
4289 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4290 # remember to set an alignment, don't render immediately
4292 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4293 # remember to set an alignment, don't render immediately
4295 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4296 # remember to set an alignment, don't render immediately
4298 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4299 # remember to set an alignment, don't render immediately
4301 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4302 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4303 # Select a page in a multipage document
4305 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4306 wfDebug( "img_width match: $match\n" );
4307 # $match is the image width in pixels
4308 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4309 $width = intval( $m[1] );
4310 $height = intval( $m[2] );
4312 $width = intval($match);
4314 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4320 # Strip bad stuff out of the alt text
4321 $alt = $this->replaceLinkHoldersText( $caption );
4323 # make sure there are no placeholders in thumbnail attributes
4324 # that are later expanded to html- so expand them now and
4326 $alt = $this->unstrip($alt, $this->mStripState
);
4327 $alt = Sanitizer
::stripAllTags( $alt );
4329 # Linker does the rest
4330 $sk =& $this->mOptions
->getSkin();
4331 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4335 * Set a flag in the output object indicating that the content is dynamic and
4336 * shouldn't be cached.
4338 function disableCache() {
4339 wfDebug( "Parser output marked as uncacheable.\n" );
4340 $this->mOutput
->mCacheTime
= -1;
4344 * Callback from the Sanitizer for expanding items found in HTML attribute
4345 * values, so they can be safely tested and escaped.
4346 * @param string $text
4347 * @param array $args
4351 function attributeStripCallback( &$text, $args ) {
4352 $text = $this->replaceVariables( $text, $args );
4353 $text = $this->unstripForHTML( $text );
4357 function unstripForHTML( $text ) {
4358 $text = $this->unstrip( $text, $this->mStripState
);
4359 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4367 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4368 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4369 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4375 function getTags() { return array_keys( $this->mTagHooks
); }
4380 * Break wikitext input into sections, and either pull or replace
4381 * some particular section's text.
4383 * External callers should use the getSection and replaceSection methods.
4385 * @param $text Page wikitext
4386 * @param $section Numbered section. 0 pulls the text before the first
4387 * heading; other numbers will pull the given section
4388 * along with its lower-level subsections.
4389 * @param $mode One of "get" or "replace"
4390 * @param $newtext Replacement text for section data.
4391 * @return string for "get", the extracted section text.
4392 * for "replace", the whole page with the section replaced.
4394 private function extractSections( $text, $section, $mode, $newtext='' ) {
4395 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4396 # comments to be stripped as well)
4397 $striparray = array();
4399 $oldOutputType = $this->mOutputType
;
4400 $oldOptions = $this->mOptions
;
4401 $this->mOptions
= new ParserOptions();
4402 $this->setOutputType( OT_WIKI
);
4404 $striptext = $this->strip( $text, $striparray, true );
4406 $this->setOutputType( $oldOutputType );
4407 $this->mOptions
= $oldOptions;
4409 # now that we can be sure that no pseudo-sections are in the source,
4410 # split it up by section
4411 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4412 $comment = "(?:$uniq-!--.*?QINU)";
4417 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4419 (=+) # Should this be limited to 6?
4420 .+? # Section title...
4421 \\2 # Ending = count must match start
4428 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4435 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4436 (=+) # Should this be limited to 6?
4437 .+? # Section title...
4438 \\2 # Ending = count must match start
4439 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4448 PREG_SPLIT_DELIM_CAPTURE
);
4450 if( $mode == "get" ) {
4451 if( $section == 0 ) {
4452 // "Section 0" returns the content before any other section.
4457 } elseif( $mode == "replace" ) {
4458 if( $section == 0 ) {
4459 $rv = $newtext . "\n\n";
4468 for( $index = 1; $index < count( $secs ); ) {
4469 $headerLine = $secs[$index++
];
4470 if( $secs[$index] ) {
4472 $headerLevel = strlen( $secs[$index++
] );
4476 $headerLevel = intval( $secs[$index++
] );
4478 $content = $secs[$index++
];
4481 if( $mode == "get" ) {
4482 if( $count == $section ) {
4483 $rv = $headerLine . $content;
4484 $sectionLevel = $headerLevel;
4485 } elseif( $count > $section ) {
4486 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4487 $rv .= $headerLine . $content;
4489 // Broke out to a higher-level section
4493 } elseif( $mode == "replace" ) {
4494 if( $count < $section ) {
4495 $rv .= $headerLine . $content;
4496 } elseif( $count == $section ) {
4497 $rv .= $newtext . "\n\n";
4498 $sectionLevel = $headerLevel;
4499 } elseif( $count > $section ) {
4500 if( $headerLevel <= $sectionLevel ) {
4501 // Passed the section's sub-parts.
4505 $rv .= $headerLine . $content;
4510 # reinsert stripped tags
4511 $rv = $this->unstrip( $rv, $striparray );
4512 $rv = $this->unstripNoWiki( $rv, $striparray );
4518 * This function returns the text of a section, specified by a number ($section).
4519 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4520 * the first section before any such heading (section 0).
4522 * If a section contains subsections, these are also returned.
4524 * @param $text String: text to look in
4525 * @param $section Integer: section number
4526 * @return string text of the requested section
4528 function getSection( $text, $section ) {
4529 return $this->extractSections( $text, $section, "get" );
4532 function replaceSection( $oldtext, $section, $text ) {
4533 return $this->extractSections( $oldtext, $section, "replace", $text );
4540 * @package MediaWiki
4544 var $mText, # The output text
4545 $mLanguageLinks, # List of the full text of language links, in the order they appear
4546 $mCategories, # Map of category names to sort keys
4547 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4548 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4549 $mVersion, # Compatibility check
4550 $mTitleText, # title text of the chosen language variant
4551 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4552 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4553 $mImages, # DB keys of the images used, in the array key only
4554 $mExternalLinks, # External link URLs, in the key only
4555 $mHTMLtitle, # Display HTML title
4556 $mSubtitle, # Additional subtitle
4557 $mNewSection, # Show a new section link?
4558 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4560 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4561 $containsOldMagic = false, $titletext = '' )
4563 $this->mText
= $text;
4564 $this->mLanguageLinks
= $languageLinks;
4565 $this->mCategories
= $categoryLinks;
4566 $this->mContainsOldMagic
= $containsOldMagic;
4567 $this->mCacheTime
= '';
4568 $this->mVersion
= MW_PARSER_VERSION
;
4569 $this->mTitleText
= $titletext;
4570 $this->mLinks
= array();
4571 $this->mTemplates
= array();
4572 $this->mImages
= array();
4573 $this->mExternalLinks
= array();
4574 $this->mHTMLtitle
= "" ;
4575 $this->mSubtitle
= "" ;
4576 $this->mNewSection
= false;
4577 $this->mNoGallery
= false;
4580 function getText() { return $this->mText
; }
4581 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4582 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4583 function &getCategories() { return $this->mCategories
; }
4584 function getCacheTime() { return $this->mCacheTime
; }
4585 function getTitleText() { return $this->mTitleText
; }
4586 function &getLinks() { return $this->mLinks
; }
4587 function &getTemplates() { return $this->mTemplates
; }
4588 function &getImages() { return $this->mImages
; }
4589 function &getExternalLinks() { return $this->mExternalLinks
; }
4590 function getNoGallery() { return $this->mNoGallery
; }
4591 function getSubtitle() { return $this->mSubtitle
; }
4593 function containsOldMagic() { return $this->mContainsOldMagic
; }
4594 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4595 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4596 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4597 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4598 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4599 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4600 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4602 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4603 function addImage( $name ) { $this->mImages
[$name] = 1; }
4604 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4605 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4607 function setNewSection( $value ) {
4608 $this->mNewSection
= (bool)$value;
4610 function getNewSection() {
4611 return (bool)$this->mNewSection
;
4614 function addLink( $title, $id = null ) {
4615 $ns = $title->getNamespace();
4616 $dbk = $title->getDBkey();
4617 if ( !isset( $this->mLinks
[$ns] ) ) {
4618 $this->mLinks
[$ns] = array();
4620 if ( is_null( $id ) ) {
4621 $id = $title->getArticleID();
4623 $this->mLinks
[$ns][$dbk] = $id;
4626 function addTemplate( $title, $id ) {
4627 $ns = $title->getNamespace();
4628 $dbk = $title->getDBkey();
4629 if ( !isset( $this->mTemplates
[$ns] ) ) {
4630 $this->mTemplates
[$ns] = array();
4632 $this->mTemplates
[$ns][$dbk] = $id;
4636 * Return true if this cached output object predates the global or
4637 * per-article cache invalidation timestamps, or if it comes from
4638 * an incompatible older version.
4640 * @param string $touched the affected article's last touched timestamp
4644 function expired( $touched ) {
4645 global $wgCacheEpoch;
4646 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4647 $this->getCacheTime() < $touched ||
4648 $this->getCacheTime() <= $wgCacheEpoch ||
4649 !isset( $this->mVersion
) ||
4650 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4655 * Set options of the Parser
4657 * @package MediaWiki
4661 # All variables are private
4662 var $mUseTeX; # Use texvc to expand <math> tags
4663 var $mUseDynamicDates; # Use DateFormatter to format dates
4664 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4665 var $mAllowExternalImages; # Allow external images inline
4666 var $mAllowExternalImagesFrom; # If not, any exception?
4667 var $mSkin; # Reference to the preferred skin
4668 var $mDateFormat; # Date format index
4669 var $mEditSection; # Create "edit section" links
4670 var $mNumberHeadings; # Automatically number headings
4671 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4672 var $mTidy; # Ask for tidy cleanup
4673 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4674 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4675 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4677 var $mUser; # Stored user object, just used to initialise the skin
4679 function getUseTeX() { return $this->mUseTeX
; }
4680 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4681 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4682 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4683 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4684 function getEditSection() { return $this->mEditSection
; }
4685 function getNumberHeadings() { return $this->mNumberHeadings
; }
4686 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4687 function getTidy() { return $this->mTidy
; }
4688 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4689 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4690 function getRemoveComments() { return $this->mRemoveComments
; }
4692 function &getSkin() {
4693 if ( !isset( $this->mSkin
) ) {
4694 $this->mSkin
= $this->mUser
->getSkin();
4696 return $this->mSkin
;
4699 function getDateFormat() {
4700 if ( !isset( $this->mDateFormat
) ) {
4701 $this->mDateFormat
= $this->mUser
->getDatePreference();
4703 return $this->mDateFormat
;
4706 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4707 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4708 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4709 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4710 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4711 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4712 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4713 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4714 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4715 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4716 function setSkin( &$x ) { $this->mSkin
=& $x; }
4717 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4718 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4719 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4721 function ParserOptions( $user = null ) {
4722 $this->initialiseFromUser( $user );
4726 * Get parser options
4729 static function newFromUser( $user ) {
4730 return new ParserOptions( $user );
4733 /** Get user options */
4734 function initialiseFromUser( $userInput ) {
4735 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4736 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4737 $fname = 'ParserOptions::initialiseFromUser';
4738 wfProfileIn( $fname );
4739 if ( !$userInput ) {
4741 if ( isset( $wgUser ) ) {
4745 $user->setLoaded( true );
4748 $user =& $userInput;
4751 $this->mUser
= $user;
4753 $this->mUseTeX
= $wgUseTeX;
4754 $this->mUseDynamicDates
= $wgUseDynamicDates;
4755 $this->mInterwikiMagic
= $wgInterwikiMagic;
4756 $this->mAllowExternalImages
= $wgAllowExternalImages;
4757 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4758 $this->mSkin
= null; # Deferred
4759 $this->mDateFormat
= null; # Deferred
4760 $this->mEditSection
= true;
4761 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4762 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4763 $this->mTidy
= false;
4764 $this->mInterfaceMessage
= false;
4765 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4766 $this->mRemoveComments
= true;
4767 wfProfileOut( $fname );
4772 * Callback function used by Parser::replaceLinkHolders()
4773 * to substitute link placeholders.
4775 function &wfOutputReplaceMatches( $matches ) {
4776 global $wgOutputReplace;
4777 return $wgOutputReplace[$matches[1]];
4781 * Return the total number of articles
4783 function wfNumberOfArticles() {
4784 global $wgNumberOfArticles;
4787 return $wgNumberOfArticles;
4791 * Return the number of files
4793 function wfNumberOfFiles() {
4794 $fname = 'wfNumberOfFiles';
4796 wfProfileIn( $fname );
4797 $dbr =& wfGetDB( DB_SLAVE
);
4798 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4799 wfProfileOut( $fname );
4805 * Return the number of user accounts
4808 function wfNumberOfUsers() {
4809 wfProfileIn( 'wfNumberOfUsers' );
4810 $dbr =& wfGetDB( DB_SLAVE
);
4811 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4812 wfProfileOut( 'wfNumberOfUsers' );
4817 * Return the total number of pages
4820 function wfNumberOfPages() {
4821 wfProfileIn( 'wfNumberOfPages' );
4822 $dbr =& wfGetDB( DB_SLAVE
);
4823 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4824 wfProfileOut( 'wfNumberOfPages' );
4829 * Return the total number of admins
4833 function wfNumberOfAdmins() {
4834 static $admins = -1;
4835 wfProfileIn( 'wfNumberOfAdmins' );
4836 if( $admins == -1 ) {
4837 $dbr =& wfGetDB( DB_SLAVE
);
4838 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4840 wfProfileOut( 'wfNumberOfAdmins' );
4841 return (int)$admins;
4845 * Count the number of pages in a particular namespace
4847 * @param $ns Namespace
4850 function wfPagesInNs( $ns ) {
4851 static $pageCount = array();
4852 wfProfileIn( 'wfPagesInNs' );
4853 if( !isset( $pageCount[$ns] ) ) {
4854 $dbr =& wfGetDB( DB_SLAVE
);
4855 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4857 wfProfileOut( 'wfPagesInNs' );
4858 return (int)$pageCount[$ns];
4862 * Get various statistics from the database
4865 function wfLoadSiteStats() {
4866 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4867 $fname = 'wfLoadSiteStats';
4869 if ( -1 != $wgNumberOfArticles ) return;
4870 $dbr =& wfGetDB( DB_SLAVE
);
4871 $s = $dbr->selectRow( 'site_stats',
4872 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4873 array( 'ss_row_id' => 1 ), $fname
4876 if ( $s === false ) {
4879 $wgTotalViews = $s->ss_total_views
;
4880 $wgTotalEdits = $s->ss_total_edits
;
4881 $wgNumberOfArticles = $s->ss_good_articles
;
4887 * Basically replacing " > and < with HTML entities ( ", >, <)
4889 * @param $in String: text that might contain HTML tags.
4890 * @return string Escaped string
4892 function wfEscapeHTMLTagsOnly( $in ) {
4894 array( '"', '>', '<' ),
4895 array( '"', '>', '<' ),