3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
16 define( 'RLH_FOR_UPDATE', 1 );
18 # Allowed values for $mOutputType
19 define( 'OT_HTML', 1 );
20 define( 'OT_WIKI', 2 );
21 define( 'OT_MSG' , 3 );
22 define( 'OT_PREPROCESS', 4 );
24 # Flags for setFunctionHook
25 define( 'SFH_NO_HASH', 1 );
27 # string parameter for extractTags which will cause it
28 # to strip HTML comments in addition to regular
29 # <XML>-style tags. This should not be anything we
30 # may want to use in wikisyntax
31 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
33 # Constants needed for external link processing
34 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
35 # Everything except bracket, space, or control characters
36 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
37 # Including space, but excluding newlines
38 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
39 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
40 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
41 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
42 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
43 define( 'EXT_IMAGE_REGEX',
44 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
45 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
46 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
49 // State constants for the definition list colon extraction
50 define( 'MW_COLON_STATE_TEXT', 0 );
51 define( 'MW_COLON_STATE_TAG', 1 );
52 define( 'MW_COLON_STATE_TAGSTART', 2 );
53 define( 'MW_COLON_STATE_CLOSETAG', 3 );
54 define( 'MW_COLON_STATE_TAGSLASH', 4 );
55 define( 'MW_COLON_STATE_COMMENT', 5 );
56 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
57 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
62 * Processes wiki markup
65 * There are four main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
73 * removes HTML comments and expands templates
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
86 * * only within ParserOptions
97 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId; // ID to display in {{REVISIONID}} tags
125 $this->mTagHooks
= array();
126 $this->mFunctionHooks
= array();
127 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
128 $this->mFirstCall
= true;
132 * Do various kinds of initialisation on the first call of the parser
134 function firstCallInit() {
135 if ( !$this->mFirstCall
) {
139 wfProfileIn( __METHOD__
);
140 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
142 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
144 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
169 if ( $wgAllowDisplayTitle ) {
170 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
172 if ( $wgAllowSlowParserFunctions ) {
173 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
176 $this->initialiseVariables();
178 $this->mFirstCall
= false;
179 wfProfileOut( __METHOD__
);
187 function clearState() {
188 wfProfileIn( __METHOD__
);
189 if ( $this->mFirstCall
) {
190 $this->firstCallInit();
192 $this->mOutput
= new ParserOutput
;
193 $this->mAutonumber
= 0;
194 $this->mLastSection
= '';
195 $this->mDTopen
= false;
196 $this->mIncludeCount
= array();
197 $this->mStripState
= array();
198 $this->mArgStack
= array();
199 $this->mInPre
= false;
200 $this->mInterwikiLinkHolders
= array(
204 $this->mLinkHolders
= array(
205 'namespaces' => array(),
207 'queries' => array(),
211 $this->mRevisionId
= null;
214 * Prefix for temporary replacement strings for the multipass parser.
215 * \x07 should never appear in input as it's disallowed in XML.
216 * Using it at the front also gives us a little extra robustness
217 * since it shouldn't match when butted up against identifier-like
220 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
222 # Clear these on every parse, bug 4549
223 $this->mTemplates
= array();
224 $this->mTemplatePath
= array();
226 $this->mShowToc
= true;
227 $this->mForceTocPosition
= false;
228 $this->mIncludeSizes
= array(
234 wfRunHooks( 'ParserClearState', array( &$this ) );
235 wfProfileOut( __METHOD__
);
238 function setOutputType( $ot ) {
239 $this->mOutputType
= $ot;
242 'html' => $ot == OT_HTML
,
243 'wiki' => $ot == OT_WIKI
,
244 'msg' => $ot == OT_MSG
,
245 'pre' => $ot == OT_PREPROCESS
,
250 * Accessor for mUniqPrefix.
254 function uniqPrefix() {
255 return $this->mUniqPrefix
;
259 * Convert wikitext to HTML
260 * Do not call this function recursively.
263 * @param string $text Text we want to parse
264 * @param Title &$title A title object
265 * @param array $options
266 * @param boolean $linestart
267 * @param boolean $clearState
268 * @param int $revid number to pass in {{REVISIONID}}
269 * @return ParserOutput a ParserOutput
271 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
273 * First pass--just handle <nowiki> sections, pass the rest off
274 * to internalParse() which does all the real work.
277 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
278 $fname = 'Parser::parse-' . wfGetCaller();
279 wfProfileIn( __METHOD__
);
280 wfProfileIn( $fname );
286 $this->mOptions
= $options;
287 $this->mTitle
=& $title;
288 $oldRevisionId = $this->mRevisionId
;
289 if( $revid !== null ) {
290 $this->mRevisionId
= $revid;
292 $this->setOutputType( OT_HTML
);
294 //$text = $this->strip( $text, $this->mStripState );
295 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
296 $x =& $this->mStripState
;
298 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
299 $text = $this->strip( $text, $x );
300 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
302 $text = $this->internalParse( $text );
304 $text = $this->unstrip( $text, $this->mStripState
);
306 # Clean up special characters, only run once, next-to-last before doBlockLevels
308 # french spaces, last one Guillemet-left
309 # only if there is something before the space
310 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
311 # french spaces, Guillemet-right
312 '/(\\302\\253) /' => '\\1 ',
314 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
317 $text = $this->doBlockLevels( $text, $linestart );
319 $this->replaceLinkHolders( $text );
321 # the position of the parserConvert() call should not be changed. it
322 # assumes that the links are all replaced and the only thing left
323 # is the <nowiki> mark.
324 # Side-effects: this calls $this->mOutput->setTitleText()
325 $text = $wgContLang->parserConvert( $text, $this );
327 $text = $this->unstripNoWiki( $text, $this->mStripState
);
329 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
331 $text = Sanitizer
::normalizeCharReferences( $text );
333 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
334 $text = Parser
::tidy($text);
336 # attempt to sanitize at least some nesting problems
337 # (bug #2702 and quite a few others)
339 # ''Something [http://www.cool.com cool''] -->
340 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
341 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
342 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
343 # fix up an anchor inside another anchor, only
344 # at least for a single single nested link (bug 3695)
345 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
346 '\\1\\2</a>\\3</a>\\1\\4</a>',
347 # fix div inside inline elements- doBlockLevels won't wrap a line which
348 # contains a div, so fix it up here; replace
349 # div with escaped text
350 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
351 '\\1\\3<div\\5>\\6</div>\\8\\9',
352 # remove empty italic or bold tag pairs, some
353 # introduced by rules above
354 '/<([bi])><\/\\1>/' => '',
357 $text = preg_replace(
358 array_keys( $tidyregs ),
359 array_values( $tidyregs ),
363 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
365 # Information on include size limits, for the benefit of users who try to skirt them
366 if ( max( $this->mIncludeSizes
) > 1000 ) {
367 $max = $this->mOptions
->getMaxIncludeSize();
369 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
370 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
371 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
372 "Maximum: $max bytes\n" .
375 $this->mOutput
->setText( $text );
376 $this->mRevisionId
= $oldRevisionId;
377 wfProfileOut( $fname );
378 wfProfileOut( __METHOD__
);
380 return $this->mOutput
;
384 * Recursive parser entry point that can be called from an extension tag
387 function recursiveTagParse( $text ) {
388 wfProfileIn( __METHOD__
);
389 $x =& $this->mStripState
;
390 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
391 $text = $this->strip( $text, $x );
392 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
393 $text = $this->internalParse( $text );
394 wfProfileOut( __METHOD__
);
399 * Expand templates and variables in the text, producing valid, static wikitext.
400 * Also removes comments.
402 function preprocess( $text, $title, $options ) {
403 wfProfileIn( __METHOD__
);
405 $this->setOutputType( OT_PREPROCESS
);
406 $this->mOptions
= $options;
407 $this->mTitle
= $title;
408 $x =& $this->mStripState
;
409 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
410 $text = $this->strip( $text, $x );
411 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
412 if ( $this->mOptions
->getRemoveComments() ) {
413 $text = Sanitizer
::removeHTMLcomments( $text );
415 $text = $this->replaceVariables( $text );
416 $text = $this->unstrip( $text, $x );
417 $text = $this->unstripNowiki( $text, $x );
418 wfProfileOut( __METHOD__
);
423 * Get a random string
428 function getRandomString() {
429 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
432 function &getTitle() { return $this->mTitle
; }
433 function getOptions() { return $this->mOptions
; }
435 function getFunctionLang() {
436 global $wgLang, $wgContLang;
437 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
441 * Replaces all occurrences of HTML-style comments and the given tags
442 * in the text with a random marker and returns teh next text. The output
443 * parameter $matches will be an associative array filled with data in
445 * 'UNIQ-xxxxx' => array(
448 * array( 'param' => 'x' ),
449 * '<element param="x">tag content</element>' ) )
451 * @param $elements list of element names. Comments are always extracted.
452 * @param $text Source text string.
453 * @param $uniq_prefix
458 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
463 $taglist = implode( '|', $elements );
464 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
466 while ( '' != $text ) {
467 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
469 if( count( $p ) < 5 ) {
472 if( count( $p ) > 5 ) {
486 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
487 $stripped .= $marker;
489 if ( $close === '/>' ) {
490 // Empty element tag, <tag />
495 if( $element == '!--' ) {
498 $end = "/(<\\/$element\\s*>)/i";
500 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
502 if( count( $q ) < 3 ) {
503 # No end tag -- let it run out to the end of the text.
512 $matches[$marker] = array( $element,
514 Sanitizer
::decodeTagAttributes( $attributes ),
515 "<$element$attributes$close$content$tail" );
521 * Strips and renders nowiki, pre, math, hiero
522 * If $render is set, performs necessary rendering operations on plugins
523 * Returns the text, and fills an array with data needed in unstrip()
524 * If the $state is already a valid strip state, it adds to the state
526 * @param bool $stripcomments when set, HTML comments <!-- like this -->
527 * will be stripped in addition to other tags. This is important
528 * for section editing, where these comments cause confusion when
529 * counting the sections in the wikisource
531 * @param array dontstrip contains tags which should not be stripped;
532 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
536 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
537 wfProfileIn( __METHOD__
);
538 $render = ($this->mOutputType
== OT_HTML
);
540 $uniq_prefix = $this->mUniqPrefix
;
541 $commentState = array();
543 $elements = array_merge(
544 array( 'nowiki', 'gallery' ),
545 array_keys( $this->mTagHooks
) );
548 $elements[] = 'html';
550 if( $this->mOptions
->getUseTeX() ) {
551 $elements[] = 'math';
554 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
555 foreach ( $elements AS $k => $v ) {
556 if ( !in_array ( $v , $dontstrip ) ) continue;
557 unset ( $elements[$k] );
561 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
563 foreach( $matches as $marker => $data ) {
564 list( $element, $content, $params, $tag ) = $data;
566 $tagName = strtolower( $element );
567 wfProfileIn( __METHOD__
."-render-$tagName" );
571 if( substr( $tag, -3 ) == '-->' ) {
574 // Unclosed comment in input.
575 // Close it so later stripping can remove it
584 // Shouldn't happen otherwise. :)
586 $output = wfEscapeHTMLTagsOnly( $content );
589 $output = MathRenderer
::renderMath( $content );
592 $output = $this->renderImageGallery( $content, $params );
595 if( isset( $this->mTagHooks
[$tagName] ) ) {
596 $output = call_user_func_array( $this->mTagHooks
[$tagName],
597 array( $content, $params, $this ) );
599 throw new MWException( "Invalid call hook $element" );
602 wfProfileOut( __METHOD__
."-render-$tagName" );
604 // Just stripping tags; keep the source
608 // Unstrip the output, because unstrip() is no longer recursive so
609 // it won't do it itself
610 $output = $this->unstrip( $output, $state );
612 if( !$stripcomments && $element == '!--' ) {
613 $commentState[$marker] = $output;
614 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
615 $state['nowiki'][$marker] = $output;
617 $state['general'][$marker] = $output;
621 # Unstrip comments unless explicitly told otherwise.
622 # (The comments are always stripped prior to this point, so as to
623 # not invoke any extension tags / parser hooks contained within
625 if ( !$stripcomments ) {
626 // Put them all back and forget them
627 $text = strtr( $text, $commentState );
630 wfProfileOut( __METHOD__
);
635 * Restores pre, math, and other extensions removed by strip()
637 * always call unstripNoWiki() after this one
640 function unstrip( $text, $state ) {
641 if ( !isset( $state['general'] ) ) {
645 wfProfileIn( __METHOD__
);
646 # TODO: good candidate for FSS
647 $text = strtr( $text, $state['general'] );
648 wfProfileOut( __METHOD__
);
653 * Always call this after unstrip() to preserve the order
657 function unstripNoWiki( $text, $state ) {
658 if ( !isset( $state['nowiki'] ) ) {
662 wfProfileIn( __METHOD__
);
663 # TODO: good candidate for FSS
664 $text = strtr( $text, $state['nowiki'] );
665 wfProfileOut( __METHOD__
);
671 * Add an item to the strip state
672 * Returns the unique tag which must be inserted into the stripped text
673 * The tag will be replaced with the original text in unstrip()
677 function insertStripItem( $text, &$state ) {
678 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
682 $state['general'][$rnd] = $text;
687 * Interface with html tidy, used if $wgUseTidy = true.
688 * If tidy isn't able to correct the markup, the original will be
689 * returned in all its glory with a warning comment appended.
691 * Either the external tidy program or the in-process tidy extension
692 * will be used depending on availability. Override the default
693 * $wgTidyInternal setting to disable the internal if it's not working.
695 * @param string $text Hideous HTML input
696 * @return string Corrected HTML output
700 function tidy( $text ) {
701 global $wgTidyInternal;
702 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
703 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
704 '<head><title>test</title></head><body>'.$text.'</body></html>';
705 if( $wgTidyInternal ) {
706 $correctedtext = Parser
::internalTidy( $wrappedtext );
708 $correctedtext = Parser
::externalTidy( $wrappedtext );
710 if( is_null( $correctedtext ) ) {
711 wfDebug( "Tidy error detected!\n" );
712 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
714 return $correctedtext;
718 * Spawn an external HTML tidy process and get corrected markup back from it.
723 function externalTidy( $text ) {
724 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
725 $fname = 'Parser::externalTidy';
726 wfProfileIn( $fname );
731 $descriptorspec = array(
732 0 => array('pipe', 'r'),
733 1 => array('pipe', 'w'),
734 2 => array('file', '/dev/null', 'a')
737 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
738 if (is_resource($process)) {
739 // Theoretically, this style of communication could cause a deadlock
740 // here. If the stdout buffer fills up, then writes to stdin could
741 // block. This doesn't appear to happen with tidy, because tidy only
742 // writes to stdout after it's finished reading from stdin. Search
743 // for tidyParseStdin and tidySaveStdout in console/tidy.c
744 fwrite($pipes[0], $text);
746 while (!feof($pipes[1])) {
747 $cleansource .= fgets($pipes[1], 1024);
750 proc_close($process);
753 wfProfileOut( $fname );
755 if( $cleansource == '' && $text != '') {
756 // Some kind of error happened, so we couldn't get the corrected text.
757 // Just give up; we'll use the source text and append a warning.
765 * Use the HTML tidy PECL extension to use the tidy library in-process,
766 * saving the overhead of spawning a new process. Currently written to
767 * the PHP 4.3.x version of the extension, may not work on PHP 5.
769 * 'pear install tidy' should be able to compile the extension module.
774 function internalTidy( $text ) {
776 $fname = 'Parser::internalTidy';
777 wfProfileIn( $fname );
779 tidy_load_config( $wgTidyConf );
780 tidy_set_encoding( 'utf8' );
781 tidy_parse_string( $text );
783 if( tidy_get_status() == 2 ) {
784 // 2 is magic number for fatal error
785 // http://www.php.net/manual/en/function.tidy-get-status.php
788 $cleansource = tidy_get_output();
790 wfProfileOut( $fname );
795 * parse the wiki syntax used to render tables
799 function doTableStuff ( $t ) {
800 $fname = 'Parser::doTableStuff';
801 wfProfileIn( $fname );
803 $t = explode ( "\n" , $t ) ;
804 $td = array () ; # Is currently a td tag open?
805 $ltd = array () ; # Was it TD or TH?
806 $tr = array () ; # Is currently a tr tag open?
807 $ltr = array () ; # tr attributes
808 $has_opened_tr = array(); # Did this table open a <tr> element?
809 $indent_level = 0; # indent level of the table
810 foreach ( $t AS $k => $x )
813 $fc = substr ( $x , 0 , 1 ) ;
815 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
816 $indent_level = strlen( $matches[1] );
818 $attributes = $this->unstripForHTML( $matches[2] );
820 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
821 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
822 array_push ( $td , false ) ;
823 array_push ( $ltd , '' ) ;
824 array_push ( $tr , false ) ;
825 array_push ( $ltr , '' ) ;
826 array_push ( $has_opened_tr, false );
828 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
829 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
830 $z = "</table>" . substr ( $x , 2);
831 $l = array_pop ( $ltd ) ;
832 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
833 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
834 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
836 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
838 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
839 $x = substr ( $x , 1 ) ;
840 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
842 $l = array_pop ( $ltd ) ;
843 array_pop ( $has_opened_tr );
844 array_push ( $has_opened_tr , true ) ;
845 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
846 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
849 array_push ( $tr , false ) ;
850 array_push ( $td , false ) ;
851 array_push ( $ltd , '' ) ;
852 $attributes = $this->unstripForHTML( $x );
853 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
855 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
857 if ( '|+' == substr ( $x , 0 , 2 ) ) {
859 $x = substr ( $x , 1 ) ;
861 $after = substr ( $x , 1 ) ;
862 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
864 // Split up multiple cells on the same line.
865 // FIXME: This can result in improper nesting of tags processed
866 // by earlier parser steps, but should avoid splitting up eg
867 // attribute values containing literal "||".
868 $after = wfExplodeMarkup( '||', $after );
872 # Loop through each table cell
873 foreach ( $after AS $theline )
878 $tra = array_pop ( $ltr ) ;
879 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
880 array_push ( $tr , true ) ;
881 array_push ( $ltr , '' ) ;
882 array_pop ( $has_opened_tr );
883 array_push ( $has_opened_tr , true ) ;
886 $l = array_pop ( $ltd ) ;
887 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
890 } else if ( $fc == '!' ) {
892 } else if ( $fc == '+' ) {
897 array_push ( $ltd , $l ) ;
900 $y = explode ( '|' , $theline , 2 ) ;
901 # Note that a '|' inside an invalid link should not
902 # be mistaken as delimiting cell parameters
903 if ( strpos( $y[0], '[[' ) !== false ) {
904 $y = array ($theline);
906 if ( count ( $y ) == 1 )
907 $y = "{$z}<{$l}>{$y[0]}" ;
909 $attributes = $this->unstripForHTML( $y[0] );
910 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
913 array_push ( $td , true ) ;
918 # Closing open td, tr && table
919 while ( count ( $td ) > 0 )
921 $l = array_pop ( $ltd ) ;
922 if ( array_pop ( $td ) ) $t[] = '</td>' ;
923 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
924 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
928 $t = implode ( "\n" , $t ) ;
929 # special case: don't return empty table
930 if($t == "<table>\n<tr><td></td></tr>\n</table>")
932 wfProfileOut( $fname );
937 * Helper function for parse() that transforms wiki markup into
938 * HTML. Only called for $mOutputType == OT_HTML.
942 function internalParse( $text ) {
945 $fname = 'Parser::internalParse';
946 wfProfileIn( $fname );
948 # Hook to suspend the parser in this state
949 $x =& $this->mStripState
; // FIXME: Please check that this initialization is correct.
950 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
951 wfProfileOut( $fname );
955 # Remove <noinclude> tags and <includeonly> sections
956 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
957 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
958 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
960 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
962 $text = $this->replaceVariables( $text, $args );
964 // Tables need to come after variable replacement for things to work
965 // properly; putting them before other transformations should keep
966 // exciting things like link expansions from showing up in surprising
968 $text = $this->doTableStuff( $text );
970 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
972 $text = $this->stripToc( $text );
973 $this->stripNoGallery( $text );
974 $text = $this->doHeadings( $text );
975 if($this->mOptions
->getUseDynamicDates()) {
976 $df =& DateFormatter
::getInstance();
977 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
979 $text = $this->doAllQuotes( $text );
980 $text = $this->replaceInternalLinks( $text );
981 $text = $this->replaceExternalLinks( $text );
983 # replaceInternalLinks may sometimes leave behind
984 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
985 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
987 $text = $this->doMagicLinks( $text );
988 $text = $this->formatHeadings( $text, $isMain );
990 wfProfileOut( $fname );
995 * Replace special strings like "ISBN xxx" and "RFC xxx" with
996 * magic external links.
1000 function &doMagicLinks( &$text ) {
1001 wfProfileIn( __METHOD__
);
1002 $text = preg_replace_callback(
1004 <a.*?</a> | # Skip link text
1005 <.*?> | # Skip stuff inside HTML elements
1006 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1007 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
1008 )!x', array( &$this, 'magicLinkCallback' ), $text );
1009 wfProfileOut( __METHOD__
);
1013 function magicLinkCallback( $m ) {
1014 if ( substr( $m[0], 0, 1 ) == '<' ) {
1017 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1019 $num = strtr( $isbn, array(
1024 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1025 $text = '<a href="' .
1026 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1027 "\" class=\"internal\">ISBN $isbn</a>";
1029 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1033 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1035 $urlmsg = 'pubmedurl';
1038 throw new MWException( __METHOD__
.': unrecognised match type "' .
1039 substr($m[0], 0, 20 ) . '"' );
1042 $url = wfMsg( $urlmsg, $id);
1043 $sk =& $this->mOptions
->getSkin();
1044 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1045 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1051 * Parse headers and return html
1055 function doHeadings( $text ) {
1056 $fname = 'Parser::doHeadings';
1057 wfProfileIn( $fname );
1058 for ( $i = 6; $i >= 1; --$i ) {
1059 $h = str_repeat( '=', $i );
1060 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1061 "<h{$i}>\\1</h{$i}>\\2", $text );
1063 wfProfileOut( $fname );
1068 * Replace single quotes with HTML markup
1070 * @return string the altered text
1072 function doAllQuotes( $text ) {
1073 $fname = 'Parser::doAllQuotes';
1074 wfProfileIn( $fname );
1076 $lines = explode( "\n", $text );
1077 foreach ( $lines as $line ) {
1078 $outtext .= $this->doQuotes ( $line ) . "\n";
1080 $outtext = substr($outtext, 0,-1);
1081 wfProfileOut( $fname );
1086 * Helper function for doAllQuotes()
1089 function doQuotes( $text ) {
1090 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1091 if ( count( $arr ) == 1 )
1095 # First, do some preliminary work. This may shift some apostrophes from
1096 # being mark-up to being text. It also counts the number of occurrences
1097 # of bold and italics mark-ups.
1101 foreach ( $arr as $r )
1103 if ( ( $i %
2 ) == 1 )
1105 # If there are ever four apostrophes, assume the first is supposed to
1106 # be text, and the remaining three constitute mark-up for bold text.
1107 if ( strlen( $arr[$i] ) == 4 )
1112 # If there are more than 5 apostrophes in a row, assume they're all
1113 # text except for the last 5.
1114 else if ( strlen( $arr[$i] ) > 5 )
1116 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1119 # Count the number of occurrences of bold and italics mark-ups.
1120 # We are not counting sequences of five apostrophes.
1121 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1122 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1123 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1128 # If there is an odd number of both bold and italics, it is likely
1129 # that one of the bold ones was meant to be an apostrophe followed
1130 # by italics. Which one we cannot know for certain, but it is more
1131 # likely to be one that has a single-letter word before it.
1132 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1135 $firstsingleletterword = -1;
1136 $firstmultiletterword = -1;
1138 foreach ( $arr as $r )
1140 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1142 $x1 = substr ($arr[$i-1], -1);
1143 $x2 = substr ($arr[$i-1], -2, 1);
1145 if ($firstspace == -1) $firstspace = $i;
1146 } else if ($x2 == ' ') {
1147 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1149 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1155 # If there is a single-letter word, use it!
1156 if ($firstsingleletterword > -1)
1158 $arr [ $firstsingleletterword ] = "''";
1159 $arr [ $firstsingleletterword-1 ] .= "'";
1161 # If not, but there's a multi-letter word, use that one.
1162 else if ($firstmultiletterword > -1)
1164 $arr [ $firstmultiletterword ] = "''";
1165 $arr [ $firstmultiletterword-1 ] .= "'";
1167 # ... otherwise use the first one that has neither.
1168 # (notice that it is possible for all three to be -1 if, for example,
1169 # there is only one pentuple-apostrophe in the line)
1170 else if ($firstspace > -1)
1172 $arr [ $firstspace ] = "''";
1173 $arr [ $firstspace-1 ] .= "'";
1177 # Now let's actually convert our apostrophic mush to HTML!
1182 foreach ($arr as $r)
1186 if ($state == 'both')
1193 if (strlen ($r) == 2)
1196 { $output .= '</i>'; $state = ''; }
1197 else if ($state == 'bi')
1198 { $output .= '</i>'; $state = 'b'; }
1199 else if ($state == 'ib')
1200 { $output .= '</b></i><b>'; $state = 'b'; }
1201 else if ($state == 'both')
1202 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1203 else # $state can be 'b' or ''
1204 { $output .= '<i>'; $state .= 'i'; }
1206 else if (strlen ($r) == 3)
1209 { $output .= '</b>'; $state = ''; }
1210 else if ($state == 'bi')
1211 { $output .= '</i></b><i>'; $state = 'i'; }
1212 else if ($state == 'ib')
1213 { $output .= '</b>'; $state = 'i'; }
1214 else if ($state == 'both')
1215 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1216 else # $state can be 'i' or ''
1217 { $output .= '<b>'; $state .= 'b'; }
1219 else if (strlen ($r) == 5)
1222 { $output .= '</b><i>'; $state = 'i'; }
1223 else if ($state == 'i')
1224 { $output .= '</i><b>'; $state = 'b'; }
1225 else if ($state == 'bi')
1226 { $output .= '</i></b>'; $state = ''; }
1227 else if ($state == 'ib')
1228 { $output .= '</b></i>'; $state = ''; }
1229 else if ($state == 'both')
1230 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1231 else # ($state == '')
1232 { $buffer = ''; $state = 'both'; }
1237 # Now close all remaining tags. Notice that the order is important.
1238 if ($state == 'b' ||
$state == 'ib')
1240 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1244 if ($state == 'both')
1245 $output .= '<b><i>'.$buffer.'</i></b>';
1251 * Replace external links
1253 * Note: this is all very hackish and the order of execution matters a lot.
1254 * Make sure to run maintenance/parserTests.php if you change this code.
1258 function replaceExternalLinks( $text ) {
1260 $fname = 'Parser::replaceExternalLinks';
1261 wfProfileIn( $fname );
1263 $sk =& $this->mOptions
->getSkin();
1265 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1267 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1270 while ( $i<count( $bits ) ) {
1272 $protocol = $bits[$i++
];
1273 $text = $bits[$i++
];
1274 $trail = $bits[$i++
];
1276 # The characters '<' and '>' (which were escaped by
1277 # removeHTMLtags()) should not be included in
1278 # URLs, per RFC 2396.
1280 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1281 $text = substr($url, $m2[0][1]) . ' ' . $text;
1282 $url = substr($url, 0, $m2[0][1]);
1285 # If the link text is an image URL, replace it with an <img> tag
1286 # This happened by accident in the original parser, but some people used it extensively
1287 $img = $this->maybeMakeExternalImage( $text );
1288 if ( $img !== false ) {
1294 # Set linktype for CSS - if URL==text, link is essentially free
1295 $linktype = ($text == $url) ?
'free' : 'text';
1297 # No link text, e.g. [http://domain.tld/some.link]
1298 if ( $text == '' ) {
1299 # Autonumber if allowed. See bug #5918
1300 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1301 $text = '[' . ++
$this->mAutonumber
. ']';
1302 $linktype = 'autonumber';
1304 # Otherwise just use the URL
1305 $text = htmlspecialchars( $url );
1309 # Have link text, e.g. [http://domain.tld/some.link text]s
1311 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1314 $text = $wgContLang->markNoConversion($text);
1316 $url = Sanitizer
::cleanUrl( $url );
1318 # Process the trail (i.e. everything after this link up until start of the next link),
1319 # replacing any non-bracketed links
1320 $trail = $this->replaceFreeExternalLinks( $trail );
1322 # Use the encoded URL
1323 # This means that users can paste URLs directly into the text
1324 # Funny characters like ö aren't valid in URLs anyway
1325 # This was changed in August 2004
1326 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1328 # Register link in the output object.
1329 # Replace unnecessary URL escape codes with the referenced character
1330 # This prevents spammers from hiding links from the filters
1331 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1332 $this->mOutput
->addExternalLink( $pasteurized );
1335 wfProfileOut( $fname );
1340 * Replace anything that looks like a URL with a link
1343 function replaceFreeExternalLinks( $text ) {
1345 $fname = 'Parser::replaceFreeExternalLinks';
1346 wfProfileIn( $fname );
1348 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1349 $s = array_shift( $bits );
1352 $sk =& $this->mOptions
->getSkin();
1354 while ( $i < count( $bits ) ){
1355 $protocol = $bits[$i++
];
1356 $remainder = $bits[$i++
];
1359 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1360 # Found some characters after the protocol that look promising
1361 $url = $protocol . $m[1];
1364 # special case: handle urls as url args:
1365 # http://www.example.com/foo?=http://www.example.com/bar
1366 if(strlen($trail) == 0 &&
1368 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1369 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1372 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1377 # The characters '<' and '>' (which were escaped by
1378 # removeHTMLtags()) should not be included in
1379 # URLs, per RFC 2396.
1381 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1382 $trail = substr($url, $m2[0][1]) . $trail;
1383 $url = substr($url, 0, $m2[0][1]);
1386 # Move trailing punctuation to $trail
1388 # If there is no left bracket, then consider right brackets fair game too
1389 if ( strpos( $url, '(' ) === false ) {
1393 $numSepChars = strspn( strrev( $url ), $sep );
1394 if ( $numSepChars ) {
1395 $trail = substr( $url, -$numSepChars ) . $trail;
1396 $url = substr( $url, 0, -$numSepChars );
1399 $url = Sanitizer
::cleanUrl( $url );
1401 # Is this an external image?
1402 $text = $this->maybeMakeExternalImage( $url );
1403 if ( $text === false ) {
1404 # Not an image, make a link
1405 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1406 # Register it in the output object...
1407 # Replace unnecessary URL escape codes with their equivalent characters
1408 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1409 $this->mOutput
->addExternalLink( $pasteurized );
1411 $s .= $text . $trail;
1413 $s .= $protocol . $remainder;
1416 wfProfileOut( $fname );
1421 * Replace unusual URL escape codes with their equivalent characters
1425 * @fixme This can merge genuinely required bits in the path or query string,
1426 * breaking legit URLs. A proper fix would treat the various parts of
1427 * the URL differently; as a workaround, just use the output for
1428 * statistical records, not for actual linking/output.
1430 static function replaceUnusualEscapes( $url ) {
1431 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1432 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1436 * Callback function used in replaceUnusualEscapes().
1437 * Replaces unusual URL escape codes with their equivalent character
1441 private static function replaceUnusualEscapesCallback( $matches ) {
1442 $char = urldecode( $matches[0] );
1443 $ord = ord( $char );
1444 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1445 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1446 // No, shouldn't be escaped
1449 // Yes, leave it escaped
1455 * make an image if it's allowed, either through the global
1456 * option or through the exception
1459 function maybeMakeExternalImage( $url ) {
1460 $sk =& $this->mOptions
->getSkin();
1461 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1462 $imagesexception = !empty($imagesfrom);
1464 if ( $this->mOptions
->getAllowExternalImages()
1465 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1466 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1468 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1475 * Process [[ ]] wikilinks
1479 function replaceInternalLinks( $s ) {
1481 static $fname = 'Parser::replaceInternalLinks' ;
1483 wfProfileIn( $fname );
1485 wfProfileIn( $fname.'-setup' );
1487 # the % is needed to support urlencoded titles as well
1488 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1490 $sk =& $this->mOptions
->getSkin();
1492 #split the entire text string on occurences of [[
1493 $a = explode( '[[', ' ' . $s );
1494 #get the first element (all text up to first [[), and remove the space we added
1495 $s = array_shift( $a );
1496 $s = substr( $s, 1 );
1498 # Match a link having the form [[namespace:link|alternate]]trail
1500 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1501 # Match cases where there is no "]]", which might still be images
1502 static $e1_img = FALSE;
1503 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1504 # Match the end of a line for a word that's not followed by whitespace,
1505 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1506 $e2 = wfMsgForContent( 'linkprefix' );
1508 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1510 if( is_null( $this->mTitle
) ) {
1511 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1513 $nottalk = !$this->mTitle
->isTalkPage();
1515 if ( $useLinkPrefixExtension ) {
1517 if ( preg_match( $e2, $s, $m ) ) {
1518 $first_prefix = $m[2];
1520 $first_prefix = false;
1526 $selflink = $this->mTitle
->getPrefixedText();
1527 $useSubpages = $this->areSubpagesAllowed();
1528 wfProfileOut( $fname.'-setup' );
1530 # Loop for each link
1531 for ($k = 0; isset( $a[$k] ); $k++
) {
1533 if ( $useLinkPrefixExtension ) {
1534 wfProfileIn( $fname.'-prefixhandling' );
1535 if ( preg_match( $e2, $s, $m ) ) {
1543 $prefix = $first_prefix;
1544 $first_prefix = false;
1546 wfProfileOut( $fname.'-prefixhandling' );
1549 $might_be_img = false;
1551 wfProfileIn( "$fname-e1" );
1552 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1554 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1555 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1556 # the real problem is with the $e1 regex
1559 # Still some problems for cases where the ] is meant to be outside punctuation,
1560 # and no image is in sight. See bug 2095.
1563 substr( $m[3], 0, 1 ) === ']' &&
1564 strpos($text, '[') !== false
1567 $text .= ']'; # so that replaceExternalLinks($text) works later
1568 $m[3] = substr( $m[3], 1 );
1570 # fix up urlencoded title texts
1571 if( strpos( $m[1], '%' ) !== false ) {
1572 # Should anchors '#' also be rejected?
1573 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1576 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1577 $might_be_img = true;
1579 if ( strpos( $m[1], '%' ) !== false ) {
1580 $m[1] = urldecode($m[1]);
1583 } else { # Invalid form; output directly
1584 $s .= $prefix . '[[' . $line ;
1585 wfProfileOut( "$fname-e1" );
1588 wfProfileOut( "$fname-e1" );
1589 wfProfileIn( "$fname-misc" );
1591 # Don't allow internal links to pages containing
1592 # PROTO: where PROTO is a valid URL protocol; these
1593 # should be external links.
1594 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1595 $s .= $prefix . '[[' . $line ;
1599 # Make subpage if necessary
1600 if( $useSubpages ) {
1601 $link = $this->maybeDoSubpageLink( $m[1], $text );
1606 $noforce = (substr($m[1], 0, 1) != ':');
1608 # Strip off leading ':'
1609 $link = substr($link, 1);
1612 wfProfileOut( "$fname-misc" );
1613 wfProfileIn( "$fname-title" );
1614 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1616 $s .= $prefix . '[[' . $line;
1617 wfProfileOut( "$fname-title" );
1621 $ns = $nt->getNamespace();
1622 $iw = $nt->getInterWiki();
1623 wfProfileOut( "$fname-title" );
1625 if ($might_be_img) { # if this is actually an invalid link
1626 wfProfileIn( "$fname-might_be_img" );
1627 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1629 while (isset ($a[$k+
1]) ) {
1630 #look at the next 'line' to see if we can close it there
1631 $spliced = array_splice( $a, $k +
1, 1 );
1632 $next_line = array_shift( $spliced );
1633 $m = explode( ']]', $next_line, 3 );
1634 if ( count( $m ) == 3 ) {
1635 # the first ]] closes the inner link, the second the image
1637 $text .= "[[{$m[0]}]]{$m[1]}";
1640 } elseif ( count( $m ) == 2 ) {
1641 #if there's exactly one ]] that's fine, we'll keep looking
1642 $text .= "[[{$m[0]}]]{$m[1]}";
1644 #if $next_line is invalid too, we need look no further
1645 $text .= '[[' . $next_line;
1650 # we couldn't find the end of this imageLink, so output it raw
1651 #but don't ignore what might be perfectly normal links in the text we've examined
1652 $text = $this->replaceInternalLinks($text);
1653 $s .= "{$prefix}[[$link|$text";
1654 # note: no $trail, because without an end, there *is* no trail
1655 wfProfileOut( "$fname-might_be_img" );
1658 } else { #it's not an image, so output it raw
1659 $s .= "{$prefix}[[$link|$text";
1660 # note: no $trail, because without an end, there *is* no trail
1661 wfProfileOut( "$fname-might_be_img" );
1664 wfProfileOut( "$fname-might_be_img" );
1667 $wasblank = ( '' == $text );
1668 if( $wasblank ) $text = $link;
1670 # Link not escaped by : , create the various objects
1674 wfProfileIn( "$fname-interwiki" );
1675 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1676 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1677 $s = rtrim($s . "\n");
1678 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1679 wfProfileOut( "$fname-interwiki" );
1682 wfProfileOut( "$fname-interwiki" );
1684 if ( $ns == NS_IMAGE
) {
1685 wfProfileIn( "$fname-image" );
1686 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1687 # recursively parse links inside the image caption
1688 # actually, this will parse them in any other parameters, too,
1689 # but it might be hard to fix that, and it doesn't matter ATM
1690 $text = $this->replaceExternalLinks($text);
1691 $text = $this->replaceInternalLinks($text);
1693 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1694 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1695 $this->mOutput
->addImage( $nt->getDBkey() );
1697 wfProfileOut( "$fname-image" );
1700 # We still need to record the image's presence on the page
1701 $this->mOutput
->addImage( $nt->getDBkey() );
1703 wfProfileOut( "$fname-image" );
1707 if ( $ns == NS_CATEGORY
) {
1708 wfProfileIn( "$fname-category" );
1709 $s = rtrim($s . "\n"); # bug 87
1712 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1713 $sortkey = $this->mTitle
->getText();
1715 $sortkey = $this->mTitle
->getPrefixedText();
1720 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1721 $sortkey = str_replace( "\n", '', $sortkey );
1722 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1723 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1726 * Strip the whitespace Category links produce, see bug 87
1727 * @todo We might want to use trim($tmp, "\n") here.
1729 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1731 wfProfileOut( "$fname-category" );
1736 if( ( $nt->getPrefixedText() === $selflink ) &&
1737 ( $nt->getFragment() === '' ) ) {
1738 # Self-links are handled specially; generally de-link and change to bold.
1739 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1743 # Special and Media are pseudo-namespaces; no pages actually exist in them
1744 if( $ns == NS_MEDIA
) {
1745 $link = $sk->makeMediaLinkObj( $nt, $text );
1746 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1747 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1748 $this->mOutput
->addImage( $nt->getDBkey() );
1750 } elseif( $ns == NS_SPECIAL
) {
1751 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1753 } elseif( $ns == NS_IMAGE
) {
1754 $img = new Image( $nt );
1755 if( $img->exists() ) {
1756 // Force a blue link if the file exists; may be a remote
1757 // upload on the shared repository, and we want to see its
1758 // auto-generated page.
1759 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1760 $this->mOutput
->addLink( $nt );
1764 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1766 wfProfileOut( $fname );
1771 * Make a link placeholder. The text returned can be later resolved to a real link with
1772 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1773 * parsing of interwiki links, and secondly to allow all existence checks and
1774 * article length checks (for stub links) to be bundled into a single query.
1777 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1778 wfProfileIn( __METHOD__
);
1779 if ( ! is_object($nt) ) {
1781 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1783 # Separate the link trail from the rest of the link
1784 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1786 if ( $nt->isExternal() ) {
1787 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1788 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1789 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1791 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1792 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1793 $this->mLinkHolders
['queries'][] = $query;
1794 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1795 $this->mLinkHolders
['titles'][] = $nt;
1797 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1800 wfProfileOut( __METHOD__
);
1805 * Render a forced-blue link inline; protect against double expansion of
1806 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1807 * Since this little disaster has to split off the trail text to avoid
1808 * breaking URLs in the following text without breaking trails on the
1809 * wiki links, it's been made into a horrible function.
1812 * @param string $text
1813 * @param string $query
1814 * @param string $trail
1815 * @param string $prefix
1816 * @return string HTML-wikitext mix oh yuck
1818 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1819 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1820 $sk =& $this->mOptions
->getSkin();
1821 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1822 return $this->armorLinks( $link ) . $trail;
1826 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1827 * going to go through further parsing steps before inline URL expansion.
1829 * In particular this is important when using action=render, which causes
1830 * full URLs to be included.
1832 * Oh man I hate our multi-layer parser!
1834 * @param string more-or-less HTML
1835 * @return string less-or-more HTML with NOPARSE bits
1837 function armorLinks( $text ) {
1838 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1839 "{$this->mUniqPrefix}NOPARSE$1", $text );
1843 * Return true if subpage links should be expanded on this page.
1846 function areSubpagesAllowed() {
1847 # Some namespaces don't allow subpages
1848 global $wgNamespacesWithSubpages;
1849 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1853 * Handle link to subpage if necessary
1854 * @param string $target the source of the link
1855 * @param string &$text the link text, modified as necessary
1856 * @return string the full name of the link
1859 function maybeDoSubpageLink($target, &$text) {
1862 # :Foobar -- override special treatment of prefix (images, language links)
1863 # /Foobar -- convert to CurrentPage/Foobar
1864 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1865 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1866 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1868 $fname = 'Parser::maybeDoSubpageLink';
1869 wfProfileIn( $fname );
1870 $ret = $target; # default return value is no change
1873 $target = trim( $target );
1875 # Some namespaces don't allow subpages,
1876 # so only perform processing if subpages are allowed
1877 if( $this->areSubpagesAllowed() ) {
1878 # Look at the first character
1879 if( $target != '' && $target{0} == '/' ) {
1880 # / at end means we don't want the slash to be shown
1881 if( substr( $target, -1, 1 ) == '/' ) {
1882 $target = substr( $target, 1, -1 );
1885 $noslash = substr( $target, 1 );
1888 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1889 if( '' === $text ) {
1891 } # this might be changed for ugliness reasons
1893 # check for .. subpage backlinks
1895 $nodotdot = $target;
1896 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1898 $nodotdot = substr( $nodotdot, 3 );
1900 if($dotdotcount > 0) {
1901 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1902 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1903 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1904 # / at the end means don't show full path
1905 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1906 $nodotdot = substr( $nodotdot, 0, -1 );
1907 if( '' === $text ) {
1911 $nodotdot = trim( $nodotdot );
1912 if( $nodotdot != '' ) {
1913 $ret .= '/' . $nodotdot;
1920 wfProfileOut( $fname );
1925 * Used by doBlockLevels()
1928 /* private */ function closeParagraph() {
1930 if ( '' != $this->mLastSection
) {
1931 $result = '</' . $this->mLastSection
. ">\n";
1933 $this->mInPre
= false;
1934 $this->mLastSection
= '';
1937 # getCommon() returns the length of the longest common substring
1938 # of both arguments, starting at the beginning of both.
1940 /* private */ function getCommon( $st1, $st2 ) {
1941 $fl = strlen( $st1 );
1942 $shorter = strlen( $st2 );
1943 if ( $fl < $shorter ) { $shorter = $fl; }
1945 for ( $i = 0; $i < $shorter; ++
$i ) {
1946 if ( $st1{$i} != $st2{$i} ) { break; }
1950 # These next three functions open, continue, and close the list
1951 # element appropriate to the prefix character passed into them.
1953 /* private */ function openList( $char ) {
1954 $result = $this->closeParagraph();
1956 if ( '*' == $char ) { $result .= '<ul><li>'; }
1957 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1958 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1959 else if ( ';' == $char ) {
1960 $result .= '<dl><dt>';
1961 $this->mDTopen
= true;
1963 else { $result = '<!-- ERR 1 -->'; }
1968 /* private */ function nextItem( $char ) {
1969 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1970 else if ( ':' == $char ||
';' == $char ) {
1972 if ( $this->mDTopen
) { $close = '</dt>'; }
1973 if ( ';' == $char ) {
1974 $this->mDTopen
= true;
1975 return $close . '<dt>';
1977 $this->mDTopen
= false;
1978 return $close . '<dd>';
1981 return '<!-- ERR 2 -->';
1984 /* private */ function closeList( $char ) {
1985 if ( '*' == $char ) { $text = '</li></ul>'; }
1986 else if ( '#' == $char ) { $text = '</li></ol>'; }
1987 else if ( ':' == $char ) {
1988 if ( $this->mDTopen
) {
1989 $this->mDTopen
= false;
1990 $text = '</dt></dl>';
1992 $text = '</dd></dl>';
1995 else { return '<!-- ERR 3 -->'; }
2001 * Make lists from lines starting with ':', '*', '#', etc.
2004 * @return string the lists rendered as HTML
2006 function doBlockLevels( $text, $linestart ) {
2007 $fname = 'Parser::doBlockLevels';
2008 wfProfileIn( $fname );
2010 # Parsing through the text line by line. The main thing
2011 # happening here is handling of block-level elements p, pre,
2012 # and making lists from lines starting with * # : etc.
2014 $textLines = explode( "\n", $text );
2016 $lastPrefix = $output = '';
2017 $this->mDTopen
= $inBlockElem = false;
2019 $paragraphStack = false;
2021 if ( !$linestart ) {
2022 $output .= array_shift( $textLines );
2024 foreach ( $textLines as $oLine ) {
2025 $lastPrefixLength = strlen( $lastPrefix );
2026 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2027 $preOpenMatch = preg_match('/<pre/i', $oLine );
2028 if ( !$this->mInPre
) {
2029 # Multiple prefixes may abut each other for nested lists.
2030 $prefixLength = strspn( $oLine, '*#:;' );
2031 $pref = substr( $oLine, 0, $prefixLength );
2034 $pref2 = str_replace( ';', ':', $pref );
2035 $t = substr( $oLine, $prefixLength );
2036 $this->mInPre
= !empty($preOpenMatch);
2038 # Don't interpret any other prefixes in preformatted text
2040 $pref = $pref2 = '';
2045 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2046 # Same as the last item, so no need to deal with nesting or opening stuff
2047 $output .= $this->nextItem( substr( $pref, -1 ) );
2048 $paragraphStack = false;
2050 if ( substr( $pref, -1 ) == ';') {
2051 # The one nasty exception: definition lists work like this:
2052 # ; title : definition text
2053 # So we check for : in the remainder text to split up the
2054 # title and definition, without b0rking links.
2056 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2058 $output .= $term . $this->nextItem( ':' );
2061 } elseif( $prefixLength ||
$lastPrefixLength ) {
2062 # Either open or close a level...
2063 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2064 $paragraphStack = false;
2066 while( $commonPrefixLength < $lastPrefixLength ) {
2067 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2068 --$lastPrefixLength;
2070 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2071 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2073 while ( $prefixLength > $commonPrefixLength ) {
2074 $char = substr( $pref, $commonPrefixLength, 1 );
2075 $output .= $this->openList( $char );
2077 if ( ';' == $char ) {
2078 # FIXME: This is dupe of code above
2079 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2081 $output .= $term . $this->nextItem( ':' );
2084 ++
$commonPrefixLength;
2086 $lastPrefix = $pref2;
2088 if( 0 == $prefixLength ) {
2089 wfProfileIn( "$fname-paragraph" );
2090 # No prefix (not in list)--go to paragraph mode
2091 // XXX: use a stack for nestable elements like span, table and div
2092 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2093 $closematch = preg_match(
2094 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2095 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2096 if ( $openmatch or $closematch ) {
2097 $paragraphStack = false;
2098 #Â TODO bug 5718: paragraph closed
2099 $output .= $this->closeParagraph();
2100 if ( $preOpenMatch and !$preCloseMatch ) {
2101 $this->mInPre
= true;
2103 if ( $closematch ) {
2104 $inBlockElem = false;
2106 $inBlockElem = true;
2108 } else if ( !$inBlockElem && !$this->mInPre
) {
2109 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2111 if ($this->mLastSection
!= 'pre') {
2112 $paragraphStack = false;
2113 $output .= $this->closeParagraph().'<pre>';
2114 $this->mLastSection
= 'pre';
2116 $t = substr( $t, 1 );
2119 if ( '' == trim($t) ) {
2120 if ( $paragraphStack ) {
2121 $output .= $paragraphStack.'<br />';
2122 $paragraphStack = false;
2123 $this->mLastSection
= 'p';
2125 if ($this->mLastSection
!= 'p' ) {
2126 $output .= $this->closeParagraph();
2127 $this->mLastSection
= '';
2128 $paragraphStack = '<p>';
2130 $paragraphStack = '</p><p>';
2134 if ( $paragraphStack ) {
2135 $output .= $paragraphStack;
2136 $paragraphStack = false;
2137 $this->mLastSection
= 'p';
2138 } else if ($this->mLastSection
!= 'p') {
2139 $output .= $this->closeParagraph().'<p>';
2140 $this->mLastSection
= 'p';
2145 wfProfileOut( "$fname-paragraph" );
2147 // somewhere above we forget to get out of pre block (bug 785)
2148 if($preCloseMatch && $this->mInPre
) {
2149 $this->mInPre
= false;
2151 if ($paragraphStack === false) {
2155 while ( $prefixLength ) {
2156 $output .= $this->closeList( $pref2{$prefixLength-1} );
2159 if ( '' != $this->mLastSection
) {
2160 $output .= '</' . $this->mLastSection
. '>';
2161 $this->mLastSection
= '';
2164 wfProfileOut( $fname );
2169 * Split up a string on ':', ignoring any occurences inside tags
2170 * to prevent illegal overlapping.
2171 * @param string $str the string to split
2172 * @param string &$before set to everything before the ':'
2173 * @param string &$after set to everything after the ':'
2174 * return string the position of the ':', or false if none found
2176 function findColonNoLinks($str, &$before, &$after) {
2177 $fname = 'Parser::findColonNoLinks';
2178 wfProfileIn( $fname );
2180 $pos = strpos( $str, ':' );
2181 if( $pos === false ) {
2183 wfProfileOut( $fname );
2187 $lt = strpos( $str, '<' );
2188 if( $lt === false ||
$lt > $pos ) {
2189 // Easy; no tag nesting to worry about
2190 $before = substr( $str, 0, $pos );
2191 $after = substr( $str, $pos+
1 );
2192 wfProfileOut( $fname );
2196 // Ugly state machine to walk through avoiding tags.
2197 $state = MW_COLON_STATE_TEXT
;
2199 $len = strlen( $str );
2200 for( $i = 0; $i < $len; $i++
) {
2204 // (Using the number is a performance hack for common cases)
2205 case 0: // MW_COLON_STATE_TEXT:
2208 // Could be either a <start> tag or an </end> tag
2209 $state = MW_COLON_STATE_TAGSTART
;
2214 $before = substr( $str, 0, $i );
2215 $after = substr( $str, $i +
1 );
2216 wfProfileOut( $fname );
2219 // Embedded in a tag; don't break it.
2222 // Skip ahead looking for something interesting
2223 $colon = strpos( $str, ':', $i );
2224 if( $colon === false ) {
2225 // Nothing else interesting
2226 wfProfileOut( $fname );
2229 $lt = strpos( $str, '<', $i );
2230 if( $stack === 0 ) {
2231 if( $lt === false ||
$colon < $lt ) {
2233 $before = substr( $str, 0, $colon );
2234 $after = substr( $str, $colon +
1 );
2235 wfProfileOut( $fname );
2239 if( $lt === false ) {
2240 // Nothing else interesting to find; abort!
2241 // We're nested, but there's no close tags left. Abort!
2244 // Skip ahead to next tag start
2246 $state = MW_COLON_STATE_TAGSTART
;
2249 case 1: // MW_COLON_STATE_TAG:
2254 $state = MW_COLON_STATE_TEXT
;
2257 // Slash may be followed by >?
2258 $state = MW_COLON_STATE_TAGSLASH
;
2264 case 2: // MW_COLON_STATE_TAGSTART:
2267 $state = MW_COLON_STATE_CLOSETAG
;
2270 $state = MW_COLON_STATE_COMMENT
;
2273 // Illegal early close? This shouldn't happen D:
2274 $state = MW_COLON_STATE_TEXT
;
2277 $state = MW_COLON_STATE_TAG
;
2280 case 3: // MW_COLON_STATE_CLOSETAG:
2285 wfDebug( "Invalid input in $fname; too many close tags\n" );
2286 wfProfileOut( $fname );
2289 $state = MW_COLON_STATE_TEXT
;
2292 case MW_COLON_STATE_TAGSLASH
:
2294 // Yes, a self-closed tag <blah/>
2295 $state = MW_COLON_STATE_TEXT
;
2297 // Probably we're jumping the gun, and this is an attribute
2298 $state = MW_COLON_STATE_TAG
;
2301 case 5: // MW_COLON_STATE_COMMENT:
2303 $state = MW_COLON_STATE_COMMENTDASH
;
2306 case MW_COLON_STATE_COMMENTDASH
:
2308 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2310 $state = MW_COLON_STATE_COMMENT
;
2313 case MW_COLON_STATE_COMMENTDASHDASH
:
2315 $state = MW_COLON_STATE_TEXT
;
2317 $state = MW_COLON_STATE_COMMENT
;
2321 throw new MWException( "State machine error in $fname" );
2325 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2328 wfProfileOut( $fname );
2333 * Return value of a magic variable (like PAGENAME)
2337 function getVariableValue( $index ) {
2338 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2341 * Some of these require message or data lookups and can be
2342 * expensive to check many times.
2344 static $varCache = array();
2345 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2346 if ( isset( $varCache[$index] ) ) {
2347 return $varCache[$index];
2352 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2355 global $wgLocaltimezone;
2356 if ( isset( $wgLocaltimezone ) ) {
2357 $oldtz = getenv( 'TZ' );
2358 putenv( 'TZ='.$wgLocaltimezone );
2360 $localTimestamp = date( 'YmdHis', $ts );
2361 $localMonth = date( 'm', $ts );
2362 $localMonthName = date( 'n', $ts );
2363 $localDay = date( 'j', $ts );
2364 $localDay2 = date( 'd', $ts );
2365 $localDayOfWeek = date( 'w', $ts );
2366 $localWeek = date( 'W', $ts );
2367 $localYear = date( 'Y', $ts );
2368 $localHour = date( 'H', $ts );
2369 if ( isset( $wgLocaltimezone ) ) {
2370 putenv( 'TZ='.$oldtz );
2374 case 'currentmonth':
2375 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2376 case 'currentmonthname':
2377 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2378 case 'currentmonthnamegen':
2379 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2380 case 'currentmonthabbrev':
2381 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2383 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2385 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2387 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2388 case 'localmonthname':
2389 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2390 case 'localmonthnamegen':
2391 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2392 case 'localmonthabbrev':
2393 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2395 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2397 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2399 return $this->mTitle
->getText();
2401 return $this->mTitle
->getPartialURL();
2402 case 'fullpagename':
2403 return $this->mTitle
->getPrefixedText();
2404 case 'fullpagenamee':
2405 return $this->mTitle
->getPrefixedURL();
2407 return $this->mTitle
->getSubpageText();
2408 case 'subpagenamee':
2409 return $this->mTitle
->getSubpageUrlForm();
2410 case 'basepagename':
2411 return $this->mTitle
->getBaseText();
2412 case 'basepagenamee':
2413 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2414 case 'talkpagename':
2415 if( $this->mTitle
->canTalk() ) {
2416 $talkPage = $this->mTitle
->getTalkPage();
2417 return $talkPage->getPrefixedText();
2421 case 'talkpagenamee':
2422 if( $this->mTitle
->canTalk() ) {
2423 $talkPage = $this->mTitle
->getTalkPage();
2424 return $talkPage->getPrefixedUrl();
2428 case 'subjectpagename':
2429 $subjPage = $this->mTitle
->getSubjectPage();
2430 return $subjPage->getPrefixedText();
2431 case 'subjectpagenamee':
2432 $subjPage = $this->mTitle
->getSubjectPage();
2433 return $subjPage->getPrefixedUrl();
2435 return $this->mRevisionId
;
2437 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 ) );
2438 case 'revisionday2':
2439 return substr( wfRevisionTimestamp( $this->mRevisionId
), 6, 2 );
2440 case 'revisionmonth':
2441 return intval( substr( wfRevisionTimestamp( $this->mRevisionId
), 4, 2 ) );
2442 case 'revisionyear':
2443 return substr( wfRevisionTimestamp( $this->mRevisionId
), 0, 4 );
2444 case 'revisiontimestamp':
2445 return wfRevisionTimestamp( $this->mRevisionId
);
2447 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2449 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2451 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2453 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2454 case 'subjectspace':
2455 return $this->mTitle
->getSubjectNsText();
2456 case 'subjectspacee':
2457 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2458 case 'currentdayname':
2459 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2461 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2463 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2465 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2467 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2468 // int to remove the padding
2469 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2471 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2472 case 'localdayname':
2473 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2475 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2477 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2479 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2481 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2482 // int to remove the padding
2483 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2485 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2486 case 'numberofarticles':
2487 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2488 case 'numberoffiles':
2489 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2490 case 'numberofusers':
2491 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2492 case 'numberofpages':
2493 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2494 case 'numberofadmins':
2495 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2496 case 'currenttimestamp':
2497 return $varCache[$index] = wfTimestampNow();
2498 case 'localtimestamp':
2499 return $varCache[$index] = $localTimestamp;
2500 case 'currentversion':
2501 return $varCache[$index] = SpecialVersion
::getVersion();
2507 return $wgServerName;
2509 return $wgScriptPath;
2510 case 'directionmark':
2511 return $wgContLang->getDirMark();
2512 case 'contentlanguage':
2513 global $wgContLanguageCode;
2514 return $wgContLanguageCode;
2517 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2525 * initialise the magic variables (like CURRENTMONTHNAME)
2529 function initialiseVariables() {
2530 $fname = 'Parser::initialiseVariables';
2531 wfProfileIn( $fname );
2532 $variableIDs = MagicWord
::getVariableIDs();
2534 $this->mVariables
= array();
2535 foreach ( $variableIDs as $id ) {
2536 $mw =& MagicWord
::get( $id );
2537 $mw->addToArray( $this->mVariables
, $id );
2539 wfProfileOut( $fname );
2543 * parse any parentheses in format ((title|part|part))
2544 * and call callbacks to get a replacement text for any found piece
2546 * @param string $text The text to parse
2547 * @param array $callbacks rules in form:
2548 * '{' => array( # opening parentheses
2549 * 'end' => '}', # closing parentheses
2550 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2551 * 3 => callback # replacement callback to call if {{{..}}} is found
2554 * 'min' => 2, # Minimum parenthesis count in cb
2555 * 'max' => 3, # Maximum parenthesis count in cb
2558 function replace_callback ($text, $callbacks) {
2559 wfProfileIn( __METHOD__
);
2560 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2561 $lastOpeningBrace = -1; # last not closed parentheses
2563 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2566 while ( $i < strlen( $text ) ) {
2567 # Find next opening brace, closing brace or pipe
2568 if ( $lastOpeningBrace == -1 ) {
2569 $currentClosing = '';
2570 $search = $validOpeningBraces;
2572 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2573 $search = $validOpeningBraces . '|' . $currentClosing;
2576 $i +
= strcspn( $text, $search, $i );
2577 if ( $i < strlen( $text ) ) {
2578 if ( $text[$i] == '|' ) {
2580 } elseif ( $text[$i] == $currentClosing ) {
2582 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2584 $rule = $callbacks[$text[$i]];
2586 # Some versions of PHP have a strcspn which stops on null characters
2587 # Ignore and continue
2596 if ( $found == 'open' ) {
2597 # found opening brace, let's add it to parentheses stack
2598 $piece = array('brace' => $text[$i],
2599 'braceEnd' => $rule['end'],
2603 # count opening brace characters
2604 $piece['count'] = strspn( $text, $piece['brace'], $i );
2605 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2606 $i +
= $piece['count'];
2608 # we need to add to stack only if opening brace count is enough for one of the rules
2609 if ( $piece['count'] >= $rule['min'] ) {
2610 $lastOpeningBrace ++
;
2611 $openingBraceStack[$lastOpeningBrace] = $piece;
2613 } elseif ( $found == 'close' ) {
2614 # lets check if it is enough characters for closing brace
2615 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2616 $count = strspn( $text, $text[$i], $i, $maxCount );
2618 # check for maximum matching characters (if there are 5 closing
2619 # characters, we will probably need only 3 - depending on the rules)
2621 $matchingCallback = null;
2622 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2623 if ( $count > $cbType['max'] ) {
2624 # The specified maximum exists in the callback array, unless the caller
2626 $matchingCount = $cbType['max'];
2628 # Count is less than the maximum
2629 # Skip any gaps in the callback array to find the true largest match
2630 # Need to use array_key_exists not isset because the callback can be null
2631 $matchingCount = $count;
2632 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2637 if ($matchingCount <= 0) {
2641 $matchingCallback = $cbType['cb'][$matchingCount];
2643 # let's set a title or last part (if '|' was found)
2644 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2645 $openingBraceStack[$lastOpeningBrace]['title'] =
2646 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2647 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2649 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2650 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2651 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2654 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2655 $pieceEnd = $i +
$matchingCount;
2657 if( is_callable( $matchingCallback ) ) {
2659 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2660 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2661 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2662 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2664 # finally we can call a user callback and replace piece of text
2665 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2666 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2667 $i = $pieceStart +
strlen($replaceWith);
2669 # null value for callback means that parentheses should be parsed, but not replaced
2670 $i +
= $matchingCount;
2673 # reset last opening parentheses, but keep it in case there are unused characters
2674 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2675 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2676 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2679 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2680 $openingBraceStack[$lastOpeningBrace--] = null;
2682 if ($matchingCount < $piece['count']) {
2683 $piece['count'] -= $matchingCount;
2684 $piece['startAt'] -= $matchingCount;
2685 $piece['partStart'] = $piece['startAt'];
2686 # do we still qualify for any callback with remaining count?
2687 $currentCbList = $callbacks[$piece['brace']]['cb'];
2688 while ( $piece['count'] ) {
2689 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2690 $lastOpeningBrace++
;
2691 $openingBraceStack[$lastOpeningBrace] = $piece;
2697 } elseif ( $found == 'pipe' ) {
2698 # lets set a title if it is a first separator, or next part otherwise
2699 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2700 $openingBraceStack[$lastOpeningBrace]['title'] =
2701 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2702 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2703 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2705 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2706 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2707 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2709 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2713 wfProfileOut( __METHOD__
);
2718 * Replace magic variables, templates, and template arguments
2719 * with the appropriate text. Templates are substituted recursively,
2720 * taking care to avoid infinite loops.
2722 * Note that the substitution depends on value of $mOutputType:
2723 * OT_WIKI: only {{subst:}} templates
2724 * OT_MSG: only magic variables
2725 * OT_HTML: all templates and magic variables
2727 * @param string $tex The text to transform
2728 * @param array $args Key-value pairs representing template parameters to substitute
2729 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2732 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2733 # Prevent too big inclusions
2734 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2738 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2739 wfProfileIn( $fname );
2741 # This function is called recursively. To keep track of arguments we need a stack:
2742 array_push( $this->mArgStack
, $args );
2744 $braceCallbacks = array();
2746 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2748 if ( $this->mOutputType
!= OT_MSG
) {
2749 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2751 if ( $braceCallbacks ) {
2755 'cb' => $braceCallbacks,
2756 'min' => $argsOnly ?
3 : 2,
2757 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2761 'cb' => array(2=>null),
2766 $text = $this->replace_callback ($text, $callbacks);
2768 array_pop( $this->mArgStack
);
2770 wfProfileOut( $fname );
2775 * Replace magic variables
2778 function variableSubstitution( $matches ) {
2780 $fname = 'Parser::variableSubstitution';
2781 $varname = $wgContLang->lc($matches[1]);
2782 wfProfileIn( $fname );
2784 if ( $this->mOutputType
== OT_WIKI
) {
2785 # Do only magic variables prefixed by SUBST
2786 $mwSubst =& MagicWord
::get( 'subst' );
2787 if (!$mwSubst->matchStartAndRemove( $varname ))
2789 # Note that if we don't substitute the variable below,
2790 # we don't remove the {{subst:}} magic word, in case
2791 # it is a template rather than a magic variable.
2793 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2794 $id = $this->mVariables
[$varname];
2795 # Now check if we did really match, case sensitive or not
2796 $mw =& MagicWord
::get( $id );
2797 if ($mw->match($matches[1])) {
2798 $text = $this->getVariableValue( $id );
2799 $this->mOutput
->mContainsOldMagic
= true;
2801 $text = $matches[0];
2804 $text = $matches[0];
2806 wfProfileOut( $fname );
2811 * Return the text of a template, after recursively
2812 * replacing any variables or templates within the template.
2814 * @param array $piece The parts of the template
2815 * $piece['text']: matched text
2816 * $piece['title']: the title, i.e. the part before the |
2817 * $piece['parts']: the parameter array
2818 * @return string the text of the template
2821 function braceSubstitution( $piece ) {
2822 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2823 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2824 wfProfileIn( $fname );
2825 wfProfileIn( __METHOD__
.'-setup' );
2828 $found = false; # $text has been filled
2829 $nowiki = false; # wiki markup in $text should be escaped
2830 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2831 $noargs = false; # Don't replace triple-brace arguments in $text
2832 $replaceHeadings = false; # Make the edit section links go to the template not the article
2833 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2834 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2836 # Title object, where $text came from
2842 # $part1 is the bit before the first |, and must contain only title characters
2843 # $args is a list of arguments, starting from index 0, not including $part1
2845 $titleText = $part1 = $piece['title'];
2846 # If the third subpattern matched anything, it will start with |
2848 if (null == $piece['parts']) {
2849 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2850 if ($replaceWith != $piece['text']) {
2851 $text = $replaceWith;
2858 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2859 wfProfileOut( __METHOD__
.'-setup' );
2862 wfProfileIn( __METHOD__
.'-modifiers' );
2864 $mwSubst =& MagicWord
::get( 'subst' );
2865 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2866 # One of two possibilities is true:
2867 # 1) Found SUBST but not in the PST phase
2868 # 2) Didn't find SUBST and in the PST phase
2869 # In either case, return without further processing
2870 $text = $piece['text'];
2877 # MSG, MSGNW and RAW
2880 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2881 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2884 # Remove obsolete MSG:
2885 $mwMsg =& MagicWord
::get( 'msg' );
2886 $mwMsg->matchStartAndRemove( $part1 );
2890 $mwRaw =& MagicWord
::get( 'raw' );
2891 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2892 $forceRawInterwiki = true;
2895 wfProfileOut( __METHOD__
.'-modifiers' );
2899 wfProfileIn( __METHOD__
. '-pfunc' );
2901 $colonPos = strpos( $part1, ':' );
2902 if ( $colonPos !== false ) {
2903 # Case sensitive functions
2904 $function = substr( $part1, 0, $colonPos );
2905 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2906 $function = $this->mFunctionSynonyms
[1][$function];
2908 # Case insensitive functions
2909 $function = strtolower( $function );
2910 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2911 $function = $this->mFunctionSynonyms
[0][$function];
2917 $funcArgs = array_map( 'trim', $args );
2918 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2919 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2922 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2926 if ( is_array( $result ) ) {
2927 if ( isset( $result[0] ) ) {
2928 $text = $linestart . $result[0];
2929 unset( $result[0] );
2932 // Extract flags into the local scope
2933 // This allows callers to set flags such as nowiki, noparse, found, etc.
2936 $text = $linestart . $result;
2940 wfProfileOut( __METHOD__
. '-pfunc' );
2943 # Template table test
2945 # Did we encounter this template already? If yes, it is in the cache
2946 # and we need to check for loops.
2947 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2950 # Infinite loop test
2951 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2955 $text = $linestart .
2956 "[[$part1]]<!-- WARNING: template loop detected -->";
2957 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2959 # set $text to cached message.
2960 $text = $linestart . $this->mTemplates
[$piece['title']];
2964 # Load from database
2965 $lastPathLevel = $this->mTemplatePath
;
2967 wfProfileIn( __METHOD__
. '-loadtpl' );
2969 # declaring $subpage directly in the function call
2970 # does not work correctly with references and breaks
2971 # {{/subpage}}-style inclusions
2973 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2974 if ($subpage !== '') {
2975 $ns = $this->mTitle
->getNamespace();
2977 $title = Title
::newFromText( $part1, $ns );
2980 if ( !is_null( $title ) ) {
2981 $titleText = $title->getPrefixedText();
2982 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2983 # Check for language variants if the template is not found
2984 if($checkVariantLink && $title->getArticleID() == 0){
2985 $wgContLang->findVariantLink($part1, $title);
2988 if ( !$title->isExternal() ) {
2989 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2990 $text = SpecialPage
::capturePath( $title );
2991 if ( is_string( $text ) ) {
2996 $this->disableCache();
2999 $articleContent = $this->fetchTemplate( $title );
3000 if ( $articleContent !== false ) {
3002 $text = $articleContent;
3003 $replaceHeadings = true;
3007 # If the title is valid but undisplayable, make a link to it
3008 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3009 $text = "[[:$titleText]]";
3012 } elseif ( $title->isTrans() ) {
3013 // Interwiki transclusion
3014 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3015 $text = $this->interwikiTransclude( $title, 'render' );
3019 $text = $this->interwikiTransclude( $title, 'raw' );
3020 $replaceHeadings = true;
3025 # Template cache array insertion
3026 # Use the original $piece['title'] not the mangled $part1, so that
3027 # modifiers such as RAW: produce separate cache entries
3030 // A special page; don't store it in the template cache.
3032 $this->mTemplates
[$piece['title']] = $text;
3034 $text = $linestart . $text;
3037 wfProfileOut( __METHOD__
. '-loadtpl' );
3040 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3041 # Error, oversize inclusion
3042 $text = $linestart .
3043 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3048 # Recursive parsing, escaping and link table handling
3049 # Only for HTML output
3050 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3051 $text = wfEscapeWikiText( $text );
3052 } elseif ( !$this->ot
['msg'] && $found ) {
3054 $assocArgs = array();
3056 # Clean up argument array
3057 $assocArgs = array();
3059 foreach( $args as $arg ) {
3060 $eqpos = strpos( $arg, '=' );
3061 if ( $eqpos === false ) {
3062 $assocArgs[$index++
] = $arg;
3064 $name = trim( substr( $arg, 0, $eqpos ) );
3065 $value = trim( substr( $arg, $eqpos+
1 ) );
3066 if ( $value === false ) {
3069 if ( $name !== false ) {
3070 $assocArgs[$name] = $value;
3075 # Add a new element to the templace recursion path
3076 $this->mTemplatePath
[$part1] = 1;
3080 # If there are any <onlyinclude> tags, only include them
3081 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3083 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3085 foreach ($m[1] as $piece)
3088 # Remove <noinclude> sections and <includeonly> tags
3089 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3090 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3092 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3093 # Strip <nowiki>, <pre>, etc.
3094 $text = $this->strip( $text, $this->mStripState
);
3095 if ( $this->ot
['html'] ) {
3096 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3097 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3098 $text = Sanitizer
::removeHTMLcomments( $text );
3101 $text = $this->replaceVariables( $text, $assocArgs );
3103 # If the template begins with a table or block-level
3104 # element, it should be treated as beginning a new line.
3105 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3106 $text = "\n" . $text;
3108 } elseif ( !$noargs ) {
3109 # $noparse and !$noargs
3110 # Just replace the arguments, not any double-brace items
3111 # This is used for rendered interwiki transclusion
3112 $text = $this->replaceVariables( $text, $assocArgs, true );
3115 # Prune lower levels off the recursion check path
3116 $this->mTemplatePath
= $lastPathLevel;
3118 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3119 # Error, oversize inclusion
3120 $text = $linestart .
3121 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3127 wfProfileOut( $fname );
3128 return $piece['text'];
3130 wfProfileIn( __METHOD__
. '-placeholders' );
3132 # Replace raw HTML by a placeholder
3133 # Add a blank line preceding, to prevent it from mucking up
3134 # immediately preceding headings
3135 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3137 # replace ==section headers==
3138 # XXX this needs to go away once we have a better parser.
3139 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3140 if( !is_null( $title ) )
3141 $encodedname = base64_encode($title->getPrefixedDBkey());
3143 $encodedname = base64_encode("");
3144 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3145 PREG_SPLIT_DELIM_CAPTURE
);
3148 for( $i = 0; $i < count($m); $i +
= 2 ) {
3150 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3152 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3157 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3158 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3159 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3165 wfProfileOut( __METHOD__
. '-placeholders' );
3168 # Prune lower levels off the recursion check path
3169 $this->mTemplatePath
= $lastPathLevel;
3172 wfProfileOut( $fname );
3173 return $piece['text'];
3175 wfProfileOut( $fname );
3181 * Fetch the unparsed text of a template and register a reference to it.
3183 function fetchTemplate( $title ) {
3185 // Loop to fetch the article, with up to 1 redirect
3186 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3187 $rev = Revision
::newFromTitle( $title );
3188 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3192 $text = $rev->getText();
3193 if ( $text === false ) {
3197 $title = Title
::newFromRedirect( $text );
3203 * Transclude an interwiki link.
3205 function interwikiTransclude( $title, $action ) {
3206 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3208 if (!$wgEnableScaryTranscluding)
3209 return wfMsg('scarytranscludedisabled');
3211 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3212 // But we'll handle it generally anyway
3213 if ( $title->getNamespace() ) {
3214 // Use the canonical namespace, which should work anywhere
3215 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3217 $articleName = $title->getDBkey();
3220 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3221 $url .= "?action=$action";
3222 if (strlen($url) > 255)
3223 return wfMsg('scarytranscludetoolong');
3224 return $this->fetchScaryTemplateMaybeFromCache($url);
3227 function fetchScaryTemplateMaybeFromCache($url) {
3228 global $wgTranscludeCacheExpiry;
3229 $dbr =& wfGetDB(DB_SLAVE
);
3230 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3231 array('tc_url' => $url));
3233 $time = $obj->tc_time
;
3234 $text = $obj->tc_contents
;
3235 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3240 $text = Http
::get($url);
3242 return wfMsg('scarytranscludefailed', $url);
3244 $dbw =& wfGetDB(DB_MASTER
);
3245 $dbw->replace('transcache', array('tc_url'), array(
3247 'tc_time' => time(),
3248 'tc_contents' => $text));
3254 * Triple brace replacement -- used for template arguments
3257 function argSubstitution( $matches ) {
3258 $arg = trim( $matches['title'] );
3259 $text = $matches['text'];
3260 $inputArgs = end( $this->mArgStack
);
3262 if ( array_key_exists( $arg, $inputArgs ) ) {
3263 $text = $inputArgs[$arg];
3264 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3265 null != $matches['parts'] && count($matches['parts']) > 0) {
3266 $text = $matches['parts'][0];
3268 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3269 $text = $matches['text'] .
3270 '<!-- WARNING: argument omitted, expansion size too large -->';
3277 * Increment an include size counter
3279 * @param string $type The type of expansion
3280 * @param integer $size The size of the text
3281 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3283 function incrementIncludeSize( $type, $size ) {
3284 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3287 $this->mIncludeSizes
[$type] +
= $size;
3293 * Detect __NOGALLERY__ magic word and set a placeholder
3295 function stripNoGallery( &$text ) {
3296 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3298 $mw = MagicWord
::get( 'nogallery' );
3299 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3303 * Detect __TOC__ magic word and set a placeholder
3305 function stripToc( $text ) {
3306 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3308 $mw = MagicWord
::get( 'notoc' );
3309 if( $mw->matchAndRemove( $text ) ) {
3310 $this->mShowToc
= false;
3313 $mw = MagicWord
::get( 'toc' );
3314 if( $mw->match( $text ) ) {
3315 $this->mShowToc
= true;
3316 $this->mForceTocPosition
= true;
3318 // Set a placeholder. At the end we'll fill it in with the TOC.
3319 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3321 // Only keep the first one.
3322 $text = $mw->replace( '', $text );
3328 * This function accomplishes several tasks:
3329 * 1) Auto-number headings if that option is enabled
3330 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3331 * 3) Add a Table of contents on the top for users who have enabled the option
3332 * 4) Auto-anchor headings
3334 * It loops through all headlines, collects the necessary data, then splits up the
3335 * string and re-inserts the newly formatted headlines.
3337 * @param string $text
3338 * @param boolean $isMain
3341 function formatHeadings( $text, $isMain=true ) {
3342 global $wgMaxTocLevel, $wgContLang;
3344 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3345 if( !$this->mTitle
->userCanEdit() ) {
3348 $showEditLink = $this->mOptions
->getEditSection();
3351 # Inhibit editsection links if requested in the page
3352 $esw =& MagicWord
::get( 'noeditsection' );
3353 if( $esw->matchAndRemove( $text ) ) {
3357 # Get all headlines for numbering them and adding funky stuff like [edit]
3358 # links - this is for later, but we need the number of headlines right now
3360 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3362 # if there are fewer than 4 headlines in the article, do not show TOC
3363 # unless it's been explicitly enabled.
3364 $enoughToc = $this->mShowToc
&&
3365 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3367 # Allow user to stipulate that a page should have a "new section"
3368 # link added via __NEWSECTIONLINK__
3369 $mw =& MagicWord
::get( 'newsectionlink' );
3370 if( $mw->matchAndRemove( $text ) )
3371 $this->mOutput
->setNewSection( true );
3373 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3374 # override above conditions and always show TOC above first header
3375 $mw =& MagicWord
::get( 'forcetoc' );
3376 if ($mw->matchAndRemove( $text ) ) {
3377 $this->mShowToc
= true;
3381 # Never ever show TOC if no headers
3382 if( $numMatches < 1 ) {
3386 # We need this to perform operations on the HTML
3387 $sk =& $this->mOptions
->getSkin();
3391 $sectionCount = 0; # headlineCount excluding template sections
3393 # Ugh .. the TOC should have neat indentation levels which can be
3394 # passed to the skin functions. These are determined here
3398 $sublevelCount = array();
3399 $levelCount = array();
3406 foreach( $matches[3] as $headline ) {
3408 $templatetitle = '';
3409 $templatesection = 0;
3412 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3414 $templatetitle = base64_decode($mat[1]);
3415 $templatesection = 1 +
(int)base64_decode($mat[2]);
3416 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3420 $prevlevel = $level;
3421 $prevtoclevel = $toclevel;
3423 $level = $matches[1][$headlineCount];
3425 if( $doNumberHeadings ||
$enoughToc ) {
3427 if ( $level > $prevlevel ) {
3428 # Increase TOC level
3430 $sublevelCount[$toclevel] = 0;
3431 if( $toclevel<$wgMaxTocLevel ) {
3432 $toc .= $sk->tocIndent();
3435 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3436 # Decrease TOC level, find level to jump to
3438 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3439 # Can only go down to level 1
3442 for ($i = $toclevel; $i > 0; $i--) {
3443 if ( $levelCount[$i] == $level ) {
3444 # Found last matching level
3448 elseif ( $levelCount[$i] < $level ) {
3449 # Found first matching level below current level
3455 if( $toclevel<$wgMaxTocLevel ) {
3456 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3460 # No change in level, end TOC line
3461 if( $toclevel<$wgMaxTocLevel ) {
3462 $toc .= $sk->tocLineEnd();
3466 $levelCount[$toclevel] = $level;
3468 # count number of headlines for each level
3469 @$sublevelCount[$toclevel]++
;
3471 for( $i = 1; $i <= $toclevel; $i++
) {
3472 if( !empty( $sublevelCount[$i] ) ) {
3476 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3482 # The canonized header is a version of the header text safe to use for links
3483 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3484 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3485 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3487 # Remove link placeholders by the link text.
3488 # <!--LINK number-->
3490 # link text with suffix
3491 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3492 "\$this->mLinkHolders['texts'][\$1]",
3493 $canonized_headline );
3494 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3495 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3496 $canonized_headline );
3499 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3500 $tocline = trim( $canonized_headline );
3501 # Save headline for section edit hint before it's escaped
3502 $headline_hint = trim( $canonized_headline );
3503 $canonized_headline = Sanitizer
::escapeId( $tocline );
3504 $refers[$headlineCount] = $canonized_headline;
3506 # count how many in assoc. array so we can track dupes in anchors
3507 @$refers[$canonized_headline]++
;
3508 $refcount[$headlineCount]=$refers[$canonized_headline];
3510 # Don't number the heading if it is the only one (looks silly)
3511 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3512 # the two are different if the line contains a link
3513 $headline=$numbering . ' ' . $headline;
3516 # Create the anchor for linking from the TOC to the section
3517 $anchor = $canonized_headline;
3518 if($refcount[$headlineCount] > 1 ) {
3519 $anchor .= '_' . $refcount[$headlineCount];
3521 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3522 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3524 # give headline the correct <h#> tag
3525 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><div class=\"mw-h$level\">";
3527 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3528 if ( empty( $head[$headlineCount] ) ) {
3529 $head[$headlineCount] = '';
3532 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3534 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3536 // Yes, the headline logically goes before the edit section. It can't
3537 // be put there, however, because of bugs in IE's and Firefox's float
3538 // rendering. See <https://bugzilla.mozilla.org/show_bug.cgi?id=50630>.
3539 $head[$headlineCount] .= " <h$level{$matches[2][$headlineCount]}$headline</h$level></div>";
3547 if( $toclevel<$wgMaxTocLevel ) {
3548 $toc .= $sk->tocUnindent( $toclevel - 1 );
3550 $toc = $sk->tocList( $toc );
3553 # split up and insert constructed headlines
3555 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3558 foreach( $blocks as $block ) {
3559 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3560 # This is the [edit] link that appears for the top block of text when
3561 # section editing is enabled
3563 # Disabled because it broke block formatting
3564 # For example, a bullet point in the top line
3565 # $full .= $sk->editSectionLink(0);
3568 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3569 # Top anchor now in skin
3573 if( !empty( $head[$i] ) ) {
3578 if( $this->mForceTocPosition
) {
3579 return str_replace( '<!--MWTOC-->', $toc, $full );
3586 * Transform wiki markup when saving a page by doing \r\n -> \n
3587 * conversion, substitting signatures, {{subst:}} templates, etc.
3589 * @param string $text the text to transform
3590 * @param Title &$title the Title object for the current article
3591 * @param User &$user the User object describing the current user
3592 * @param ParserOptions $options parsing options
3593 * @param bool $clearState whether to clear the parser state first
3594 * @return string the altered wiki markup
3597 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3598 $this->mOptions
= $options;
3599 $this->mTitle
=& $title;
3600 $this->setOutputType( OT_WIKI
);
3602 if ( $clearState ) {
3603 $this->clearState();
3606 $stripState = false;
3610 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3611 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3612 $text = $this->pstPass2( $text, $stripState, $user );
3613 $text = $this->unstrip( $text, $stripState );
3614 $text = $this->unstripNoWiki( $text, $stripState );
3619 * Pre-save transform helper function
3622 function pstPass2( $text, &$stripState, $user ) {
3623 global $wgContLang, $wgLocaltimezone;
3625 /* Note: This is the timestamp saved as hardcoded wikitext to
3626 * the database, we use $wgContLang here in order to give
3627 * everyone the same signature and use the default one rather
3628 * than the one selected in each user's preferences.
3630 if ( isset( $wgLocaltimezone ) ) {
3631 $oldtz = getenv( 'TZ' );
3632 putenv( 'TZ='.$wgLocaltimezone );
3634 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3635 ' (' . date( 'T' ) . ')';
3636 if ( isset( $wgLocaltimezone ) ) {
3637 putenv( 'TZ='.$oldtz );
3640 # Variable replacement
3641 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3642 $text = $this->replaceVariables( $text );
3644 # Strip out <nowiki> etc. added via replaceVariables
3645 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3648 $sigText = $this->getUserSig( $user );
3649 $text = strtr( $text, array(
3651 '~~~~' => "$sigText $d",
3655 # Context links: [[|name]] and [[name (context)|]]
3657 global $wgLegalTitleChars;
3658 $tc = "[$wgLegalTitleChars]";
3659 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3661 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3662 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3663 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3665 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3666 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3667 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3669 $t = $this->mTitle
->getText();
3671 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3672 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3673 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3674 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3676 # if there's no context, don't bother duplicating the title
3677 $text = preg_replace( $p2, '[[\\1]]', $text );
3680 # Trim trailing whitespace
3681 # __END__ tag allows for trailing
3682 # whitespace to be deliberately included
3683 $text = rtrim( $text );
3684 $mw =& MagicWord
::get( 'end' );
3685 $mw->matchAndRemove( $text );
3691 * Fetch the user's signature text, if any, and normalize to
3692 * validated, ready-to-insert wikitext.
3698 function getUserSig( &$user ) {
3699 $username = $user->getName();
3700 $nickname = $user->getOption( 'nickname' );
3701 $nickname = $nickname === '' ?
$username : $nickname;
3703 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3704 # Sig. might contain markup; validate this
3705 if( $this->validateSig( $nickname ) !== false ) {
3706 # Validated; clean up (if needed) and return it
3707 return $this->cleanSig( $nickname, true );
3709 # Failed to validate; fall back to the default
3710 $nickname = $username;
3711 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3715 // Make sure nickname doesnt get a sig in a sig
3716 $nickname = $this->cleanSigInSig( $nickname );
3718 # If we're still here, make it a link to the user page
3719 $userpage = $user->getUserPage();
3720 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3724 * Check that the user's signature contains no bad XML
3726 * @param string $text
3727 * @return mixed An expanded string, or false if invalid.
3729 function validateSig( $text ) {
3730 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3734 * Clean up signature text
3736 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3737 * 2) Substitute all transclusions
3739 * @param string $text
3740 * @param $parsing Whether we're cleaning (preferences save) or parsing
3741 * @return string Signature text
3743 function cleanSig( $text, $parsing = false ) {
3745 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3747 $substWord = MagicWord
::get( 'subst' );
3748 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3749 $substText = '{{' . $substWord->getSynonym( 0 );
3751 $text = preg_replace( $substRegex, $substText, $text );
3752 $text = $this->cleanSigInSig( $text );
3753 $text = $this->replaceVariables( $text );
3755 $this->clearState();
3760 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3761 * @param string $text
3762 * @return string Signature text with /~{3,5}/ removed
3764 function cleanSigInSig( $text ) {
3765 $text = preg_replace( '/~{3,5}/', '', $text );
3770 * Set up some variables which are usually set up in parse()
3771 * so that an external function can call some class members with confidence
3774 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3775 $this->mTitle
=& $title;
3776 $this->mOptions
= $options;
3777 $this->setOutputType( $outputType );
3778 if ( $clearState ) {
3779 $this->clearState();
3784 * Transform a MediaWiki message by replacing magic variables.
3786 * @param string $text the text to transform
3787 * @param ParserOptions $options options
3788 * @return string the text with variables substituted
3791 function transformMsg( $text, $options ) {
3793 static $executing = false;
3795 $fname = "Parser::transformMsg";
3797 # Guard against infinite recursion
3803 wfProfileIn($fname);
3806 $this->mTitle
= $wgTitle;
3808 $this->mTitle
= Title
::newFromText('msg');
3810 $this->mOptions
= $options;
3811 $this->setOutputType( OT_MSG
);
3812 $this->clearState();
3813 $text = $this->replaceVariables( $text );
3816 wfProfileOut($fname);
3821 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3822 * The callback should have the following form:
3823 * function myParserHook( $text, $params, &$parser ) { ... }
3825 * Transform and return $text. Use $parser for any required context, e.g. use
3826 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3830 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3831 * @param mixed $callback The callback function (and object) to use for the tag
3833 * @return The old value of the mTagHooks array associated with the hook
3835 function setHook( $tag, $callback ) {
3836 $tag = strtolower( $tag );
3837 $oldVal = @$this->mTagHooks
[$tag];
3838 $this->mTagHooks
[$tag] = $callback;
3844 * Create a function, e.g. {{sum:1|2|3}}
3845 * The callback function should have the form:
3846 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3848 * The callback may either return the text result of the function, or an array with the text
3849 * in element 0, and a number of flags in the other elements. The names of the flags are
3850 * specified in the keys. Valid flags are:
3851 * found The text returned is valid, stop processing the template. This
3853 * nowiki Wiki markup in the return value should be escaped
3854 * noparse Unsafe HTML tags should not be stripped, etc.
3855 * noargs Don't replace triple-brace arguments in the return value
3856 * isHTML The returned text is HTML, armour it against wikitext transformation
3860 * @param string $id The magic word ID
3861 * @param mixed $callback The callback function (and object) to use
3862 * @param integer $flags a combination of the following flags:
3863 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3865 * @return The old callback function for this name, if any
3867 function setFunctionHook( $id, $callback, $flags = 0 ) {
3868 $oldVal = @$this->mFunctionHooks
[$id];
3869 $this->mFunctionHooks
[$id] = $callback;
3871 # Add to function cache
3872 $mw = MagicWord
::get( $id );
3874 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3876 $synonyms = $mw->getSynonyms();
3877 $sensitive = intval( $mw->isCaseSensitive() );
3879 foreach ( $synonyms as $syn ) {
3881 if ( !$sensitive ) {
3882 $syn = strtolower( $syn );
3885 if ( !( $flags & SFH_NO_HASH
) ) {
3888 # Remove trailing colon
3889 if ( substr( $syn, -1, 1 ) == ':' ) {
3890 $syn = substr( $syn, 0, -1 );
3892 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3898 * Get all registered function hook identifiers
3902 function getFunctionHooks() {
3903 return array_keys( $this->mFunctionHooks
);
3907 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3908 * Placeholders created in Skin::makeLinkObj()
3909 * Returns an array of links found, indexed by PDBK:
3913 * $options is a bit field, RLH_FOR_UPDATE to select for update
3915 function replaceLinkHolders( &$text, $options = 0 ) {
3917 global $wgOutputReplace;
3920 $fname = 'Parser::replaceLinkHolders';
3921 wfProfileIn( $fname );
3925 $sk =& $this->mOptions
->getSkin();
3926 $linkCache =& LinkCache
::singleton();
3928 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3929 wfProfileIn( $fname.'-check' );
3930 $dbr =& wfGetDB( DB_SLAVE
);
3931 $page = $dbr->tableName( 'page' );
3932 $threshold = $wgUser->getOption('stubthreshold');
3935 asort( $this->mLinkHolders
['namespaces'] );
3940 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3942 $title = $this->mLinkHolders
['titles'][$key];
3944 # Skip invalid entries.
3945 # Result will be ugly, but prevents crash.
3946 if ( is_null( $title ) ) {
3949 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3951 # Check if it's a static known link, e.g. interwiki
3952 if ( $title->isAlwaysKnown() ) {
3953 $colours[$pdbk] = 1;
3954 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3955 $colours[$pdbk] = 1;
3956 $this->mOutput
->addLink( $title, $id );
3957 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3958 $colours[$pdbk] = 0;
3960 # Not in the link cache, add it to the query
3961 if ( !isset( $current ) ) {
3963 $query = "SELECT page_id, page_namespace, page_title";
3964 if ( $threshold > 0 ) {
3965 $query .= ', page_len, page_is_redirect';
3967 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3968 } elseif ( $current != $ns ) {
3970 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3975 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3980 if ( $options & RLH_FOR_UPDATE
) {
3981 $query .= ' FOR UPDATE';
3984 $res = $dbr->query( $query, $fname );
3986 # Fetch data and form into an associative array
3987 # non-existent = broken
3990 while ( $s = $dbr->fetchObject($res) ) {
3991 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3992 $pdbk = $title->getPrefixedDBkey();
3993 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3994 $this->mOutput
->addLink( $title, $s->page_id
);
3996 if ( $threshold > 0 ) {
3997 $size = $s->page_len
;
3998 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3999 $colours[$pdbk] = 1;
4001 $colours[$pdbk] = 2;
4004 $colours[$pdbk] = 1;
4008 wfProfileOut( $fname.'-check' );
4010 # Do a second query for different language variants of links (if needed)
4011 if($wgContLang->hasVariants()){
4012 $linkBatch = new LinkBatch();
4013 $variantMap = array(); // maps $pdbkey_Variant => $pdbkey_original
4015 // Add variants of links to link batch
4016 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4017 $title = $this->mLinkHolders
['titles'][$key];
4018 if ( is_null( $title ) )
4021 $pdbk = $title->getPrefixedDBkey();
4023 // generate all variants of the link title text
4024 $allTextVariants = $wgContLang->convertLinkToAllVariants($title->getText());
4026 // if link was not found (in first query), add all variants to query
4027 if ( !isset($colours[$pdbk]) ){
4028 foreach($allTextVariants as $textVariant){
4029 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4030 if(is_null($variantTitle)) continue;
4031 $linkBatch->addObj( $variantTitle );
4032 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4038 if(!$linkBatch->isEmpty()){
4040 $titleClause = $linkBatch->constructSet('page', $dbr);
4042 $variantQuery = "SELECT page_id, page_namespace, page_title";
4043 if ( $threshold > 0 ) {
4044 $variantQuery .= ', page_len, page_is_redirect';
4047 $variantQuery .= " FROM $page WHERE $titleClause";
4048 if ( $options & RLH_FOR_UPDATE
) {
4049 $variantQuery .= ' FOR UPDATE';
4052 $varRes = $dbr->query( $variantQuery, $fname );
4054 // for each found variants, figure out link holders and replace
4055 while ( $s = $dbr->fetchObject($varRes) ) {
4057 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4058 $varPdbk = $variantTitle->getPrefixedDBkey();
4059 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4060 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4062 $holderKeys = $variantMap[$varPdbk];
4064 // loop over link holders
4065 foreach($holderKeys as $key){
4066 $title = $this->mLinkHolders
['titles'][$key];
4067 if ( is_null( $title ) ) continue;
4069 $pdbk = $title->getPrefixedDBkey();
4071 if(!isset($colours[$pdbk])){
4072 // found link in some of the variants, replace the link holder data
4073 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4074 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4076 // set pdbk and colour
4077 $pdbks[$key] = $varPdbk;
4078 if ( $threshold > 0 ) {
4079 $size = $s->page_len
;
4080 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4081 $colours[$varPdbk] = 1;
4083 $colours[$varPdbk] = 2;
4087 $colours[$varPdbk] = 1;
4095 # Construct search and replace arrays
4096 wfProfileIn( $fname.'-construct' );
4097 $wgOutputReplace = array();
4098 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4099 $pdbk = $pdbks[$key];
4100 $searchkey = "<!--LINK $key-->";
4101 $title = $this->mLinkHolders
['titles'][$key];
4102 if ( empty( $colours[$pdbk] ) ) {
4103 $linkCache->addBadLinkObj( $title );
4104 $colours[$pdbk] = 0;
4105 $this->mOutput
->addLink( $title, 0 );
4106 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4107 $this->mLinkHolders
['texts'][$key],
4108 $this->mLinkHolders
['queries'][$key] );
4109 } elseif ( $colours[$pdbk] == 1 ) {
4110 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4111 $this->mLinkHolders
['texts'][$key],
4112 $this->mLinkHolders
['queries'][$key] );
4113 } elseif ( $colours[$pdbk] == 2 ) {
4114 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4115 $this->mLinkHolders
['texts'][$key],
4116 $this->mLinkHolders
['queries'][$key] );
4119 wfProfileOut( $fname.'-construct' );
4122 wfProfileIn( $fname.'-replace' );
4124 $text = preg_replace_callback(
4125 '/(<!--LINK .*?-->)/',
4126 "wfOutputReplaceMatches",
4129 wfProfileOut( $fname.'-replace' );
4132 # Now process interwiki link holders
4133 # This is quite a bit simpler than internal links
4134 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4135 wfProfileIn( $fname.'-interwiki' );
4136 # Make interwiki link HTML
4137 $wgOutputReplace = array();
4138 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4139 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4140 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4143 $text = preg_replace_callback(
4144 '/<!--IWLINK (.*?)-->/',
4145 "wfOutputReplaceMatches",
4147 wfProfileOut( $fname.'-interwiki' );
4150 wfProfileOut( $fname );
4155 * Replace <!--LINK--> link placeholders with plain text of links
4156 * (not HTML-formatted).
4157 * @param string $text
4160 function replaceLinkHoldersText( $text ) {
4161 $fname = 'Parser::replaceLinkHoldersText';
4162 wfProfileIn( $fname );
4164 $text = preg_replace_callback(
4165 '/<!--(LINK|IWLINK) (.*?)-->/',
4166 array( &$this, 'replaceLinkHoldersTextCallback' ),
4169 wfProfileOut( $fname );
4174 * @param array $matches
4178 function replaceLinkHoldersTextCallback( $matches ) {
4179 $type = $matches[1];
4181 if( $type == 'LINK' ) {
4182 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4183 return $this->mLinkHolders
['texts'][$key];
4185 } elseif( $type == 'IWLINK' ) {
4186 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4187 return $this->mInterwikiLinkHolders
['texts'][$key];
4194 * Tag hook handler for 'pre'.
4196 function renderPreTag( $text, $attribs ) {
4197 // Backwards-compatibility hack
4198 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4200 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4201 return wfOpenElement( 'pre', $attribs ) .
4202 wfEscapeHTMLTagsOnly( $content ) .
4207 * Renders an image gallery from a text with one line per image.
4208 * text labels may be given by using |-style alternative text. E.g.
4209 * Image:one.jpg|The number "1"
4210 * Image:tree.jpg|A tree
4211 * given as text will return the HTML of a gallery with two images,
4212 * labeled 'The number "1"' and
4215 function renderImageGallery( $text, $params ) {
4216 $ig = new ImageGallery();
4217 $ig->setShowBytes( false );
4218 $ig->setShowFilename( false );
4220 $ig->useSkin( $this->mOptions
->getSkin() );
4222 if( isset( $params['caption'] ) )
4223 $ig->setCaption( $params['caption'] );
4225 $lines = explode( "\n", $text );
4226 foreach ( $lines as $line ) {
4227 # match lines like these:
4228 # Image:someimage.jpg|This is some image
4230 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4232 if ( count( $matches ) == 0 ) {
4235 $tp = Title
::newFromText( $matches[1] );
4237 if( is_null( $nt ) ) {
4238 # Bogus title. Ignore these so we don't bomb out later.
4241 if ( isset( $matches[3] ) ) {
4242 $label = $matches[3];
4247 $pout = $this->parse( $label,
4250 false, // Strip whitespace...?
4251 false // Don't clear state!
4253 $html = $pout->getText();
4255 $ig->add( new Image( $nt ), $html );
4257 # Only add real images (bug #5586)
4258 if ( $nt->getNamespace() == NS_IMAGE
) {
4259 $this->mOutput
->addImage( $nt->getDBkey() );
4262 return $ig->toHTML();
4266 * Parse image options text and use it to make an image
4268 function makeImage( $nt, $options ) {
4269 global $wgUseImageResize, $wgDjvuRenderer;
4273 # Check if the options text is of the form "options|alt text"
4275 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4276 # * left no resizing, just left align. label is used for alt= only
4277 # * right same, but right aligned
4278 # * none same, but not aligned
4279 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4280 # * center center the image
4281 # * framed Keep original image size, no magnify-button.
4283 $part = explode( '|', $options);
4285 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4286 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4287 $mwLeft =& MagicWord
::get( 'img_left' );
4288 $mwRight =& MagicWord
::get( 'img_right' );
4289 $mwNone =& MagicWord
::get( 'img_none' );
4290 $mwWidth =& MagicWord
::get( 'img_width' );
4291 $mwCenter =& MagicWord
::get( 'img_center' );
4292 $mwFramed =& MagicWord
::get( 'img_framed' );
4293 $mwPage =& MagicWord
::get( 'img_page' );
4296 $width = $height = $framed = $thumb = false;
4298 $manual_thumb = '' ;
4300 foreach( $part as $val ) {
4301 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4303 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4304 # use manually specified thumbnail
4306 $manual_thumb = $match;
4307 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4308 # remember to set an alignment, don't render immediately
4310 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4311 # remember to set an alignment, don't render immediately
4313 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4314 # remember to set an alignment, don't render immediately
4316 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4317 # remember to set an alignment, don't render immediately
4319 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4320 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4321 # Select a page in a multipage document
4323 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4324 wfDebug( "img_width match: $match\n" );
4325 # $match is the image width in pixels
4327 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4328 $width = intval( $m[1] );
4329 $height = intval( $m[2] );
4331 $width = intval($match);
4333 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4339 # Strip bad stuff out of the alt text
4340 $alt = $this->replaceLinkHoldersText( $caption );
4342 # make sure there are no placeholders in thumbnail attributes
4343 # that are later expanded to html- so expand them now and
4345 $alt = $this->unstrip($alt, $this->mStripState
);
4346 $alt = Sanitizer
::stripAllTags( $alt );
4348 # Linker does the rest
4349 $sk =& $this->mOptions
->getSkin();
4350 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4354 * Set a flag in the output object indicating that the content is dynamic and
4355 * shouldn't be cached.
4357 function disableCache() {
4358 wfDebug( "Parser output marked as uncacheable.\n" );
4359 $this->mOutput
->mCacheTime
= -1;
4363 * Callback from the Sanitizer for expanding items found in HTML attribute
4364 * values, so they can be safely tested and escaped.
4365 * @param string $text
4366 * @param array $args
4370 function attributeStripCallback( &$text, $args ) {
4371 $text = $this->replaceVariables( $text, $args );
4372 $text = $this->unstripForHTML( $text );
4376 function unstripForHTML( $text ) {
4377 $text = $this->unstrip( $text, $this->mStripState
);
4378 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4386 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4387 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4388 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4394 function getTags() { return array_keys( $this->mTagHooks
); }
4399 * Break wikitext input into sections, and either pull or replace
4400 * some particular section's text.
4402 * External callers should use the getSection and replaceSection methods.
4404 * @param $text Page wikitext
4405 * @param $section Numbered section. 0 pulls the text before the first
4406 * heading; other numbers will pull the given section
4407 * along with its lower-level subsections.
4408 * @param $mode One of "get" or "replace"
4409 * @param $newtext Replacement text for section data.
4410 * @return string for "get", the extracted section text.
4411 * for "replace", the whole page with the section replaced.
4413 private function extractSections( $text, $section, $mode, $newtext='' ) {
4414 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4415 # comments to be stripped as well)
4416 $striparray = array();
4418 $oldOutputType = $this->mOutputType
;
4419 $oldOptions = $this->mOptions
;
4420 $this->mOptions
= new ParserOptions();
4421 $this->setOutputType( OT_WIKI
);
4423 $striptext = $this->strip( $text, $striparray, true );
4425 $this->setOutputType( $oldOutputType );
4426 $this->mOptions
= $oldOptions;
4428 # now that we can be sure that no pseudo-sections are in the source,
4429 # split it up by section
4430 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4431 $comment = "(?:$uniq-!--.*?QINU)";
4436 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4438 (=+) # Should this be limited to 6?
4439 .+? # Section title...
4440 \\2 # Ending = count must match start
4447 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4454 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4455 (=+) # Should this be limited to 6?
4456 .+? # Section title...
4457 \\2 # Ending = count must match start
4458 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4467 PREG_SPLIT_DELIM_CAPTURE
);
4469 if( $mode == "get" ) {
4470 if( $section == 0 ) {
4471 // "Section 0" returns the content before any other section.
4476 } elseif( $mode == "replace" ) {
4477 if( $section == 0 ) {
4478 $rv = $newtext . "\n\n";
4487 for( $index = 1; $index < count( $secs ); ) {
4488 $headerLine = $secs[$index++
];
4489 if( $secs[$index] ) {
4491 $headerLevel = strlen( $secs[$index++
] );
4495 $headerLevel = intval( $secs[$index++
] );
4497 $content = $secs[$index++
];
4500 if( $mode == "get" ) {
4501 if( $count == $section ) {
4502 $rv = $headerLine . $content;
4503 $sectionLevel = $headerLevel;
4504 } elseif( $count > $section ) {
4505 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4506 $rv .= $headerLine . $content;
4508 // Broke out to a higher-level section
4512 } elseif( $mode == "replace" ) {
4513 if( $count < $section ) {
4514 $rv .= $headerLine . $content;
4515 } elseif( $count == $section ) {
4516 $rv .= $newtext . "\n\n";
4517 $sectionLevel = $headerLevel;
4518 } elseif( $count > $section ) {
4519 if( $headerLevel <= $sectionLevel ) {
4520 // Passed the section's sub-parts.
4524 $rv .= $headerLine . $content;
4529 # reinsert stripped tags
4530 $rv = $this->unstrip( $rv, $striparray );
4531 $rv = $this->unstripNoWiki( $rv, $striparray );
4537 * This function returns the text of a section, specified by a number ($section).
4538 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4539 * the first section before any such heading (section 0).
4541 * If a section contains subsections, these are also returned.
4543 * @param $text String: text to look in
4544 * @param $section Integer: section number
4545 * @return string text of the requested section
4547 function getSection( $text, $section ) {
4548 return $this->extractSections( $text, $section, "get" );
4551 function replaceSection( $oldtext, $section, $text ) {
4552 return $this->extractSections( $oldtext, $section, "replace", $text );
4559 * @package MediaWiki
4563 var $mText, # The output text
4564 $mLanguageLinks, # List of the full text of language links, in the order they appear
4565 $mCategories, # Map of category names to sort keys
4566 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4567 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4568 $mVersion, # Compatibility check
4569 $mTitleText, # title text of the chosen language variant
4570 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4571 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4572 $mImages, # DB keys of the images used, in the array key only
4573 $mExternalLinks, # External link URLs, in the key only
4574 $mHTMLtitle, # Display HTML title
4575 $mSubtitle, # Additional subtitle
4576 $mNewSection, # Show a new section link?
4577 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4579 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4580 $containsOldMagic = false, $titletext = '' )
4582 $this->mText
= $text;
4583 $this->mLanguageLinks
= $languageLinks;
4584 $this->mCategories
= $categoryLinks;
4585 $this->mContainsOldMagic
= $containsOldMagic;
4586 $this->mCacheTime
= '';
4587 $this->mVersion
= MW_PARSER_VERSION
;
4588 $this->mTitleText
= $titletext;
4589 $this->mLinks
= array();
4590 $this->mTemplates
= array();
4591 $this->mImages
= array();
4592 $this->mExternalLinks
= array();
4593 $this->mHTMLtitle
= "" ;
4594 $this->mSubtitle
= "" ;
4595 $this->mNewSection
= false;
4596 $this->mNoGallery
= false;
4599 function getText() { return $this->mText
; }
4600 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4601 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4602 function &getCategories() { return $this->mCategories
; }
4603 function getCacheTime() { return $this->mCacheTime
; }
4604 function getTitleText() { return $this->mTitleText
; }
4605 function &getLinks() { return $this->mLinks
; }
4606 function &getTemplates() { return $this->mTemplates
; }
4607 function &getImages() { return $this->mImages
; }
4608 function &getExternalLinks() { return $this->mExternalLinks
; }
4609 function getNoGallery() { return $this->mNoGallery
; }
4610 function getSubtitle() { return $this->mSubtitle
; }
4612 function containsOldMagic() { return $this->mContainsOldMagic
; }
4613 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4614 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4615 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4616 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4617 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4618 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4619 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4621 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4622 function addImage( $name ) { $this->mImages
[$name] = 1; }
4623 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4624 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4626 function setNewSection( $value ) {
4627 $this->mNewSection
= (bool)$value;
4629 function getNewSection() {
4630 return (bool)$this->mNewSection
;
4633 function addLink( $title, $id = null ) {
4634 $ns = $title->getNamespace();
4635 $dbk = $title->getDBkey();
4636 if ( !isset( $this->mLinks
[$ns] ) ) {
4637 $this->mLinks
[$ns] = array();
4639 if ( is_null( $id ) ) {
4640 $id = $title->getArticleID();
4642 $this->mLinks
[$ns][$dbk] = $id;
4645 function addTemplate( $title, $id ) {
4646 $ns = $title->getNamespace();
4647 $dbk = $title->getDBkey();
4648 if ( !isset( $this->mTemplates
[$ns] ) ) {
4649 $this->mTemplates
[$ns] = array();
4651 $this->mTemplates
[$ns][$dbk] = $id;
4655 * Return true if this cached output object predates the global or
4656 * per-article cache invalidation timestamps, or if it comes from
4657 * an incompatible older version.
4659 * @param string $touched the affected article's last touched timestamp
4663 function expired( $touched ) {
4664 global $wgCacheEpoch;
4665 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4666 $this->getCacheTime() < $touched ||
4667 $this->getCacheTime() <= $wgCacheEpoch ||
4668 !isset( $this->mVersion
) ||
4669 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4674 * Set options of the Parser
4676 * @package MediaWiki
4680 # All variables are supposed to be private in theory, although in practise this is not the case.
4681 var $mUseTeX; # Use texvc to expand <math> tags
4682 var $mUseDynamicDates; # Use DateFormatter to format dates
4683 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4684 var $mAllowExternalImages; # Allow external images inline
4685 var $mAllowExternalImagesFrom; # If not, any exception?
4686 var $mSkin; # Reference to the preferred skin
4687 var $mDateFormat; # Date format index
4688 var $mEditSection; # Create "edit section" links
4689 var $mNumberHeadings; # Automatically number headings
4690 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4691 var $mTidy; # Ask for tidy cleanup
4692 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4693 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4694 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4696 var $mUser; # Stored user object, just used to initialise the skin
4698 function getUseTeX() { return $this->mUseTeX
; }
4699 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4700 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4701 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4702 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4703 function getEditSection() { return $this->mEditSection
; }
4704 function getNumberHeadings() { return $this->mNumberHeadings
; }
4705 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4706 function getTidy() { return $this->mTidy
; }
4707 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4708 function getMaxIncludeSize() { return $this->mMaxIncludeSize
; }
4709 function getRemoveComments() { return $this->mRemoveComments
; }
4711 function &getSkin() {
4712 if ( !isset( $this->mSkin
) ) {
4713 $this->mSkin
= $this->mUser
->getSkin();
4715 return $this->mSkin
;
4718 function getDateFormat() {
4719 if ( !isset( $this->mDateFormat
) ) {
4720 $this->mDateFormat
= $this->mUser
->getDatePreference();
4722 return $this->mDateFormat
;
4725 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4726 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4727 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4728 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4729 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4730 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4731 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4732 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4733 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4734 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4735 function setSkin( $x ) { $this->mSkin
= $x; }
4736 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4737 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize
, $x ); }
4738 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments
, $x ); }
4740 function ParserOptions( $user = null ) {
4741 $this->initialiseFromUser( $user );
4745 * Get parser options
4748 static function newFromUser( $user ) {
4749 return new ParserOptions( $user );
4752 /** Get user options */
4753 function initialiseFromUser( $userInput ) {
4754 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4755 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4756 $fname = 'ParserOptions::initialiseFromUser';
4757 wfProfileIn( $fname );
4758 if ( !$userInput ) {
4760 if ( isset( $wgUser ) ) {
4766 $user =& $userInput;
4769 $this->mUser
= $user;
4771 $this->mUseTeX
= $wgUseTeX;
4772 $this->mUseDynamicDates
= $wgUseDynamicDates;
4773 $this->mInterwikiMagic
= $wgInterwikiMagic;
4774 $this->mAllowExternalImages
= $wgAllowExternalImages;
4775 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4776 $this->mSkin
= null; # Deferred
4777 $this->mDateFormat
= null; # Deferred
4778 $this->mEditSection
= true;
4779 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4780 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4781 $this->mTidy
= false;
4782 $this->mInterfaceMessage
= false;
4783 $this->mMaxIncludeSize
= $wgMaxArticleSize * 1024;
4784 $this->mRemoveComments
= true;
4785 wfProfileOut( $fname );
4790 * Callback function used by Parser::replaceLinkHolders()
4791 * to substitute link placeholders.
4793 function &wfOutputReplaceMatches( $matches ) {
4794 global $wgOutputReplace;
4795 return $wgOutputReplace[$matches[1]];
4799 * Return the total number of articles
4801 function wfNumberOfArticles() {
4802 global $wgNumberOfArticles;
4805 return $wgNumberOfArticles;
4809 * Return the number of files
4811 function wfNumberOfFiles() {
4812 $fname = 'wfNumberOfFiles';
4814 wfProfileIn( $fname );
4815 $dbr =& wfGetDB( DB_SLAVE
);
4816 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4817 wfProfileOut( $fname );
4823 * Return the number of user accounts
4826 function wfNumberOfUsers() {
4827 wfProfileIn( 'wfNumberOfUsers' );
4828 $dbr =& wfGetDB( DB_SLAVE
);
4829 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4830 wfProfileOut( 'wfNumberOfUsers' );
4835 * Return the total number of pages
4838 function wfNumberOfPages() {
4839 wfProfileIn( 'wfNumberOfPages' );
4840 $dbr =& wfGetDB( DB_SLAVE
);
4841 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4842 wfProfileOut( 'wfNumberOfPages' );
4847 * Return the total number of admins
4851 function wfNumberOfAdmins() {
4852 static $admins = -1;
4853 wfProfileIn( 'wfNumberOfAdmins' );
4854 if( $admins == -1 ) {
4855 $dbr =& wfGetDB( DB_SLAVE
);
4856 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4858 wfProfileOut( 'wfNumberOfAdmins' );
4859 return (int)$admins;
4863 * Count the number of pages in a particular namespace
4865 * @param $ns Namespace
4868 function wfPagesInNs( $ns ) {
4869 static $pageCount = array();
4870 wfProfileIn( 'wfPagesInNs' );
4871 if( !isset( $pageCount[$ns] ) ) {
4872 $dbr =& wfGetDB( DB_SLAVE
);
4873 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4875 wfProfileOut( 'wfPagesInNs' );
4876 return (int)$pageCount[$ns];
4880 * Get various statistics from the database
4883 function wfLoadSiteStats() {
4884 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4885 $fname = 'wfLoadSiteStats';
4887 if ( -1 != $wgNumberOfArticles ) return;
4888 $dbr =& wfGetDB( DB_SLAVE
);
4889 $s = $dbr->selectRow( 'site_stats',
4890 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4891 array( 'ss_row_id' => 1 ), $fname
4894 if ( $s === false ) {
4897 $wgTotalViews = $s->ss_total_views
;
4898 $wgTotalEdits = $s->ss_total_edits
;
4899 $wgNumberOfArticles = $s->ss_good_articles
;
4904 * Get revision timestamp from the database considering timecorrection
4906 * @param $id Int: page revision id
4909 function wfRevisionTimestamp( $id ) {
4911 $fname = 'wfRevisionTimestamp';
4913 wfProfileIn( $fname );
4914 $dbr =& wfGetDB( DB_SLAVE
);
4915 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4916 array( 'rev_id' => $id ), __METHOD__
);
4917 $timestamp = $wgContLang->userAdjust( $timestamp );
4918 wfProfileOut( $fname );
4925 * Basically replacing " > and < with HTML entities ( ", >, <)
4927 * @param $in String: text that might contain HTML tags.
4928 * @return string Escaped string
4930 function wfEscapeHTMLTagsOnly( $in ) {
4932 array( '"', '>', '<' ),
4933 array( '"', '>', '<' ),