5 * File for Parser and related classes
11 * Update this version number when the ParserOutput format
12 * changes in an incompatible way, so the parser cache
13 * can automatically discard old data.
15 define( 'MW_PARSER_VERSION', '1.6.2' );
17 define( 'RLH_FOR_UPDATE', 1 );
19 # Allowed values for $mOutputType
20 define( 'OT_HTML', 1 );
21 define( 'OT_WIKI', 2 );
22 define( 'OT_MSG' , 3 );
23 define( 'OT_PREPROCESS', 4 );
25 # Flags for setFunctionHook
26 define( 'SFH_NO_HASH', 1 );
28 # string parameter for extractTags which will cause it
29 # to strip HTML comments in addition to regular
30 # <XML>-style tags. This should not be anything we
31 # may want to use in wikisyntax
32 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
34 # Constants needed for external link processing
35 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
36 # Everything except bracket, space, or control characters
37 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
38 # Including space, but excluding newlines
39 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
40 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
41 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
42 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
43 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
44 define( 'EXT_IMAGE_REGEX',
45 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
46 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
47 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
50 // State constants for the definition list colon extraction
51 define( 'MW_COLON_STATE_TEXT', 0 );
52 define( 'MW_COLON_STATE_TAG', 1 );
53 define( 'MW_COLON_STATE_TAGSTART', 2 );
54 define( 'MW_COLON_STATE_CLOSETAG', 3 );
55 define( 'MW_COLON_STATE_TAGSLASH', 4 );
56 define( 'MW_COLON_STATE_COMMENT', 5 );
57 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
58 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
61 * PHP Parser - Processes wiki markup (which uses a more user-friendly
62 * syntax, such as "[[link]]" for making links), and provides a one-way
63 * transformation of that wiki markup it into XHTML output / markup
64 * (which in turn the browser understands, and can display).
67 * There are four main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
75 * removes HTML comments and expands templates
78 * objects: $wgLang, $wgContLang
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
85 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
88 * * only within ParserOptions
95 const VERSION
= MW_PARSER_VERSION
;
100 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
101 $mImageParams, $mImageParamsMagicArray;
103 # Cleared with clearState():
104 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
105 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
106 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
107 var $mIncludeSizes, $mDefaultSort;
108 var $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
114 # These are variables reset at least once per parse regardless of $clearState
115 var $mOptions, // ParserOptions object
116 $mTitle, // Title context, used for self-link rendering and similar things
117 $mOutputType, // Output type, one of the OT_xxx constants
118 $ot, // Shortcut alias, see setOutputType()
119 $mRevisionId, // ID to display in {{REVISIONID}} tags
120 $mRevisionTimestamp, // The timestamp of the specified revision ID
121 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
131 $this->mTagHooks
= array();
132 $this->mTransparentTagHooks
= array();
133 $this->mFunctionHooks
= array();
134 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
135 $this->mFirstCall
= true;
139 * Do various kinds of initialisation on the first call of the parser
141 function firstCallInit() {
142 if ( !$this->mFirstCall
) {
146 wfProfileIn( __METHOD__
);
147 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
149 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
151 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
174 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
175 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
176 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
177 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
179 if ( $wgAllowDisplayTitle ) {
180 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
182 if ( $wgAllowSlowParserFunctions ) {
183 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
186 $this->initialiseVariables();
187 $this->mFirstCall
= false;
188 wfProfileOut( __METHOD__
);
196 function clearState() {
197 wfProfileIn( __METHOD__
);
198 if ( $this->mFirstCall
) {
199 $this->firstCallInit();
201 $this->mOutput
= new ParserOutput
;
202 $this->mAutonumber
= 0;
203 $this->mLastSection
= '';
204 $this->mDTopen
= false;
205 $this->mIncludeCount
= array();
206 $this->mStripState
= new StripState
;
207 $this->mArgStack
= array();
208 $this->mInPre
= false;
209 $this->mInterwikiLinkHolders
= array(
213 $this->mLinkHolders
= array(
214 'namespaces' => array(),
216 'queries' => array(),
220 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
223 * Prefix for temporary replacement strings for the multipass parser.
224 * \x07 should never appear in input as it's disallowed in XML.
225 * Using it at the front also gives us a little extra robustness
226 * since it shouldn't match when butted up against identifier-like
229 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
231 # Clear these on every parse, bug 4549
232 $this->mTemplates
= array();
233 $this->mTemplatePath
= array();
235 $this->mShowToc
= true;
236 $this->mForceTocPosition
= false;
237 $this->mIncludeSizes
= array(
242 $this->mDefaultSort
= false;
244 wfRunHooks( 'ParserClearState', array( &$this ) );
245 wfProfileOut( __METHOD__
);
248 function setOutputType( $ot ) {
249 $this->mOutputType
= $ot;
252 'html' => $ot == OT_HTML
,
253 'wiki' => $ot == OT_WIKI
,
254 'msg' => $ot == OT_MSG
,
255 'pre' => $ot == OT_PREPROCESS
,
260 * Accessor for mUniqPrefix.
264 function uniqPrefix() {
265 return $this->mUniqPrefix
;
269 * Convert wikitext to HTML
270 * Do not call this function recursively.
272 * @param string $text Text we want to parse
273 * @param Title &$title A title object
274 * @param array $options
275 * @param boolean $linestart
276 * @param boolean $clearState
277 * @param int $revid number to pass in {{REVISIONID}}
278 * @return ParserOutput a ParserOutput
280 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
282 * First pass--just handle <nowiki> sections, pass the rest off
283 * to internalParse() which does all the real work.
286 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
287 $fname = 'Parser::parse-' . wfGetCaller();
288 wfProfileIn( __METHOD__
);
289 wfProfileIn( $fname );
295 $this->mOptions
= $options;
296 $this->mTitle
=& $title;
297 $oldRevisionId = $this->mRevisionId
;
298 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
299 if( $revid !== null ) {
300 $this->mRevisionId
= $revid;
301 $this->mRevisionTimestamp
= null;
303 $this->setOutputType( OT_HTML
);
304 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
305 $text = $this->strip( $text, $this->mStripState
);
306 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
307 $text = $this->internalParse( $text );
308 $text = $this->mStripState
->unstripGeneral( $text );
310 # Clean up special characters, only run once, next-to-last before doBlockLevels
312 # french spaces, last one Guillemet-left
313 # only if there is something before the space
314 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
315 # french spaces, Guillemet-right
316 '/(\\302\\253) /' => '\\1 ',
318 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
321 $text = $this->doBlockLevels( $text, $linestart );
323 $this->replaceLinkHolders( $text );
325 # the position of the parserConvert() call should not be changed. it
326 # assumes that the links are all replaced and the only thing left
327 # is the <nowiki> mark.
328 # Side-effects: this calls $this->mOutput->setTitleText()
329 $text = $wgContLang->parserConvert( $text, $this );
331 $text = $this->mStripState
->unstripNoWiki( $text );
333 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
335 //!JF Move to its own function
337 $uniq_prefix = $this->mUniqPrefix
;
339 $elements = array_keys( $this->mTransparentTagHooks
);
340 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
342 foreach( $matches as $marker => $data ) {
343 list( $element, $content, $params, $tag ) = $data;
344 $tagName = strtolower( $element );
345 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
346 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
347 array( $content, $params, $this ) );
351 $this->mStripState
->general
->setPair( $marker, $output );
353 $text = $this->mStripState
->unstripGeneral( $text );
355 $text = Sanitizer
::normalizeCharReferences( $text );
357 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
358 $text = Parser
::tidy($text);
360 # attempt to sanitize at least some nesting problems
361 # (bug #2702 and quite a few others)
363 # ''Something [http://www.cool.com cool''] -->
364 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
365 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
366 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
367 # fix up an anchor inside another anchor, only
368 # at least for a single single nested link (bug 3695)
369 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
370 '\\1\\2</a>\\3</a>\\1\\4</a>',
371 # fix div inside inline elements- doBlockLevels won't wrap a line which
372 # contains a div, so fix it up here; replace
373 # div with escaped text
374 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
375 '\\1\\3<div\\5>\\6</div>\\8\\9',
376 # remove empty italic or bold tag pairs, some
377 # introduced by rules above
378 '/<([bi])><\/\\1>/' => '',
381 $text = preg_replace(
382 array_keys( $tidyregs ),
383 array_values( $tidyregs ),
387 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
389 # Information on include size limits, for the benefit of users who try to skirt them
390 if ( max( $this->mIncludeSizes
) > 1000 ) {
391 $max = $this->mOptions
->getMaxIncludeSize();
393 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
394 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
395 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
396 "Maximum: $max bytes\n" .
399 $this->mOutput
->setText( $text );
400 $this->mRevisionId
= $oldRevisionId;
401 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
402 wfProfileOut( $fname );
403 wfProfileOut( __METHOD__
);
405 return $this->mOutput
;
409 * Recursive parser entry point that can be called from an extension tag
412 function recursiveTagParse( $text ) {
413 wfProfileIn( __METHOD__
);
414 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
415 $text = $this->strip( $text, $this->mStripState
);
416 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
417 $text = $this->internalParse( $text );
418 wfProfileOut( __METHOD__
);
423 * Expand templates and variables in the text, producing valid, static wikitext.
424 * Also removes comments.
426 function preprocess( $text, $title, $options, $revid = null ) {
427 wfProfileIn( __METHOD__
);
429 $this->setOutputType( OT_PREPROCESS
);
430 $this->mOptions
= $options;
431 $this->mTitle
= $title;
432 if( $revid !== null ) {
433 $this->mRevisionId
= $revid;
435 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
436 $text = $this->strip( $text, $this->mStripState
);
437 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
438 if ( $this->mOptions
->getRemoveComments() ) {
439 $text = Sanitizer
::removeHTMLcomments( $text );
441 $text = $this->replaceVariables( $text );
442 $text = $this->mStripState
->unstripBoth( $text );
443 wfProfileOut( __METHOD__
);
448 * Get a random string
453 function getRandomString() {
454 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
457 function &getTitle() { return $this->mTitle
; }
458 function getOptions() { return $this->mOptions
; }
460 function getFunctionLang() {
461 global $wgLang, $wgContLang;
462 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
466 * Replaces all occurrences of HTML-style comments and the given tags
467 * in the text with a random marker and returns teh next text. The output
468 * parameter $matches will be an associative array filled with data in
470 * 'UNIQ-xxxxx' => array(
473 * array( 'param' => 'x' ),
474 * '<element param="x">tag content</element>' ) )
476 * @param $elements list of element names. Comments are always extracted.
477 * @param $text Source text string.
478 * @param $uniq_prefix
483 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
488 $taglist = implode( '|', $elements );
489 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
491 while ( '' != $text ) {
492 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
494 if( count( $p ) < 5 ) {
497 if( count( $p ) > 5 ) {
511 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
512 $stripped .= $marker;
514 if ( $close === '/>' ) {
515 // Empty element tag, <tag />
520 if( $element == '!--' ) {
523 $end = "/(<\\/$element\\s*>)/i";
525 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
527 if( count( $q ) < 3 ) {
528 # No end tag -- let it run out to the end of the text.
537 $matches[$marker] = array( $element,
539 Sanitizer
::decodeTagAttributes( $attributes ),
540 "<$element$attributes$close$content$tail" );
546 * Strips and renders nowiki, pre, math, hiero
547 * If $render is set, performs necessary rendering operations on plugins
548 * Returns the text, and fills an array with data needed in unstrip()
550 * @param StripState $state
552 * @param bool $stripcomments when set, HTML comments <!-- like this -->
553 * will be stripped in addition to other tags. This is important
554 * for section editing, where these comments cause confusion when
555 * counting the sections in the wikisource
557 * @param array dontstrip contains tags which should not be stripped;
558 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
562 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
564 wfProfileIn( __METHOD__
);
565 $render = ($this->mOutputType
== OT_HTML
);
567 $uniq_prefix = $this->mUniqPrefix
;
568 $commentState = new ReplacementArray
;
569 $nowikiItems = array();
570 $generalItems = array();
572 $elements = array_merge(
573 array( 'nowiki', 'gallery' ),
574 array_keys( $this->mTagHooks
) );
577 $elements[] = 'html';
579 if( $this->mOptions
->getUseTeX() ) {
580 $elements[] = 'math';
583 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
584 foreach ( $elements AS $k => $v ) {
585 if ( !in_array ( $v , $dontstrip ) ) continue;
586 unset ( $elements[$k] );
590 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
592 foreach( $matches as $marker => $data ) {
593 list( $element, $content, $params, $tag ) = $data;
595 $tagName = strtolower( $element );
596 wfProfileIn( __METHOD__
."-render-$tagName" );
600 if( substr( $tag, -3 ) == '-->' ) {
603 // Unclosed comment in input.
604 // Close it so later stripping can remove it
613 // Shouldn't happen otherwise. :)
615 $output = Xml
::escapeTagsOnly( $content );
618 $output = $wgContLang->armourMath(
619 MathRenderer
::renderMath( $content, $params ) );
622 $output = $this->renderImageGallery( $content, $params );
625 if( isset( $this->mTagHooks
[$tagName] ) ) {
626 $output = call_user_func_array( $this->mTagHooks
[$tagName],
627 array( $content, $params, $this ) );
629 throw new MWException( "Invalid call hook $element" );
632 wfProfileOut( __METHOD__
."-render-$tagName" );
634 // Just stripping tags; keep the source
638 // Unstrip the output, to support recursive strip() calls
639 $output = $state->unstripBoth( $output );
641 if( !$stripcomments && $element == '!--' ) {
642 $commentState->setPair( $marker, $output );
643 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
644 $nowikiItems[$marker] = $output;
646 $generalItems[$marker] = $output;
649 # Add the new items to the state
650 # We do this after the loop instead of during it to avoid slowing
651 # down the recursive unstrip
652 $state->nowiki
->mergeArray( $nowikiItems );
653 $state->general
->mergeArray( $generalItems );
655 # Unstrip comments unless explicitly told otherwise.
656 # (The comments are always stripped prior to this point, so as to
657 # not invoke any extension tags / parser hooks contained within
659 if ( !$stripcomments ) {
660 // Put them all back and forget them
661 $text = $commentState->replace( $text );
664 wfProfileOut( __METHOD__
);
669 * Restores pre, math, and other extensions removed by strip()
671 * always call unstripNoWiki() after this one
673 * @deprecated use $this->mStripState->unstrip()
675 function unstrip( $text, $state ) {
676 return $state->unstripGeneral( $text );
680 * Always call this after unstrip() to preserve the order
683 * @deprecated use $this->mStripState->unstrip()
685 function unstripNoWiki( $text, $state ) {
686 return $state->unstripNoWiki( $text );
690 * @deprecated use $this->mStripState->unstripBoth()
692 function unstripForHTML( $text ) {
693 return $this->mStripState
->unstripBoth( $text );
697 * Add an item to the strip state
698 * Returns the unique tag which must be inserted into the stripped text
699 * The tag will be replaced with the original text in unstrip()
703 function insertStripItem( $text, &$state ) {
704 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
705 $state->general
->setPair( $rnd, $text );
710 * Interface with html tidy, used if $wgUseTidy = true.
711 * If tidy isn't able to correct the markup, the original will be
712 * returned in all its glory with a warning comment appended.
714 * Either the external tidy program or the in-process tidy extension
715 * will be used depending on availability. Override the default
716 * $wgTidyInternal setting to disable the internal if it's not working.
718 * @param string $text Hideous HTML input
719 * @return string Corrected HTML output
723 function tidy( $text ) {
724 global $wgTidyInternal;
725 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
726 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
727 '<head><title>test</title></head><body>'.$text.'</body></html>';
728 if( $wgTidyInternal ) {
729 $correctedtext = Parser
::internalTidy( $wrappedtext );
731 $correctedtext = Parser
::externalTidy( $wrappedtext );
733 if( is_null( $correctedtext ) ) {
734 wfDebug( "Tidy error detected!\n" );
735 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
737 return $correctedtext;
741 * Spawn an external HTML tidy process and get corrected markup back from it.
746 function externalTidy( $text ) {
747 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
748 $fname = 'Parser::externalTidy';
749 wfProfileIn( $fname );
754 $descriptorspec = array(
755 0 => array('pipe', 'r'),
756 1 => array('pipe', 'w'),
757 2 => array('file', wfGetNull(), 'a')
760 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
761 if (is_resource($process)) {
762 // Theoretically, this style of communication could cause a deadlock
763 // here. If the stdout buffer fills up, then writes to stdin could
764 // block. This doesn't appear to happen with tidy, because tidy only
765 // writes to stdout after it's finished reading from stdin. Search
766 // for tidyParseStdin and tidySaveStdout in console/tidy.c
767 fwrite($pipes[0], $text);
769 while (!feof($pipes[1])) {
770 $cleansource .= fgets($pipes[1], 1024);
773 proc_close($process);
776 wfProfileOut( $fname );
778 if( $cleansource == '' && $text != '') {
779 // Some kind of error happened, so we couldn't get the corrected text.
780 // Just give up; we'll use the source text and append a warning.
788 * Use the HTML tidy PECL extension to use the tidy library in-process,
789 * saving the overhead of spawning a new process. Currently written to
790 * the PHP 4.3.x version of the extension, may not work on PHP 5.
792 * 'pear install tidy' should be able to compile the extension module.
797 function internalTidy( $text ) {
799 $fname = 'Parser::internalTidy';
800 wfProfileIn( $fname );
802 tidy_load_config( $wgTidyConf );
803 tidy_set_encoding( 'utf8' );
804 tidy_parse_string( $text );
806 if( tidy_get_status() == 2 ) {
807 // 2 is magic number for fatal error
808 // http://www.php.net/manual/en/function.tidy-get-status.php
811 $cleansource = tidy_get_output();
813 wfProfileOut( $fname );
818 * parse the wiki syntax used to render tables
822 function doTableStuff ( $text ) {
823 $fname = 'Parser::doTableStuff';
824 wfProfileIn( $fname );
826 $lines = explode ( "\n" , $text );
827 $td_history = array (); // Is currently a td tag open?
828 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
829 $tr_history = array (); // Is currently a tr tag open?
830 $tr_attributes = array (); // history of tr attributes
831 $has_opened_tr = array(); // Did this table open a <tr> element?
832 $indent_level = 0; // indent level of the table
833 foreach ( $lines as $key => $line )
835 $line = trim ( $line );
837 if( $line == '' ) { // empty line, go to next line
840 $first_character = $line{0};
843 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
844 // First check if we are starting a new table
845 $indent_level = strlen( $matches[1] );
847 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
848 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
850 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
851 array_push ( $td_history , false );
852 array_push ( $last_tag_history , '' );
853 array_push ( $tr_history , false );
854 array_push ( $tr_attributes , '' );
855 array_push ( $has_opened_tr , false );
856 } else if ( count ( $td_history ) == 0 ) {
857 // Don't do any of the following
859 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
860 // We are ending a table
861 $line = '</table>' . substr ( $line , 2 );
862 $last_tag = array_pop ( $last_tag_history );
864 if ( !array_pop ( $has_opened_tr ) ) {
865 $line = "<tr><td></td></tr>{$line}";
868 if ( array_pop ( $tr_history ) ) {
869 $line = "</tr>{$line}";
872 if ( array_pop ( $td_history ) ) {
873 $line = "</{$last_tag}>{$line}";
875 array_pop ( $tr_attributes );
876 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
877 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
878 // Now we have a table row
879 $line = preg_replace( '#^\|-+#', '', $line );
881 // Whats after the tag is now only attributes
882 $attributes = $this->mStripState
->unstripBoth( $line );
883 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
884 array_pop ( $tr_attributes );
885 array_push ( $tr_attributes , $attributes );
888 $last_tag = array_pop ( $last_tag_history );
889 array_pop ( $has_opened_tr );
890 array_push ( $has_opened_tr , true );
892 if ( array_pop ( $tr_history ) ) {
896 if ( array_pop ( $td_history ) ) {
897 $line = "</{$last_tag}>{$line}";
900 $lines[$key] = $line;
901 array_push ( $tr_history , false );
902 array_push ( $td_history , false );
903 array_push ( $last_tag_history , '' );
905 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
906 // This might be cell elements, td, th or captions
907 if ( substr ( $line , 0 , 2 ) == '|+' ) {
908 $first_character = '+';
909 $line = substr ( $line , 1 );
912 $line = substr ( $line , 1 );
914 if ( $first_character == '!' ) {
915 $line = str_replace ( '!!' , '||' , $line );
918 // Split up multiple cells on the same line.
919 // FIXME : This can result in improper nesting of tags processed
920 // by earlier parser steps, but should avoid splitting up eg
921 // attribute values containing literal "||".
922 $cells = StringUtils
::explodeMarkup( '||' , $line );
926 // Loop through each table cell
927 foreach ( $cells as $cell )
930 if ( $first_character != '+' )
932 $tr_after = array_pop ( $tr_attributes );
933 if ( !array_pop ( $tr_history ) ) {
934 $previous = "<tr{$tr_after}>\n";
936 array_push ( $tr_history , true );
937 array_push ( $tr_attributes , '' );
938 array_pop ( $has_opened_tr );
939 array_push ( $has_opened_tr , true );
942 $last_tag = array_pop ( $last_tag_history );
944 if ( array_pop ( $td_history ) ) {
945 $previous = "</{$last_tag}>{$previous}";
948 if ( $first_character == '|' ) {
950 } else if ( $first_character == '!' ) {
952 } else if ( $first_character == '+' ) {
953 $last_tag = 'caption';
958 array_push ( $last_tag_history , $last_tag );
960 // A cell could contain both parameters and data
961 $cell_data = explode ( '|' , $cell , 2 );
963 // Bug 553: Note that a '|' inside an invalid link should not
964 // be mistaken as delimiting cell parameters
965 if ( strpos( $cell_data[0], '[[' ) !== false ) {
966 $cell = "{$previous}<{$last_tag}>{$cell}";
967 } else if ( count ( $cell_data ) == 1 )
968 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
970 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
971 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
972 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
975 $lines[$key] .= $cell;
976 array_push ( $td_history , true );
981 // Closing open td, tr && table
982 while ( count ( $td_history ) > 0 )
984 if ( array_pop ( $td_history ) ) {
987 if ( array_pop ( $tr_history ) ) {
990 if ( !array_pop ( $has_opened_tr ) ) {
991 $lines[] = "<tr><td></td></tr>" ;
994 $lines[] = '</table>' ;
997 $output = implode ( "\n" , $lines ) ;
999 // special case: don't return empty table
1000 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
1004 wfProfileOut( $fname );
1010 * Helper function for parse() that transforms wiki markup into
1011 * HTML. Only called for $mOutputType == OT_HTML.
1015 function internalParse( $text ) {
1018 $fname = 'Parser::internalParse';
1019 wfProfileIn( $fname );
1021 # Hook to suspend the parser in this state
1022 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1023 wfProfileOut( $fname );
1027 # Remove <noinclude> tags and <includeonly> sections
1028 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
1029 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1030 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1032 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
1034 $text = $this->replaceVariables( $text, $args );
1035 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1037 // Tables need to come after variable replacement for things to work
1038 // properly; putting them before other transformations should keep
1039 // exciting things like link expansions from showing up in surprising
1041 $text = $this->doTableStuff( $text );
1043 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1045 $text = $this->stripToc( $text );
1046 $this->stripNoGallery( $text );
1047 $text = $this->doHeadings( $text );
1048 if($this->mOptions
->getUseDynamicDates()) {
1049 $df =& DateFormatter
::getInstance();
1050 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1052 $text = $this->doAllQuotes( $text );
1053 $text = $this->replaceInternalLinks( $text );
1054 $text = $this->replaceExternalLinks( $text );
1056 # replaceInternalLinks may sometimes leave behind
1057 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1058 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1060 $text = $this->doMagicLinks( $text );
1061 $text = $this->formatHeadings( $text, $isMain );
1063 wfProfileOut( $fname );
1068 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1069 * magic external links.
1073 function &doMagicLinks( &$text ) {
1074 wfProfileIn( __METHOD__
);
1075 $text = preg_replace_callback(
1077 <a.*?</a> | # Skip link text
1078 <.*?> | # Skip stuff inside HTML elements
1079 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1080 ISBN\s+(\b # ISBN, capture number as m[2]
1081 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1082 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1083 [0-9Xx] # check digit
1085 )!x', array( &$this, 'magicLinkCallback' ), $text );
1086 wfProfileOut( __METHOD__
);
1090 function magicLinkCallback( $m ) {
1091 if ( substr( $m[0], 0, 1 ) == '<' ) {
1094 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1096 $num = strtr( $isbn, array(
1101 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1102 $text = '<a href="' .
1103 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1104 "\" class=\"internal\">ISBN $isbn</a>";
1106 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1110 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1112 $urlmsg = 'pubmedurl';
1115 throw new MWException( __METHOD__
.': unrecognised match type "' .
1116 substr($m[0], 0, 20 ) . '"' );
1119 $url = wfMsg( $urlmsg, $id);
1120 $sk = $this->mOptions
->getSkin();
1121 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1122 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1128 * Parse headers and return html
1132 function doHeadings( $text ) {
1133 $fname = 'Parser::doHeadings';
1134 wfProfileIn( $fname );
1135 for ( $i = 6; $i >= 1; --$i ) {
1136 $h = str_repeat( '=', $i );
1137 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1138 "<h{$i}>\\1</h{$i}>\\2", $text );
1140 wfProfileOut( $fname );
1145 * Replace single quotes with HTML markup
1147 * @return string the altered text
1149 function doAllQuotes( $text ) {
1150 $fname = 'Parser::doAllQuotes';
1151 wfProfileIn( $fname );
1153 $lines = explode( "\n", $text );
1154 foreach ( $lines as $line ) {
1155 $outtext .= $this->doQuotes ( $line ) . "\n";
1157 $outtext = substr($outtext, 0,-1);
1158 wfProfileOut( $fname );
1163 * Helper function for doAllQuotes()
1165 public function doQuotes( $text ) {
1166 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1167 if ( count( $arr ) == 1 )
1171 # First, do some preliminary work. This may shift some apostrophes from
1172 # being mark-up to being text. It also counts the number of occurrences
1173 # of bold and italics mark-ups.
1177 foreach ( $arr as $r )
1179 if ( ( $i %
2 ) == 1 )
1181 # If there are ever four apostrophes, assume the first is supposed to
1182 # be text, and the remaining three constitute mark-up for bold text.
1183 if ( strlen( $arr[$i] ) == 4 )
1188 # If there are more than 5 apostrophes in a row, assume they're all
1189 # text except for the last 5.
1190 else if ( strlen( $arr[$i] ) > 5 )
1192 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1195 # Count the number of occurrences of bold and italics mark-ups.
1196 # We are not counting sequences of five apostrophes.
1197 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1198 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1199 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1204 # If there is an odd number of both bold and italics, it is likely
1205 # that one of the bold ones was meant to be an apostrophe followed
1206 # by italics. Which one we cannot know for certain, but it is more
1207 # likely to be one that has a single-letter word before it.
1208 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1211 $firstsingleletterword = -1;
1212 $firstmultiletterword = -1;
1214 foreach ( $arr as $r )
1216 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1218 $x1 = substr ($arr[$i-1], -1);
1219 $x2 = substr ($arr[$i-1], -2, 1);
1221 if ($firstspace == -1) $firstspace = $i;
1222 } else if ($x2 == ' ') {
1223 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1225 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1231 # If there is a single-letter word, use it!
1232 if ($firstsingleletterword > -1)
1234 $arr [ $firstsingleletterword ] = "''";
1235 $arr [ $firstsingleletterword-1 ] .= "'";
1237 # If not, but there's a multi-letter word, use that one.
1238 else if ($firstmultiletterword > -1)
1240 $arr [ $firstmultiletterword ] = "''";
1241 $arr [ $firstmultiletterword-1 ] .= "'";
1243 # ... otherwise use the first one that has neither.
1244 # (notice that it is possible for all three to be -1 if, for example,
1245 # there is only one pentuple-apostrophe in the line)
1246 else if ($firstspace > -1)
1248 $arr [ $firstspace ] = "''";
1249 $arr [ $firstspace-1 ] .= "'";
1253 # Now let's actually convert our apostrophic mush to HTML!
1258 foreach ($arr as $r)
1262 if ($state == 'both')
1269 if (strlen ($r) == 2)
1272 { $output .= '</i>'; $state = ''; }
1273 else if ($state == 'bi')
1274 { $output .= '</i>'; $state = 'b'; }
1275 else if ($state == 'ib')
1276 { $output .= '</b></i><b>'; $state = 'b'; }
1277 else if ($state == 'both')
1278 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1279 else # $state can be 'b' or ''
1280 { $output .= '<i>'; $state .= 'i'; }
1282 else if (strlen ($r) == 3)
1285 { $output .= '</b>'; $state = ''; }
1286 else if ($state == 'bi')
1287 { $output .= '</i></b><i>'; $state = 'i'; }
1288 else if ($state == 'ib')
1289 { $output .= '</b>'; $state = 'i'; }
1290 else if ($state == 'both')
1291 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1292 else # $state can be 'i' or ''
1293 { $output .= '<b>'; $state .= 'b'; }
1295 else if (strlen ($r) == 5)
1298 { $output .= '</b><i>'; $state = 'i'; }
1299 else if ($state == 'i')
1300 { $output .= '</i><b>'; $state = 'b'; }
1301 else if ($state == 'bi')
1302 { $output .= '</i></b>'; $state = ''; }
1303 else if ($state == 'ib')
1304 { $output .= '</b></i>'; $state = ''; }
1305 else if ($state == 'both')
1306 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1307 else # ($state == '')
1308 { $buffer = ''; $state = 'both'; }
1313 # Now close all remaining tags. Notice that the order is important.
1314 if ($state == 'b' ||
$state == 'ib')
1316 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1320 # There might be lonely ''''', so make sure we have a buffer
1321 if ($state == 'both' && $buffer)
1322 $output .= '<b><i>'.$buffer.'</i></b>';
1328 * Replace external links
1330 * Note: this is all very hackish and the order of execution matters a lot.
1331 * Make sure to run maintenance/parserTests.php if you change this code.
1335 function replaceExternalLinks( $text ) {
1337 $fname = 'Parser::replaceExternalLinks';
1338 wfProfileIn( $fname );
1340 $sk = $this->mOptions
->getSkin();
1342 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1344 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1347 while ( $i<count( $bits ) ) {
1349 $protocol = $bits[$i++
];
1350 $text = $bits[$i++
];
1351 $trail = $bits[$i++
];
1353 # The characters '<' and '>' (which were escaped by
1354 # removeHTMLtags()) should not be included in
1355 # URLs, per RFC 2396.
1357 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1358 $text = substr($url, $m2[0][1]) . ' ' . $text;
1359 $url = substr($url, 0, $m2[0][1]);
1362 # If the link text is an image URL, replace it with an <img> tag
1363 # This happened by accident in the original parser, but some people used it extensively
1364 $img = $this->maybeMakeExternalImage( $text );
1365 if ( $img !== false ) {
1371 # Set linktype for CSS - if URL==text, link is essentially free
1372 $linktype = ($text == $url) ?
'free' : 'text';
1374 # No link text, e.g. [http://domain.tld/some.link]
1375 if ( $text == '' ) {
1376 # Autonumber if allowed. See bug #5918
1377 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1378 $text = '[' . ++
$this->mAutonumber
. ']';
1379 $linktype = 'autonumber';
1381 # Otherwise just use the URL
1382 $text = htmlspecialchars( $url );
1386 # Have link text, e.g. [http://domain.tld/some.link text]s
1388 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1391 $text = $wgContLang->markNoConversion($text);
1393 $url = Sanitizer
::cleanUrl( $url );
1395 # Process the trail (i.e. everything after this link up until start of the next link),
1396 # replacing any non-bracketed links
1397 $trail = $this->replaceFreeExternalLinks( $trail );
1399 # Use the encoded URL
1400 # This means that users can paste URLs directly into the text
1401 # Funny characters like ö aren't valid in URLs anyway
1402 # This was changed in August 2004
1403 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1405 # Register link in the output object.
1406 # Replace unnecessary URL escape codes with the referenced character
1407 # This prevents spammers from hiding links from the filters
1408 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1409 $this->mOutput
->addExternalLink( $pasteurized );
1412 wfProfileOut( $fname );
1417 * Replace anything that looks like a URL with a link
1420 function replaceFreeExternalLinks( $text ) {
1422 $fname = 'Parser::replaceFreeExternalLinks';
1423 wfProfileIn( $fname );
1425 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1426 $s = array_shift( $bits );
1429 $sk = $this->mOptions
->getSkin();
1431 while ( $i < count( $bits ) ){
1432 $protocol = $bits[$i++
];
1433 $remainder = $bits[$i++
];
1436 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1437 # Found some characters after the protocol that look promising
1438 $url = $protocol . $m[1];
1441 # special case: handle urls as url args:
1442 # http://www.example.com/foo?=http://www.example.com/bar
1443 if(strlen($trail) == 0 &&
1445 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1446 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1449 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1454 # The characters '<' and '>' (which were escaped by
1455 # removeHTMLtags()) should not be included in
1456 # URLs, per RFC 2396.
1458 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1459 $trail = substr($url, $m2[0][1]) . $trail;
1460 $url = substr($url, 0, $m2[0][1]);
1463 # Move trailing punctuation to $trail
1465 # If there is no left bracket, then consider right brackets fair game too
1466 if ( strpos( $url, '(' ) === false ) {
1470 $numSepChars = strspn( strrev( $url ), $sep );
1471 if ( $numSepChars ) {
1472 $trail = substr( $url, -$numSepChars ) . $trail;
1473 $url = substr( $url, 0, -$numSepChars );
1476 $url = Sanitizer
::cleanUrl( $url );
1478 # Is this an external image?
1479 $text = $this->maybeMakeExternalImage( $url );
1480 if ( $text === false ) {
1481 # Not an image, make a link
1482 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1483 # Register it in the output object...
1484 # Replace unnecessary URL escape codes with their equivalent characters
1485 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1486 $this->mOutput
->addExternalLink( $pasteurized );
1488 $s .= $text . $trail;
1490 $s .= $protocol . $remainder;
1493 wfProfileOut( $fname );
1498 * Replace unusual URL escape codes with their equivalent characters
1502 * @todo This can merge genuinely required bits in the path or query string,
1503 * breaking legit URLs. A proper fix would treat the various parts of
1504 * the URL differently; as a workaround, just use the output for
1505 * statistical records, not for actual linking/output.
1507 static function replaceUnusualEscapes( $url ) {
1508 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1509 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1513 * Callback function used in replaceUnusualEscapes().
1514 * Replaces unusual URL escape codes with their equivalent character
1518 private static function replaceUnusualEscapesCallback( $matches ) {
1519 $char = urldecode( $matches[0] );
1520 $ord = ord( $char );
1521 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1522 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1523 // No, shouldn't be escaped
1526 // Yes, leave it escaped
1532 * make an image if it's allowed, either through the global
1533 * option or through the exception
1536 function maybeMakeExternalImage( $url ) {
1537 $sk = $this->mOptions
->getSkin();
1538 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1539 $imagesexception = !empty($imagesfrom);
1541 if ( $this->mOptions
->getAllowExternalImages()
1542 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1543 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1545 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1552 * Process [[ ]] wikilinks
1556 function replaceInternalLinks( $s ) {
1558 static $fname = 'Parser::replaceInternalLinks' ;
1560 wfProfileIn( $fname );
1562 wfProfileIn( $fname.'-setup' );
1564 # the % is needed to support urlencoded titles as well
1565 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1567 $sk = $this->mOptions
->getSkin();
1569 #split the entire text string on occurences of [[
1570 $a = explode( '[[', ' ' . $s );
1571 #get the first element (all text up to first [[), and remove the space we added
1572 $s = array_shift( $a );
1573 $s = substr( $s, 1 );
1575 # Match a link having the form [[namespace:link|alternate]]trail
1577 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1578 # Match cases where there is no "]]", which might still be images
1579 static $e1_img = FALSE;
1580 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1582 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1584 if ( $useLinkPrefixExtension ) {
1585 # Match the end of a line for a word that's not followed by whitespace,
1586 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1587 $e2 = wfMsgForContent( 'linkprefix' );
1590 if( is_null( $this->mTitle
) ) {
1591 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1593 $nottalk = !$this->mTitle
->isTalkPage();
1595 if ( $useLinkPrefixExtension ) {
1597 if ( preg_match( $e2, $s, $m ) ) {
1598 $first_prefix = $m[2];
1600 $first_prefix = false;
1606 if($wgContLang->hasVariants()) {
1607 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1609 $selflink = array($this->mTitle
->getPrefixedText());
1611 $useSubpages = $this->areSubpagesAllowed();
1612 wfProfileOut( $fname.'-setup' );
1614 # Loop for each link
1615 for ($k = 0; isset( $a[$k] ); $k++
) {
1617 if ( $useLinkPrefixExtension ) {
1618 wfProfileIn( $fname.'-prefixhandling' );
1619 if ( preg_match( $e2, $s, $m ) ) {
1627 $prefix = $first_prefix;
1628 $first_prefix = false;
1630 wfProfileOut( $fname.'-prefixhandling' );
1633 $might_be_img = false;
1635 wfProfileIn( "$fname-e1" );
1636 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1638 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1639 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1640 # the real problem is with the $e1 regex
1643 # Still some problems for cases where the ] is meant to be outside punctuation,
1644 # and no image is in sight. See bug 2095.
1647 substr( $m[3], 0, 1 ) === ']' &&
1648 strpos($text, '[') !== false
1651 $text .= ']'; # so that replaceExternalLinks($text) works later
1652 $m[3] = substr( $m[3], 1 );
1654 # fix up urlencoded title texts
1655 if( strpos( $m[1], '%' ) !== false ) {
1656 # Should anchors '#' also be rejected?
1657 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1660 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1661 $might_be_img = true;
1663 if ( strpos( $m[1], '%' ) !== false ) {
1664 $m[1] = urldecode($m[1]);
1667 } else { # Invalid form; output directly
1668 $s .= $prefix . '[[' . $line ;
1669 wfProfileOut( "$fname-e1" );
1672 wfProfileOut( "$fname-e1" );
1673 wfProfileIn( "$fname-misc" );
1675 # Don't allow internal links to pages containing
1676 # PROTO: where PROTO is a valid URL protocol; these
1677 # should be external links.
1678 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1679 $s .= $prefix . '[[' . $line ;
1683 # Make subpage if necessary
1684 if( $useSubpages ) {
1685 $link = $this->maybeDoSubpageLink( $m[1], $text );
1690 $noforce = (substr($m[1], 0, 1) != ':');
1692 # Strip off leading ':'
1693 $link = substr($link, 1);
1696 wfProfileOut( "$fname-misc" );
1697 wfProfileIn( "$fname-title" );
1698 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1700 $s .= $prefix . '[[' . $line;
1701 wfProfileOut( "$fname-title" );
1705 $ns = $nt->getNamespace();
1706 $iw = $nt->getInterWiki();
1707 wfProfileOut( "$fname-title" );
1709 if ($might_be_img) { # if this is actually an invalid link
1710 wfProfileIn( "$fname-might_be_img" );
1711 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1713 while (isset ($a[$k+
1]) ) {
1714 #look at the next 'line' to see if we can close it there
1715 $spliced = array_splice( $a, $k +
1, 1 );
1716 $next_line = array_shift( $spliced );
1717 $m = explode( ']]', $next_line, 3 );
1718 if ( count( $m ) == 3 ) {
1719 # the first ]] closes the inner link, the second the image
1721 $text .= "[[{$m[0]}]]{$m[1]}";
1724 } elseif ( count( $m ) == 2 ) {
1725 #if there's exactly one ]] that's fine, we'll keep looking
1726 $text .= "[[{$m[0]}]]{$m[1]}";
1728 #if $next_line is invalid too, we need look no further
1729 $text .= '[[' . $next_line;
1734 # we couldn't find the end of this imageLink, so output it raw
1735 #but don't ignore what might be perfectly normal links in the text we've examined
1736 $text = $this->replaceInternalLinks($text);
1737 $s .= "{$prefix}[[$link|$text";
1738 # note: no $trail, because without an end, there *is* no trail
1739 wfProfileOut( "$fname-might_be_img" );
1742 } else { #it's not an image, so output it raw
1743 $s .= "{$prefix}[[$link|$text";
1744 # note: no $trail, because without an end, there *is* no trail
1745 wfProfileOut( "$fname-might_be_img" );
1748 wfProfileOut( "$fname-might_be_img" );
1751 $wasblank = ( '' == $text );
1752 if( $wasblank ) $text = $link;
1754 # Link not escaped by : , create the various objects
1758 wfProfileIn( "$fname-interwiki" );
1759 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1760 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1761 $s = rtrim($s . $prefix);
1762 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1763 wfProfileOut( "$fname-interwiki" );
1766 wfProfileOut( "$fname-interwiki" );
1768 if ( $ns == NS_IMAGE
) {
1769 wfProfileIn( "$fname-image" );
1770 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1771 # recursively parse links inside the image caption
1772 # actually, this will parse them in any other parameters, too,
1773 # but it might be hard to fix that, and it doesn't matter ATM
1774 $text = $this->replaceExternalLinks($text);
1775 $text = $this->replaceInternalLinks($text);
1777 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1778 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1779 $this->mOutput
->addImage( $nt->getDBkey() );
1781 wfProfileOut( "$fname-image" );
1784 # We still need to record the image's presence on the page
1785 $this->mOutput
->addImage( $nt->getDBkey() );
1787 wfProfileOut( "$fname-image" );
1791 if ( $ns == NS_CATEGORY
) {
1792 wfProfileIn( "$fname-category" );
1793 $s = rtrim($s . "\n"); # bug 87
1796 $sortkey = $this->getDefaultSort();
1800 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1801 $sortkey = str_replace( "\n", '', $sortkey );
1802 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1803 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1806 * Strip the whitespace Category links produce, see bug 87
1807 * @todo We might want to use trim($tmp, "\n") here.
1809 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1811 wfProfileOut( "$fname-category" );
1816 # Self-link checking
1817 if( $nt->getFragment() === '' ) {
1818 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1819 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1824 # Special and Media are pseudo-namespaces; no pages actually exist in them
1825 if( $ns == NS_MEDIA
) {
1826 $link = $sk->makeMediaLinkObj( $nt, $text );
1827 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1828 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1829 $this->mOutput
->addImage( $nt->getDBkey() );
1831 } elseif( $ns == NS_SPECIAL
) {
1832 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1833 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1835 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1838 } elseif( $ns == NS_IMAGE
) {
1839 $img = wfFindFile( $nt );
1841 // Force a blue link if the file exists; may be a remote
1842 // upload on the shared repository, and we want to see its
1843 // auto-generated page.
1844 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1845 $this->mOutput
->addLink( $nt );
1849 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1851 wfProfileOut( $fname );
1856 * Make a link placeholder. The text returned can be later resolved to a real link with
1857 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1858 * parsing of interwiki links, and secondly to allow all existence checks and
1859 * article length checks (for stub links) to be bundled into a single query.
1862 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1863 wfProfileIn( __METHOD__
);
1864 if ( ! is_object($nt) ) {
1866 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1868 # Separate the link trail from the rest of the link
1869 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1871 if ( $nt->isExternal() ) {
1872 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1873 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1874 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1876 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1877 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1878 $this->mLinkHolders
['queries'][] = $query;
1879 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1880 $this->mLinkHolders
['titles'][] = $nt;
1882 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1885 wfProfileOut( __METHOD__
);
1890 * Render a forced-blue link inline; protect against double expansion of
1891 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1892 * Since this little disaster has to split off the trail text to avoid
1893 * breaking URLs in the following text without breaking trails on the
1894 * wiki links, it's been made into a horrible function.
1897 * @param string $text
1898 * @param string $query
1899 * @param string $trail
1900 * @param string $prefix
1901 * @return string HTML-wikitext mix oh yuck
1903 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1904 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1905 $sk = $this->mOptions
->getSkin();
1906 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1907 return $this->armorLinks( $link ) . $trail;
1911 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1912 * going to go through further parsing steps before inline URL expansion.
1914 * In particular this is important when using action=render, which causes
1915 * full URLs to be included.
1917 * Oh man I hate our multi-layer parser!
1919 * @param string more-or-less HTML
1920 * @return string less-or-more HTML with NOPARSE bits
1922 function armorLinks( $text ) {
1923 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1924 "{$this->mUniqPrefix}NOPARSE$1", $text );
1928 * Return true if subpage links should be expanded on this page.
1931 function areSubpagesAllowed() {
1932 # Some namespaces don't allow subpages
1933 global $wgNamespacesWithSubpages;
1934 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1938 * Handle link to subpage if necessary
1939 * @param string $target the source of the link
1940 * @param string &$text the link text, modified as necessary
1941 * @return string the full name of the link
1944 function maybeDoSubpageLink($target, &$text) {
1947 # :Foobar -- override special treatment of prefix (images, language links)
1948 # /Foobar -- convert to CurrentPage/Foobar
1949 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1950 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1951 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1953 $fname = 'Parser::maybeDoSubpageLink';
1954 wfProfileIn( $fname );
1955 $ret = $target; # default return value is no change
1957 # Some namespaces don't allow subpages,
1958 # so only perform processing if subpages are allowed
1959 if( $this->areSubpagesAllowed() ) {
1960 $hash = strpos( $target, '#' );
1961 if( $hash !== false ) {
1962 $suffix = substr( $target, $hash );
1963 $target = substr( $target, 0, $hash );
1968 $target = trim( $target );
1969 # Look at the first character
1970 if( $target != '' && $target{0} == '/' ) {
1971 # / at end means we don't want the slash to be shown
1973 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1974 if( $trailingSlashes ) {
1975 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1977 $noslash = substr( $target, 1 );
1980 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1981 if( '' === $text ) {
1982 $text = $target . $suffix;
1983 } # this might be changed for ugliness reasons
1985 # check for .. subpage backlinks
1987 $nodotdot = $target;
1988 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1990 $nodotdot = substr( $nodotdot, 3 );
1992 if($dotdotcount > 0) {
1993 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1994 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1995 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1996 # / at the end means don't show full path
1997 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1998 $nodotdot = substr( $nodotdot, 0, -1 );
1999 if( '' === $text ) {
2000 $text = $nodotdot . $suffix;
2003 $nodotdot = trim( $nodotdot );
2004 if( $nodotdot != '' ) {
2005 $ret .= '/' . $nodotdot;
2013 wfProfileOut( $fname );
2018 * Used by doBlockLevels()
2021 /* private */ function closeParagraph() {
2023 if ( '' != $this->mLastSection
) {
2024 $result = '</' . $this->mLastSection
. ">\n";
2026 $this->mInPre
= false;
2027 $this->mLastSection
= '';
2030 # getCommon() returns the length of the longest common substring
2031 # of both arguments, starting at the beginning of both.
2033 /* private */ function getCommon( $st1, $st2 ) {
2034 $fl = strlen( $st1 );
2035 $shorter = strlen( $st2 );
2036 if ( $fl < $shorter ) { $shorter = $fl; }
2038 for ( $i = 0; $i < $shorter; ++
$i ) {
2039 if ( $st1{$i} != $st2{$i} ) { break; }
2043 # These next three functions open, continue, and close the list
2044 # element appropriate to the prefix character passed into them.
2046 /* private */ function openList( $char ) {
2047 $result = $this->closeParagraph();
2049 if ( '*' == $char ) { $result .= '<ul><li>'; }
2050 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2051 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2052 else if ( ';' == $char ) {
2053 $result .= '<dl><dt>';
2054 $this->mDTopen
= true;
2056 else { $result = '<!-- ERR 1 -->'; }
2061 /* private */ function nextItem( $char ) {
2062 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2063 else if ( ':' == $char ||
';' == $char ) {
2065 if ( $this->mDTopen
) { $close = '</dt>'; }
2066 if ( ';' == $char ) {
2067 $this->mDTopen
= true;
2068 return $close . '<dt>';
2070 $this->mDTopen
= false;
2071 return $close . '<dd>';
2074 return '<!-- ERR 2 -->';
2077 /* private */ function closeList( $char ) {
2078 if ( '*' == $char ) { $text = '</li></ul>'; }
2079 else if ( '#' == $char ) { $text = '</li></ol>'; }
2080 else if ( ':' == $char ) {
2081 if ( $this->mDTopen
) {
2082 $this->mDTopen
= false;
2083 $text = '</dt></dl>';
2085 $text = '</dd></dl>';
2088 else { return '<!-- ERR 3 -->'; }
2094 * Make lists from lines starting with ':', '*', '#', etc.
2097 * @return string the lists rendered as HTML
2099 function doBlockLevels( $text, $linestart ) {
2100 $fname = 'Parser::doBlockLevels';
2101 wfProfileIn( $fname );
2103 # Parsing through the text line by line. The main thing
2104 # happening here is handling of block-level elements p, pre,
2105 # and making lists from lines starting with * # : etc.
2107 $textLines = explode( "\n", $text );
2109 $lastPrefix = $output = '';
2110 $this->mDTopen
= $inBlockElem = false;
2112 $paragraphStack = false;
2114 if ( !$linestart ) {
2115 $output .= array_shift( $textLines );
2117 foreach ( $textLines as $oLine ) {
2118 $lastPrefixLength = strlen( $lastPrefix );
2119 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2120 $preOpenMatch = preg_match('/<pre/i', $oLine );
2121 if ( !$this->mInPre
) {
2122 # Multiple prefixes may abut each other for nested lists.
2123 $prefixLength = strspn( $oLine, '*#:;' );
2124 $pref = substr( $oLine, 0, $prefixLength );
2127 $pref2 = str_replace( ';', ':', $pref );
2128 $t = substr( $oLine, $prefixLength );
2129 $this->mInPre
= !empty($preOpenMatch);
2131 # Don't interpret any other prefixes in preformatted text
2133 $pref = $pref2 = '';
2138 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2139 # Same as the last item, so no need to deal with nesting or opening stuff
2140 $output .= $this->nextItem( substr( $pref, -1 ) );
2141 $paragraphStack = false;
2143 if ( substr( $pref, -1 ) == ';') {
2144 # The one nasty exception: definition lists work like this:
2145 # ; title : definition text
2146 # So we check for : in the remainder text to split up the
2147 # title and definition, without b0rking links.
2149 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2151 $output .= $term . $this->nextItem( ':' );
2154 } elseif( $prefixLength ||
$lastPrefixLength ) {
2155 # Either open or close a level...
2156 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2157 $paragraphStack = false;
2159 while( $commonPrefixLength < $lastPrefixLength ) {
2160 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2161 --$lastPrefixLength;
2163 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2164 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2166 while ( $prefixLength > $commonPrefixLength ) {
2167 $char = substr( $pref, $commonPrefixLength, 1 );
2168 $output .= $this->openList( $char );
2170 if ( ';' == $char ) {
2171 # FIXME: This is dupe of code above
2172 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2174 $output .= $term . $this->nextItem( ':' );
2177 ++
$commonPrefixLength;
2179 $lastPrefix = $pref2;
2181 if( 0 == $prefixLength ) {
2182 wfProfileIn( "$fname-paragraph" );
2183 # No prefix (not in list)--go to paragraph mode
2184 // XXX: use a stack for nestable elements like span, table and div
2185 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2186 $closematch = preg_match(
2187 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2188 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2189 if ( $openmatch or $closematch ) {
2190 $paragraphStack = false;
2191 #Â TODO bug 5718: paragraph closed
2192 $output .= $this->closeParagraph();
2193 if ( $preOpenMatch and !$preCloseMatch ) {
2194 $this->mInPre
= true;
2196 if ( $closematch ) {
2197 $inBlockElem = false;
2199 $inBlockElem = true;
2201 } else if ( !$inBlockElem && !$this->mInPre
) {
2202 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2204 if ($this->mLastSection
!= 'pre') {
2205 $paragraphStack = false;
2206 $output .= $this->closeParagraph().'<pre>';
2207 $this->mLastSection
= 'pre';
2209 $t = substr( $t, 1 );
2212 if ( '' == trim($t) ) {
2213 if ( $paragraphStack ) {
2214 $output .= $paragraphStack.'<br />';
2215 $paragraphStack = false;
2216 $this->mLastSection
= 'p';
2218 if ($this->mLastSection
!= 'p' ) {
2219 $output .= $this->closeParagraph();
2220 $this->mLastSection
= '';
2221 $paragraphStack = '<p>';
2223 $paragraphStack = '</p><p>';
2227 if ( $paragraphStack ) {
2228 $output .= $paragraphStack;
2229 $paragraphStack = false;
2230 $this->mLastSection
= 'p';
2231 } else if ($this->mLastSection
!= 'p') {
2232 $output .= $this->closeParagraph().'<p>';
2233 $this->mLastSection
= 'p';
2238 wfProfileOut( "$fname-paragraph" );
2240 // somewhere above we forget to get out of pre block (bug 785)
2241 if($preCloseMatch && $this->mInPre
) {
2242 $this->mInPre
= false;
2244 if ($paragraphStack === false) {
2248 while ( $prefixLength ) {
2249 $output .= $this->closeList( $pref2{$prefixLength-1} );
2252 if ( '' != $this->mLastSection
) {
2253 $output .= '</' . $this->mLastSection
. '>';
2254 $this->mLastSection
= '';
2257 wfProfileOut( $fname );
2262 * Split up a string on ':', ignoring any occurences inside tags
2263 * to prevent illegal overlapping.
2264 * @param string $str the string to split
2265 * @param string &$before set to everything before the ':'
2266 * @param string &$after set to everything after the ':'
2267 * return string the position of the ':', or false if none found
2269 function findColonNoLinks($str, &$before, &$after) {
2270 $fname = 'Parser::findColonNoLinks';
2271 wfProfileIn( $fname );
2273 $pos = strpos( $str, ':' );
2274 if( $pos === false ) {
2276 wfProfileOut( $fname );
2280 $lt = strpos( $str, '<' );
2281 if( $lt === false ||
$lt > $pos ) {
2282 // Easy; no tag nesting to worry about
2283 $before = substr( $str, 0, $pos );
2284 $after = substr( $str, $pos+
1 );
2285 wfProfileOut( $fname );
2289 // Ugly state machine to walk through avoiding tags.
2290 $state = MW_COLON_STATE_TEXT
;
2292 $len = strlen( $str );
2293 for( $i = 0; $i < $len; $i++
) {
2297 // (Using the number is a performance hack for common cases)
2298 case 0: // MW_COLON_STATE_TEXT:
2301 // Could be either a <start> tag or an </end> tag
2302 $state = MW_COLON_STATE_TAGSTART
;
2307 $before = substr( $str, 0, $i );
2308 $after = substr( $str, $i +
1 );
2309 wfProfileOut( $fname );
2312 // Embedded in a tag; don't break it.
2315 // Skip ahead looking for something interesting
2316 $colon = strpos( $str, ':', $i );
2317 if( $colon === false ) {
2318 // Nothing else interesting
2319 wfProfileOut( $fname );
2322 $lt = strpos( $str, '<', $i );
2323 if( $stack === 0 ) {
2324 if( $lt === false ||
$colon < $lt ) {
2326 $before = substr( $str, 0, $colon );
2327 $after = substr( $str, $colon +
1 );
2328 wfProfileOut( $fname );
2332 if( $lt === false ) {
2333 // Nothing else interesting to find; abort!
2334 // We're nested, but there's no close tags left. Abort!
2337 // Skip ahead to next tag start
2339 $state = MW_COLON_STATE_TAGSTART
;
2342 case 1: // MW_COLON_STATE_TAG:
2347 $state = MW_COLON_STATE_TEXT
;
2350 // Slash may be followed by >?
2351 $state = MW_COLON_STATE_TAGSLASH
;
2357 case 2: // MW_COLON_STATE_TAGSTART:
2360 $state = MW_COLON_STATE_CLOSETAG
;
2363 $state = MW_COLON_STATE_COMMENT
;
2366 // Illegal early close? This shouldn't happen D:
2367 $state = MW_COLON_STATE_TEXT
;
2370 $state = MW_COLON_STATE_TAG
;
2373 case 3: // MW_COLON_STATE_CLOSETAG:
2378 wfDebug( "Invalid input in $fname; too many close tags\n" );
2379 wfProfileOut( $fname );
2382 $state = MW_COLON_STATE_TEXT
;
2385 case MW_COLON_STATE_TAGSLASH
:
2387 // Yes, a self-closed tag <blah/>
2388 $state = MW_COLON_STATE_TEXT
;
2390 // Probably we're jumping the gun, and this is an attribute
2391 $state = MW_COLON_STATE_TAG
;
2394 case 5: // MW_COLON_STATE_COMMENT:
2396 $state = MW_COLON_STATE_COMMENTDASH
;
2399 case MW_COLON_STATE_COMMENTDASH
:
2401 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2403 $state = MW_COLON_STATE_COMMENT
;
2406 case MW_COLON_STATE_COMMENTDASHDASH
:
2408 $state = MW_COLON_STATE_TEXT
;
2410 $state = MW_COLON_STATE_COMMENT
;
2414 throw new MWException( "State machine error in $fname" );
2418 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2421 wfProfileOut( $fname );
2426 * Return value of a magic variable (like PAGENAME)
2430 function getVariableValue( $index ) {
2431 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2434 * Some of these require message or data lookups and can be
2435 * expensive to check many times.
2437 static $varCache = array();
2438 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2439 if ( isset( $varCache[$index] ) ) {
2440 return $varCache[$index];
2445 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2448 global $wgLocaltimezone;
2449 if ( isset( $wgLocaltimezone ) ) {
2450 $oldtz = getenv( 'TZ' );
2451 putenv( 'TZ='.$wgLocaltimezone );
2454 wfSuppressWarnings(); // E_STRICT system time bitching
2455 $localTimestamp = date( 'YmdHis', $ts );
2456 $localMonth = date( 'm', $ts );
2457 $localMonthName = date( 'n', $ts );
2458 $localDay = date( 'j', $ts );
2459 $localDay2 = date( 'd', $ts );
2460 $localDayOfWeek = date( 'w', $ts );
2461 $localWeek = date( 'W', $ts );
2462 $localYear = date( 'Y', $ts );
2463 $localHour = date( 'H', $ts );
2464 if ( isset( $wgLocaltimezone ) ) {
2465 putenv( 'TZ='.$oldtz );
2467 wfRestoreWarnings();
2470 case 'currentmonth':
2471 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2472 case 'currentmonthname':
2473 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2474 case 'currentmonthnamegen':
2475 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2476 case 'currentmonthabbrev':
2477 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2479 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2481 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2483 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2484 case 'localmonthname':
2485 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2486 case 'localmonthnamegen':
2487 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2488 case 'localmonthabbrev':
2489 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2491 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2493 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2495 return wfEscapeWikiText( $this->mTitle
->getText() );
2497 return $this->mTitle
->getPartialURL();
2498 case 'fullpagename':
2499 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2500 case 'fullpagenamee':
2501 return $this->mTitle
->getPrefixedURL();
2503 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2504 case 'subpagenamee':
2505 return $this->mTitle
->getSubpageUrlForm();
2506 case 'basepagename':
2507 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2508 case 'basepagenamee':
2509 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2510 case 'talkpagename':
2511 if( $this->mTitle
->canTalk() ) {
2512 $talkPage = $this->mTitle
->getTalkPage();
2513 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2517 case 'talkpagenamee':
2518 if( $this->mTitle
->canTalk() ) {
2519 $talkPage = $this->mTitle
->getTalkPage();
2520 return $talkPage->getPrefixedUrl();
2524 case 'subjectpagename':
2525 $subjPage = $this->mTitle
->getSubjectPage();
2526 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2527 case 'subjectpagenamee':
2528 $subjPage = $this->mTitle
->getSubjectPage();
2529 return $subjPage->getPrefixedUrl();
2531 return $this->mRevisionId
;
2533 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2534 case 'revisionday2':
2535 return substr( $this->getRevisionTimestamp(), 6, 2 );
2536 case 'revisionmonth':
2537 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2538 case 'revisionyear':
2539 return substr( $this->getRevisionTimestamp(), 0, 4 );
2540 case 'revisiontimestamp':
2541 return $this->getRevisionTimestamp();
2543 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2545 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2547 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2549 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2550 case 'subjectspace':
2551 return $this->mTitle
->getSubjectNsText();
2552 case 'subjectspacee':
2553 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2554 case 'currentdayname':
2555 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2557 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2559 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2561 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2563 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2564 // int to remove the padding
2565 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2567 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2568 case 'localdayname':
2569 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2571 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2573 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2575 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2577 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2578 // int to remove the padding
2579 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2581 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2582 case 'numberofarticles':
2583 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2584 case 'numberoffiles':
2585 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2586 case 'numberofusers':
2587 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2588 case 'numberofpages':
2589 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2590 case 'numberofadmins':
2591 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2592 case 'numberofedits':
2593 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2594 case 'currenttimestamp':
2595 return $varCache[$index] = wfTimestampNow();
2596 case 'localtimestamp':
2597 return $varCache[$index] = $localTimestamp;
2598 case 'currentversion':
2599 return $varCache[$index] = SpecialVersion
::getVersion();
2605 return $wgServerName;
2607 return $wgScriptPath;
2608 case 'directionmark':
2609 return $wgContLang->getDirMark();
2610 case 'contentlanguage':
2611 global $wgContLanguageCode;
2612 return $wgContLanguageCode;
2615 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2623 * initialise the magic variables (like CURRENTMONTHNAME)
2627 function initialiseVariables() {
2628 $fname = 'Parser::initialiseVariables';
2629 wfProfileIn( $fname );
2630 $variableIDs = MagicWord
::getVariableIDs();
2632 $this->mVariables
= array();
2633 foreach ( $variableIDs as $id ) {
2634 $mw =& MagicWord
::get( $id );
2635 $mw->addToArray( $this->mVariables
, $id );
2637 wfProfileOut( $fname );
2641 * parse any parentheses in format ((title|part|part))
2642 * and call callbacks to get a replacement text for any found piece
2644 * @param string $text The text to parse
2645 * @param array $callbacks rules in form:
2646 * '{' => array( # opening parentheses
2647 * 'end' => '}', # closing parentheses
2648 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2649 * 3 => callback # replacement callback to call if {{{..}}} is found
2652 * 'min' => 2, # Minimum parenthesis count in cb
2653 * 'max' => 3, # Maximum parenthesis count in cb
2656 function replace_callback ($text, $callbacks) {
2657 wfProfileIn( __METHOD__
);
2658 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2659 $lastOpeningBrace = -1; # last not closed parentheses
2661 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2664 while ( $i < strlen( $text ) ) {
2665 # Find next opening brace, closing brace or pipe
2666 if ( $lastOpeningBrace == -1 ) {
2667 $currentClosing = '';
2668 $search = $validOpeningBraces;
2670 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2671 $search = $validOpeningBraces . '|' . $currentClosing;
2674 $i +
= strcspn( $text, $search, $i );
2675 if ( $i < strlen( $text ) ) {
2676 if ( $text[$i] == '|' ) {
2678 } elseif ( $text[$i] == $currentClosing ) {
2680 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2682 $rule = $callbacks[$text[$i]];
2684 # Some versions of PHP have a strcspn which stops on null characters
2685 # Ignore and continue
2694 if ( $found == 'open' ) {
2695 # found opening brace, let's add it to parentheses stack
2696 $piece = array('brace' => $text[$i],
2697 'braceEnd' => $rule['end'],
2701 # count opening brace characters
2702 $piece['count'] = strspn( $text, $piece['brace'], $i );
2703 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2704 $i +
= $piece['count'];
2706 # we need to add to stack only if opening brace count is enough for one of the rules
2707 if ( $piece['count'] >= $rule['min'] ) {
2708 $lastOpeningBrace ++
;
2709 $openingBraceStack[$lastOpeningBrace] = $piece;
2711 } elseif ( $found == 'close' ) {
2712 # lets check if it is enough characters for closing brace
2713 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2714 $count = strspn( $text, $text[$i], $i, $maxCount );
2716 # check for maximum matching characters (if there are 5 closing
2717 # characters, we will probably need only 3 - depending on the rules)
2719 $matchingCallback = null;
2720 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2721 if ( $count > $cbType['max'] ) {
2722 # The specified maximum exists in the callback array, unless the caller
2724 $matchingCount = $cbType['max'];
2726 # Count is less than the maximum
2727 # Skip any gaps in the callback array to find the true largest match
2728 # Need to use array_key_exists not isset because the callback can be null
2729 $matchingCount = $count;
2730 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2735 if ($matchingCount <= 0) {
2739 $matchingCallback = $cbType['cb'][$matchingCount];
2741 # let's set a title or last part (if '|' was found)
2742 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2743 $openingBraceStack[$lastOpeningBrace]['title'] =
2744 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2745 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2748 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2749 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2752 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2753 $pieceEnd = $i +
$matchingCount;
2755 if( is_callable( $matchingCallback ) ) {
2757 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2758 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2759 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2760 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2762 # finally we can call a user callback and replace piece of text
2763 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2764 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2765 $i = $pieceStart +
strlen($replaceWith);
2767 # null value for callback means that parentheses should be parsed, but not replaced
2768 $i +
= $matchingCount;
2771 # reset last opening parentheses, but keep it in case there are unused characters
2772 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2773 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2774 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2777 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2778 $openingBraceStack[$lastOpeningBrace--] = null;
2780 if ($matchingCount < $piece['count']) {
2781 $piece['count'] -= $matchingCount;
2782 $piece['startAt'] -= $matchingCount;
2783 $piece['partStart'] = $piece['startAt'];
2784 # do we still qualify for any callback with remaining count?
2785 $currentCbList = $callbacks[$piece['brace']]['cb'];
2786 while ( $piece['count'] ) {
2787 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2788 $lastOpeningBrace++
;
2789 $openingBraceStack[$lastOpeningBrace] = $piece;
2795 } elseif ( $found == 'pipe' ) {
2796 # lets set a title if it is a first separator, or next part otherwise
2797 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2798 $openingBraceStack[$lastOpeningBrace]['title'] =
2799 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2800 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2801 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2803 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2804 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2805 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2807 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2811 wfProfileOut( __METHOD__
);
2816 * Replace magic variables, templates, and template arguments
2817 * with the appropriate text. Templates are substituted recursively,
2818 * taking care to avoid infinite loops.
2820 * Note that the substitution depends on value of $mOutputType:
2821 * OT_WIKI: only {{subst:}} templates
2822 * OT_MSG: only magic variables
2823 * OT_HTML: all templates and magic variables
2825 * @param string $tex The text to transform
2826 * @param array $args Key-value pairs representing template parameters to substitute
2827 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2830 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2831 # Prevent too big inclusions
2832 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2836 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2837 wfProfileIn( $fname );
2839 # This function is called recursively. To keep track of arguments we need a stack:
2840 array_push( $this->mArgStack
, $args );
2842 $braceCallbacks = array();
2844 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2846 if ( $this->mOutputType
!= OT_MSG
) {
2847 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2849 if ( $braceCallbacks ) {
2853 'cb' => $braceCallbacks,
2854 'min' => $argsOnly ?
3 : 2,
2855 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2859 'cb' => array(2=>null),
2864 $text = $this->replace_callback ($text, $callbacks);
2866 array_pop( $this->mArgStack
);
2868 wfProfileOut( $fname );
2873 * Replace magic variables
2876 function variableSubstitution( $matches ) {
2878 $fname = 'Parser::variableSubstitution';
2879 $varname = $wgContLang->lc($matches[1]);
2880 wfProfileIn( $fname );
2882 if ( $this->mOutputType
== OT_WIKI
) {
2883 # Do only magic variables prefixed by SUBST
2884 $mwSubst =& MagicWord
::get( 'subst' );
2885 if (!$mwSubst->matchStartAndRemove( $varname ))
2887 # Note that if we don't substitute the variable below,
2888 # we don't remove the {{subst:}} magic word, in case
2889 # it is a template rather than a magic variable.
2891 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2892 $id = $this->mVariables
[$varname];
2893 # Now check if we did really match, case sensitive or not
2894 $mw =& MagicWord
::get( $id );
2895 if ($mw->match($matches[1])) {
2896 $text = $this->getVariableValue( $id );
2897 $this->mOutput
->mContainsOldMagic
= true;
2899 $text = $matches[0];
2902 $text = $matches[0];
2904 wfProfileOut( $fname );
2909 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2910 static function createAssocArgs( $args ) {
2911 $assocArgs = array();
2913 foreach( $args as $arg ) {
2914 $eqpos = strpos( $arg, '=' );
2915 if ( $eqpos === false ) {
2916 $assocArgs[$index++
] = $arg;
2918 $name = trim( substr( $arg, 0, $eqpos ) );
2919 $value = trim( substr( $arg, $eqpos+
1 ) );
2920 if ( $value === false ) {
2923 if ( $name !== false ) {
2924 $assocArgs[$name] = $value;
2933 * Return the text of a template, after recursively
2934 * replacing any variables or templates within the template.
2936 * @param array $piece The parts of the template
2937 * $piece['text']: matched text
2938 * $piece['title']: the title, i.e. the part before the |
2939 * $piece['parts']: the parameter array
2940 * @return string the text of the template
2943 function braceSubstitution( $piece ) {
2944 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2945 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2946 wfProfileIn( $fname );
2947 wfProfileIn( __METHOD__
.'-setup' );
2950 $found = false; # $text has been filled
2951 $nowiki = false; # wiki markup in $text should be escaped
2952 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2953 $noargs = false; # Don't replace triple-brace arguments in $text
2954 $replaceHeadings = false; # Make the edit section links go to the template not the article
2955 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2956 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2957 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2959 # Title object, where $text came from
2965 # $part1 is the bit before the first |, and must contain only title characters
2966 # $args is a list of arguments, starting from index 0, not including $part1
2968 $titleText = $part1 = $piece['title'];
2969 # If the third subpattern matched anything, it will start with |
2971 if (null == $piece['parts']) {
2972 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2973 if ($replaceWith != $piece['text']) {
2974 $text = $replaceWith;
2981 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2982 wfProfileOut( __METHOD__
.'-setup' );
2985 wfProfileIn( __METHOD__
.'-modifiers' );
2987 $mwSubst =& MagicWord
::get( 'subst' );
2988 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2989 # One of two possibilities is true:
2990 # 1) Found SUBST but not in the PST phase
2991 # 2) Didn't find SUBST and in the PST phase
2992 # In either case, return without further processing
2993 $text = $piece['text'];
3000 # MSG, MSGNW and RAW
3003 $mwMsgnw =& MagicWord
::get( 'msgnw' );
3004 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3007 # Remove obsolete MSG:
3008 $mwMsg =& MagicWord
::get( 'msg' );
3009 $mwMsg->matchStartAndRemove( $part1 );
3013 $mwRaw =& MagicWord
::get( 'raw' );
3014 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3015 $forceRawInterwiki = true;
3018 wfProfileOut( __METHOD__
.'-modifiers' );
3020 //save path level before recursing into functions & templates.
3021 $lastPathLevel = $this->mTemplatePath
;
3025 wfProfileIn( __METHOD__
. '-pfunc' );
3027 $colonPos = strpos( $part1, ':' );
3028 if ( $colonPos !== false ) {
3029 # Case sensitive functions
3030 $function = substr( $part1, 0, $colonPos );
3031 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3032 $function = $this->mFunctionSynonyms
[1][$function];
3034 # Case insensitive functions
3035 $function = strtolower( $function );
3036 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3037 $function = $this->mFunctionSynonyms
[0][$function];
3043 $funcArgs = array_map( 'trim', $args );
3044 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
3045 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
3048 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3052 if ( is_array( $result ) ) {
3053 if ( isset( $result[0] ) ) {
3054 $text = $linestart . $result[0];
3055 unset( $result[0] );
3058 // Extract flags into the local scope
3059 // This allows callers to set flags such as nowiki, noparse, found, etc.
3062 $text = $linestart . $result;
3066 wfProfileOut( __METHOD__
. '-pfunc' );
3069 # Template table test
3071 # Did we encounter this template already? If yes, it is in the cache
3072 # and we need to check for loops.
3073 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3076 # Infinite loop test
3077 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3081 $text = $linestart .
3082 "[[$part1]]<!-- WARNING: template loop detected -->";
3083 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3085 # set $text to cached message.
3086 $text = $linestart . $this->mTemplates
[$piece['title']];
3087 #treat title for cached page the same as others
3090 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3091 if ($subpage !== '') {
3092 $ns = $this->mTitle
->getNamespace();
3094 $title = Title
::newFromText( $part1, $ns );
3095 //used by include size checking
3096 $titleText = $title->getPrefixedText();
3097 //used by edit section links
3098 $replaceHeadings = true;
3103 # Load from database
3105 wfProfileIn( __METHOD__
. '-loadtpl' );
3107 # declaring $subpage directly in the function call
3108 # does not work correctly with references and breaks
3109 # {{/subpage}}-style inclusions
3111 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3112 if ($subpage !== '') {
3113 $ns = $this->mTitle
->getNamespace();
3115 $title = Title
::newFromText( $part1, $ns );
3118 if ( !is_null( $title ) ) {
3119 $titleText = $title->getPrefixedText();
3120 # Check for language variants if the template is not found
3121 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3122 $wgContLang->findVariantLink($part1, $title);
3125 if ( !$title->isExternal() ) {
3126 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3127 $text = SpecialPage
::capturePath( $title );
3128 if ( is_string( $text ) ) {
3133 $this->disableCache();
3135 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3136 $found = false; //access denied
3137 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3139 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3140 if ( $articleContent !== false ) {
3142 $text = $articleContent;
3143 $replaceHeadings = true;
3147 # If the title is valid but undisplayable, make a link to it
3148 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3149 $text = "[[:$titleText]]";
3152 } elseif ( $title->isTrans() ) {
3153 // Interwiki transclusion
3154 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3155 $text = $this->interwikiTransclude( $title, 'render' );
3159 $text = $this->interwikiTransclude( $title, 'raw' );
3160 $replaceHeadings = true;
3165 # Template cache array insertion
3166 # Use the original $piece['title'] not the mangled $part1, so that
3167 # modifiers such as RAW: produce separate cache entries
3170 // A special page; don't store it in the template cache.
3172 $this->mTemplates
[$piece['title']] = $text;
3174 $text = $linestart . $text;
3177 wfProfileOut( __METHOD__
. '-loadtpl' );
3180 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3181 # Error, oversize inclusion
3182 $text = $linestart .
3183 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3188 # Recursive parsing, escaping and link table handling
3189 # Only for HTML output
3190 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3191 $text = wfEscapeWikiText( $text );
3192 } elseif ( !$this->ot
['msg'] && $found ) {
3194 $assocArgs = array();
3196 # Clean up argument array
3197 $assocArgs = self
::createAssocArgs($args);
3198 # Add a new element to the templace recursion path
3199 $this->mTemplatePath
[$part1] = 1;
3203 # If there are any <onlyinclude> tags, only include them
3204 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3205 $replacer = new OnlyIncludeReplacer
;
3206 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3207 array( &$replacer, 'replace' ), $text );
3208 $text = $replacer->output
;
3210 # Remove <noinclude> sections and <includeonly> tags
3211 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3212 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3214 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3215 # Strip <nowiki>, <pre>, etc.
3216 $text = $this->strip( $text, $this->mStripState
);
3217 if ( $this->ot
['html'] ) {
3218 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3219 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3220 $text = Sanitizer
::removeHTMLcomments( $text );
3223 $text = $this->replaceVariables( $text, $assocArgs );
3225 # If the template begins with a table or block-level
3226 # element, it should be treated as beginning a new line.
3227 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3228 $text = "\n" . $text;
3230 } elseif ( !$noargs ) {
3231 # $noparse and !$noargs
3232 # Just replace the arguments, not any double-brace items
3233 # This is used for rendered interwiki transclusion
3234 $text = $this->replaceVariables( $text, $assocArgs, true );
3237 # Prune lower levels off the recursion check path
3238 $this->mTemplatePath
= $lastPathLevel;
3240 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3241 # Error, oversize inclusion
3242 $text = $linestart .
3243 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3249 wfProfileOut( $fname );
3250 return $piece['text'];
3252 wfProfileIn( __METHOD__
. '-placeholders' );
3254 # Replace raw HTML by a placeholder
3255 # Add a blank line preceding, to prevent it from mucking up
3256 # immediately preceding headings
3257 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3259 # replace ==section headers==
3260 # XXX this needs to go away once we have a better parser.
3261 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3262 if( !is_null( $title ) )
3263 $encodedname = base64_encode($title->getPrefixedDBkey());
3265 $encodedname = base64_encode("");
3266 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3267 PREG_SPLIT_DELIM_CAPTURE
);
3269 $nsec = $headingOffset;
3271 for( $i = 0; $i < count($m); $i +
= 2 ) {
3273 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3275 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3280 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3281 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3282 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3288 wfProfileOut( __METHOD__
. '-placeholders' );
3291 # Prune lower levels off the recursion check path
3292 $this->mTemplatePath
= $lastPathLevel;
3295 wfProfileOut( $fname );
3296 return $piece['text'];
3298 wfProfileOut( $fname );
3304 * Fetch the unparsed text of a template and register a reference to it.
3306 function fetchTemplateAndtitle( $title ) {
3307 $text = $skip = false;
3308 $finalTitle = $title;
3309 // Loop to fetch the article, with up to 1 redirect
3310 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3311 # Give extensions a chance to select the revision instead
3312 $id = false; // Assume current
3313 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( &$this, &$title, &$skip, &$id ) );
3317 $this->mOutput
->addTemplate( $title, $title->getArticleID(), null );
3320 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3321 $rev_id = $rev ?
$rev->getId() : 0;
3323 $this->mOutput
->addTemplate( $title, $title->getArticleID(), $rev_id );
3326 $text = $rev->getText();
3327 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3329 $message = $wgLang->lcfirst( $title->getText() );
3330 $text = wfMsgForContentNoTrans( $message );
3331 if( wfEmptyMsg( $message, $text ) ) {
3338 if ( $text === false ) {
3342 $finalTitle = $title;
3343 $title = Title
::newFromRedirect( $text );
3345 return array($text,$finalTitle);
3348 function fetchTemplate( $title ) {
3349 $rv = $this->fetchTemplateAndtitle($title);
3354 * Transclude an interwiki link.
3356 function interwikiTransclude( $title, $action ) {
3357 global $wgEnableScaryTranscluding;
3359 if (!$wgEnableScaryTranscluding)
3360 return wfMsg('scarytranscludedisabled');
3362 $url = $title->getFullUrl( "action=$action" );
3364 if (strlen($url) > 255)
3365 return wfMsg('scarytranscludetoolong');
3366 return $this->fetchScaryTemplateMaybeFromCache($url);
3369 function fetchScaryTemplateMaybeFromCache($url) {
3370 global $wgTranscludeCacheExpiry;
3371 $dbr = wfGetDB(DB_SLAVE
);
3372 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3373 array('tc_url' => $url));
3375 $time = $obj->tc_time
;
3376 $text = $obj->tc_contents
;
3377 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3382 $text = Http
::get($url);
3384 return wfMsg('scarytranscludefailed', $url);
3386 $dbw = wfGetDB(DB_MASTER
);
3387 $dbw->replace('transcache', array('tc_url'), array(
3389 'tc_time' => time(),
3390 'tc_contents' => $text));
3396 * Triple brace replacement -- used for template arguments
3399 function argSubstitution( $matches ) {
3400 $arg = trim( $matches['title'] );
3401 $text = $matches['text'];
3402 $inputArgs = end( $this->mArgStack
);
3404 if ( array_key_exists( $arg, $inputArgs ) ) {
3405 $text = $inputArgs[$arg];
3406 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3407 null != $matches['parts'] && count($matches['parts']) > 0) {
3408 $text = $matches['parts'][0];
3410 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3411 $text = $matches['text'] .
3412 '<!-- WARNING: argument omitted, expansion size too large -->';
3419 * Increment an include size counter
3421 * @param string $type The type of expansion
3422 * @param integer $size The size of the text
3423 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3425 function incrementIncludeSize( $type, $size ) {
3426 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3429 $this->mIncludeSizes
[$type] +
= $size;
3435 * Detect __NOGALLERY__ magic word and set a placeholder
3437 function stripNoGallery( &$text ) {
3438 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3440 $mw = MagicWord
::get( 'nogallery' );
3441 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3445 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3446 * placeholder that will then be replaced by the real TOC in
3447 * ->formatHeadings, this works because at this points real
3448 * comments will have already been discarded by the sanitizer.
3450 * Any additional __TOC__ magic words left over will be discarded
3451 * as there can only be one TOC on the page.
3453 function stripToc( $text ) {
3454 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3456 $mw = MagicWord
::get( 'notoc' );
3457 if( $mw->matchAndRemove( $text ) ) {
3458 $this->mShowToc
= false;
3461 $mw = MagicWord
::get( 'toc' );
3462 if( $mw->match( $text ) ) {
3463 $this->mShowToc
= true;
3464 $this->mForceTocPosition
= true;
3466 // Set a placeholder. At the end we'll fill it in with the TOC.
3467 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3469 // Only keep the first one.
3470 $text = $mw->replace( '', $text );
3476 * This function accomplishes several tasks:
3477 * 1) Auto-number headings if that option is enabled
3478 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3479 * 3) Add a Table of contents on the top for users who have enabled the option
3480 * 4) Auto-anchor headings
3482 * It loops through all headlines, collects the necessary data, then splits up the
3483 * string and re-inserts the newly formatted headlines.
3485 * @param string $text
3486 * @param boolean $isMain
3489 function formatHeadings( $text, $isMain=true ) {
3490 global $wgMaxTocLevel, $wgContLang;
3492 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3493 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3496 $showEditLink = $this->mOptions
->getEditSection();
3499 # Inhibit editsection links if requested in the page
3500 $esw =& MagicWord
::get( 'noeditsection' );
3501 if( $esw->matchAndRemove( $text ) ) {
3505 # Get all headlines for numbering them and adding funky stuff like [edit]
3506 # links - this is for later, but we need the number of headlines right now
3508 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3510 # if there are fewer than 4 headlines in the article, do not show TOC
3511 # unless it's been explicitly enabled.
3512 $enoughToc = $this->mShowToc
&&
3513 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3515 # Allow user to stipulate that a page should have a "new section"
3516 # link added via __NEWSECTIONLINK__
3517 $mw =& MagicWord
::get( 'newsectionlink' );
3518 if( $mw->matchAndRemove( $text ) )
3519 $this->mOutput
->setNewSection( true );
3521 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3522 # override above conditions and always show TOC above first header
3523 $mw =& MagicWord
::get( 'forcetoc' );
3524 if ($mw->matchAndRemove( $text ) ) {
3525 $this->mShowToc
= true;
3529 # We need this to perform operations on the HTML
3530 $sk = $this->mOptions
->getSkin();
3534 $sectionCount = 0; # headlineCount excluding template sections
3537 # Ugh .. the TOC should have neat indentation levels which can be
3538 # passed to the skin functions. These are determined here
3542 $sublevelCount = array();
3543 $levelCount = array();
3550 foreach( $matches[3] as $headline ) {
3552 $templatetitle = '';
3553 $templatesection = 0;
3556 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3558 $templatetitle = base64_decode($mat[1]);
3559 $templatesection = 1 +
(int)base64_decode($mat[2]);
3560 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3564 $prevlevel = $level;
3565 $prevtoclevel = $toclevel;
3567 $level = $matches[1][$headlineCount];
3569 if( $doNumberHeadings ||
$enoughToc ) {
3571 if ( $level > $prevlevel ) {
3572 # Increase TOC level
3574 $sublevelCount[$toclevel] = 0;
3575 if( $toclevel<$wgMaxTocLevel ) {
3576 $prevtoclevel = $toclevel;
3577 $toc .= $sk->tocIndent();
3581 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3582 # Decrease TOC level, find level to jump to
3584 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3585 # Can only go down to level 1
3588 for ($i = $toclevel; $i > 0; $i--) {
3589 if ( $levelCount[$i] == $level ) {
3590 # Found last matching level
3594 elseif ( $levelCount[$i] < $level ) {
3595 # Found first matching level below current level
3601 if( $toclevel<$wgMaxTocLevel ) {
3602 if($prevtoclevel < $wgMaxTocLevel) {
3603 # Unindent only if the previous toc level was shown :p
3604 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3606 $toc .= $sk->tocLineEnd();
3611 # No change in level, end TOC line
3612 if( $toclevel<$wgMaxTocLevel ) {
3613 $toc .= $sk->tocLineEnd();
3617 $levelCount[$toclevel] = $level;
3619 # count number of headlines for each level
3620 @$sublevelCount[$toclevel]++
;
3622 for( $i = 1; $i <= $toclevel; $i++
) {
3623 if( !empty( $sublevelCount[$i] ) ) {
3627 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3633 # The canonized header is a version of the header text safe to use for links
3634 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3635 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3637 # Remove link placeholders by the link text.
3638 # <!--LINK number-->
3640 # link text with suffix
3641 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3642 "\$this->mLinkHolders['texts'][\$1]",
3643 $canonized_headline );
3644 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3645 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3646 $canonized_headline );
3648 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3649 $tocline = preg_replace(
3650 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3654 $tocline = trim( $tocline );
3656 # For the anchor, strip out HTML-y stuff period
3657 $canonized_headline = preg_replace( '/<.*?'.'>/', '', $canonized_headline );
3658 $canonized_headline = trim( $canonized_headline );
3660 # Save headline for section edit hint before it's escaped
3661 $headline_hint = $canonized_headline;
3662 $canonized_headline = Sanitizer
::escapeId( $canonized_headline );
3663 $refers[$headlineCount] = $canonized_headline;
3665 # count how many in assoc. array so we can track dupes in anchors
3666 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3667 $refcount[$headlineCount]=$refers[$canonized_headline];
3669 # Don't number the heading if it is the only one (looks silly)
3670 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3671 # the two are different if the line contains a link
3672 $headline=$numbering . ' ' . $headline;
3675 # Create the anchor for linking from the TOC to the section
3676 $anchor = $canonized_headline;
3677 if($refcount[$headlineCount] > 1 ) {
3678 $anchor .= '_' . $refcount[$headlineCount];
3680 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3681 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3683 # give headline the correct <h#> tag
3684 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3686 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3688 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3692 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3699 # Never ever show TOC if no headers
3700 if( $numVisible < 1 ) {
3705 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3706 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3708 $toc = $sk->tocList( $toc );
3711 # split up and insert constructed headlines
3713 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3716 foreach( $blocks as $block ) {
3717 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3718 # This is the [edit] link that appears for the top block of text when
3719 # section editing is enabled
3721 # Disabled because it broke block formatting
3722 # For example, a bullet point in the top line
3723 # $full .= $sk->editSectionLink(0);
3726 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3727 # Top anchor now in skin
3731 if( !empty( $head[$i] ) ) {
3736 if( $this->mForceTocPosition
) {
3737 return str_replace( '<!--MWTOC-->', $toc, $full );
3744 * Transform wiki markup when saving a page by doing \r\n -> \n
3745 * conversion, substitting signatures, {{subst:}} templates, etc.
3747 * @param string $text the text to transform
3748 * @param Title &$title the Title object for the current article
3749 * @param User &$user the User object describing the current user
3750 * @param ParserOptions $options parsing options
3751 * @param bool $clearState whether to clear the parser state first
3752 * @return string the altered wiki markup
3755 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3756 $this->mOptions
= $options;
3757 $this->mTitle
=& $title;
3758 $this->setOutputType( OT_WIKI
);
3760 if ( $clearState ) {
3761 $this->clearState();
3764 $stripState = new StripState
;
3768 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3769 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3770 $text = $this->pstPass2( $text, $stripState, $user );
3771 $text = $stripState->unstripBoth( $text );
3776 * Pre-save transform helper function
3779 function pstPass2( $text, &$stripState, $user ) {
3780 global $wgContLang, $wgLocaltimezone;
3782 /* Note: This is the timestamp saved as hardcoded wikitext to
3783 * the database, we use $wgContLang here in order to give
3784 * everyone the same signature and use the default one rather
3785 * than the one selected in each user's preferences.
3787 if ( isset( $wgLocaltimezone ) ) {
3788 $oldtz = getenv( 'TZ' );
3789 putenv( 'TZ='.$wgLocaltimezone );
3791 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3792 ' (' . date( 'T' ) . ')';
3793 if ( isset( $wgLocaltimezone ) ) {
3794 putenv( 'TZ='.$oldtz );
3797 # Variable replacement
3798 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3799 $text = $this->replaceVariables( $text );
3801 # Strip out <nowiki> etc. added via replaceVariables
3802 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3805 $sigText = $this->getUserSig( $user );
3806 $text = strtr( $text, array(
3808 '~~~~' => "$sigText $d",
3812 # Context links: [[|name]] and [[name (context)|]]
3814 global $wgLegalTitleChars;
3815 $tc = "[$wgLegalTitleChars]";
3816 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3818 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3819 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3820 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3822 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3823 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3824 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3826 $t = $this->mTitle
->getText();
3828 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3829 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3830 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3831 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3833 # if there's no context, don't bother duplicating the title
3834 $text = preg_replace( $p2, '[[\\1]]', $text );
3837 # Trim trailing whitespace
3838 $text = rtrim( $text );
3844 * Fetch the user's signature text, if any, and normalize to
3845 * validated, ready-to-insert wikitext.
3851 function getUserSig( &$user ) {
3852 global $wgMaxSigChars;
3854 $username = $user->getName();
3855 $nickname = $user->getOption( 'nickname' );
3856 $nickname = $nickname === '' ?
$username : $nickname;
3858 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3859 $nickname = $username;
3860 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3861 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3862 # Sig. might contain markup; validate this
3863 if( $this->validateSig( $nickname ) !== false ) {
3864 # Validated; clean up (if needed) and return it
3865 return $this->cleanSig( $nickname, true );
3867 # Failed to validate; fall back to the default
3868 $nickname = $username;
3869 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3873 // Make sure nickname doesnt get a sig in a sig
3874 $nickname = $this->cleanSigInSig( $nickname );
3876 # If we're still here, make it a link to the user page
3877 $userpage = $user->getUserPage();
3878 if ( $user->isAnon() ) {
3879 $title = SpecialPage
::getTitleFor('Contributions' );
3880 return ( wfMsgForContent( 'signature-ip',
3881 $title->getPrefixedText() . '/' . wfEscapeWikiText( $username ),
3882 wfEscapeWikiText( $nickname ),
3883 $userpage->getTalkPage(), wfMsgForContent('talkpagelinktext') ) );
3885 return ( wfMsgForContent( 'signature', $userpage->getPrefixedText(),
3886 wfEscapeWikiText( $nickname ),
3887 $userpage->getTalkPage(), wfMsgForContent('talkpagelinktext') ) );
3892 * Check that the user's signature contains no bad XML
3894 * @param string $text
3895 * @return mixed An expanded string, or false if invalid.
3897 function validateSig( $text ) {
3898 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3902 * Clean up signature text
3904 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3905 * 2) Substitute all transclusions
3907 * @param string $text
3908 * @param $parsing Whether we're cleaning (preferences save) or parsing
3909 * @return string Signature text
3911 function cleanSig( $text, $parsing = false ) {
3913 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3915 $substWord = MagicWord
::get( 'subst' );
3916 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3917 $substText = '{{' . $substWord->getSynonym( 0 );
3919 $text = preg_replace( $substRegex, $substText, $text );
3920 $text = $this->cleanSigInSig( $text );
3921 $text = $this->replaceVariables( $text );
3923 $this->clearState();
3928 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3929 * @param string $text
3930 * @return string Signature text with /~{3,5}/ removed
3932 function cleanSigInSig( $text ) {
3933 $text = preg_replace( '/~{3,5}/', '', $text );
3938 * Set up some variables which are usually set up in parse()
3939 * so that an external function can call some class members with confidence
3942 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3943 $this->mTitle
=& $title;
3944 $this->mOptions
= $options;
3945 $this->setOutputType( $outputType );
3946 if ( $clearState ) {
3947 $this->clearState();
3952 * Transform a MediaWiki message by replacing magic variables.
3954 * @param string $text the text to transform
3955 * @param ParserOptions $options options
3956 * @return string the text with variables substituted
3959 function transformMsg( $text, $options ) {
3961 static $executing = false;
3963 $fname = "Parser::transformMsg";
3965 # Guard against infinite recursion
3971 wfProfileIn($fname);
3973 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3974 $this->mTitle
= $wgTitle;
3976 $this->mTitle
= Title
::newFromText('msg');
3978 $this->mOptions
= $options;
3979 $this->setOutputType( OT_MSG
);
3980 $this->clearState();
3981 $text = $this->replaceVariables( $text );
3984 wfProfileOut($fname);
3989 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3990 * The callback should have the following form:
3991 * function myParserHook( $text, $params, &$parser ) { ... }
3993 * Transform and return $text. Use $parser for any required context, e.g. use
3994 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3998 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3999 * @param mixed $callback The callback function (and object) to use for the tag
4001 * @return The old value of the mTagHooks array associated with the hook
4003 function setHook( $tag, $callback ) {
4004 $tag = strtolower( $tag );
4005 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4006 $this->mTagHooks
[$tag] = $callback;
4011 function setTransparentTagHook( $tag, $callback ) {
4012 $tag = strtolower( $tag );
4013 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4014 $this->mTransparentTagHooks
[$tag] = $callback;
4020 * Create a function, e.g. {{sum:1|2|3}}
4021 * The callback function should have the form:
4022 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4024 * The callback may either return the text result of the function, or an array with the text
4025 * in element 0, and a number of flags in the other elements. The names of the flags are
4026 * specified in the keys. Valid flags are:
4027 * found The text returned is valid, stop processing the template. This
4029 * nowiki Wiki markup in the return value should be escaped
4030 * noparse Unsafe HTML tags should not be stripped, etc.
4031 * noargs Don't replace triple-brace arguments in the return value
4032 * isHTML The returned text is HTML, armour it against wikitext transformation
4036 * @param string $id The magic word ID
4037 * @param mixed $callback The callback function (and object) to use
4038 * @param integer $flags a combination of the following flags:
4039 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4041 * @return The old callback function for this name, if any
4043 function setFunctionHook( $id, $callback, $flags = 0 ) {
4044 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4045 $this->mFunctionHooks
[$id] = $callback;
4047 # Add to function cache
4048 $mw = MagicWord
::get( $id );
4050 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4052 $synonyms = $mw->getSynonyms();
4053 $sensitive = intval( $mw->isCaseSensitive() );
4055 foreach ( $synonyms as $syn ) {
4057 if ( !$sensitive ) {
4058 $syn = strtolower( $syn );
4061 if ( !( $flags & SFH_NO_HASH
) ) {
4064 # Remove trailing colon
4065 if ( substr( $syn, -1, 1 ) == ':' ) {
4066 $syn = substr( $syn, 0, -1 );
4068 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4074 * Get all registered function hook identifiers
4078 function getFunctionHooks() {
4079 return array_keys( $this->mFunctionHooks
);
4083 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4084 * Placeholders created in Skin::makeLinkObj()
4085 * Returns an array of links found, indexed by PDBK:
4089 * $options is a bit field, RLH_FOR_UPDATE to select for update
4091 function replaceLinkHolders( &$text, $options = 0 ) {
4095 $fname = 'Parser::replaceLinkHolders';
4096 wfProfileIn( $fname );
4100 $sk = $this->mOptions
->getSkin();
4101 $linkCache =& LinkCache
::singleton();
4103 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4104 wfProfileIn( $fname.'-check' );
4105 $dbr = wfGetDB( DB_SLAVE
);
4106 $page = $dbr->tableName( 'page' );
4107 $threshold = $wgUser->getOption('stubthreshold');
4110 asort( $this->mLinkHolders
['namespaces'] );
4115 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4117 $title = $this->mLinkHolders
['titles'][$key];
4119 # Skip invalid entries.
4120 # Result will be ugly, but prevents crash.
4121 if ( is_null( $title ) ) {
4124 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4126 # Check if it's a static known link, e.g. interwiki
4127 if ( $title->isAlwaysKnown() ) {
4128 $colours[$pdbk] = 1;
4129 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4130 $colours[$pdbk] = 1;
4131 $this->mOutput
->addLink( $title, $id );
4132 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4133 $colours[$pdbk] = 0;
4134 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4135 $colours[$pdbk] = 0;
4137 # Not in the link cache, add it to the query
4138 if ( !isset( $current ) ) {
4140 $query = "SELECT page_id, page_namespace, page_title";
4141 if ( $threshold > 0 ) {
4142 $query .= ', page_len, page_is_redirect';
4144 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4145 } elseif ( $current != $ns ) {
4147 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4152 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4157 if ( $options & RLH_FOR_UPDATE
) {
4158 $query .= ' FOR UPDATE';
4161 $res = $dbr->query( $query, $fname );
4163 # Fetch data and form into an associative array
4164 # non-existent = broken
4167 while ( $s = $dbr->fetchObject($res) ) {
4168 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4169 $pdbk = $title->getPrefixedDBkey();
4170 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4171 $this->mOutput
->addLink( $title, $s->page_id
);
4173 $colours[$pdbk] = ( $threshold == 0 ||
(
4174 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4175 $s->page_is_redirect ||
4176 !Namespace::isContent( $s->page_namespace
) )
4180 wfProfileOut( $fname.'-check' );
4182 # Do a second query for different language variants of links and categories
4183 if($wgContLang->hasVariants()){
4184 $linkBatch = new LinkBatch();
4185 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4186 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4187 $varCategories = array(); // category replacements oldDBkey => newDBkey
4189 $categories = $this->mOutput
->getCategoryLinks();
4191 // Add variants of links to link batch
4192 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4193 $title = $this->mLinkHolders
['titles'][$key];
4194 if ( is_null( $title ) )
4197 $pdbk = $title->getPrefixedDBkey();
4198 $titleText = $title->getText();
4200 // generate all variants of the link title text
4201 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4203 // if link was not found (in first query), add all variants to query
4204 if ( !isset($colours[$pdbk]) ){
4205 foreach($allTextVariants as $textVariant){
4206 if($textVariant != $titleText){
4207 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4208 if(is_null($variantTitle)) continue;
4209 $linkBatch->addObj( $variantTitle );
4210 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4216 // process categories, check if a category exists in some variant
4217 foreach( $categories as $category ){
4218 $variants = $wgContLang->convertLinkToAllVariants($category);
4219 foreach($variants as $variant){
4220 if($variant != $category){
4221 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4222 if(is_null($variantTitle)) continue;
4223 $linkBatch->addObj( $variantTitle );
4224 $categoryMap[$variant] = $category;
4230 if(!$linkBatch->isEmpty()){
4232 $titleClause = $linkBatch->constructSet('page', $dbr);
4234 $variantQuery = "SELECT page_id, page_namespace, page_title";
4235 if ( $threshold > 0 ) {
4236 $variantQuery .= ', page_len, page_is_redirect';
4239 $variantQuery .= " FROM $page WHERE $titleClause";
4240 if ( $options & RLH_FOR_UPDATE
) {
4241 $variantQuery .= ' FOR UPDATE';
4244 $varRes = $dbr->query( $variantQuery, $fname );
4246 // for each found variants, figure out link holders and replace
4247 while ( $s = $dbr->fetchObject($varRes) ) {
4249 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4250 $varPdbk = $variantTitle->getPrefixedDBkey();
4251 $vardbk = $variantTitle->getDBkey();
4253 $holderKeys = array();
4254 if(isset($variantMap[$varPdbk])){
4255 $holderKeys = $variantMap[$varPdbk];
4256 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4257 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4260 // loop over link holders
4261 foreach($holderKeys as $key){
4262 $title = $this->mLinkHolders
['titles'][$key];
4263 if ( is_null( $title ) ) continue;
4265 $pdbk = $title->getPrefixedDBkey();
4267 if(!isset($colours[$pdbk])){
4268 // found link in some of the variants, replace the link holder data
4269 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4270 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4272 // set pdbk and colour
4273 $pdbks[$key] = $varPdbk;
4274 if ( $threshold > 0 ) {
4275 $size = $s->page_len
;
4276 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4277 $colours[$varPdbk] = 1;
4279 $colours[$varPdbk] = 2;
4283 $colours[$varPdbk] = 1;
4288 // check if the object is a variant of a category
4289 if(isset($categoryMap[$vardbk])){
4290 $oldkey = $categoryMap[$vardbk];
4291 if($oldkey != $vardbk)
4292 $varCategories[$oldkey]=$vardbk;
4296 // rebuild the categories in original order (if there are replacements)
4297 if(count($varCategories)>0){
4299 $originalCats = $this->mOutput
->getCategories();
4300 foreach($originalCats as $cat => $sortkey){
4301 // make the replacement
4302 if( array_key_exists($cat,$varCategories) )
4303 $newCats[$varCategories[$cat]] = $sortkey;
4304 else $newCats[$cat] = $sortkey;
4306 $this->mOutput
->setCategoryLinks($newCats);
4311 # Construct search and replace arrays
4312 wfProfileIn( $fname.'-construct' );
4313 $replacePairs = array();
4314 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4315 $pdbk = $pdbks[$key];
4316 $searchkey = "<!--LINK $key-->";
4317 $title = $this->mLinkHolders
['titles'][$key];
4318 if ( empty( $colours[$pdbk] ) ) {
4319 $linkCache->addBadLinkObj( $title );
4320 $colours[$pdbk] = 0;
4321 $this->mOutput
->addLink( $title, 0 );
4322 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4323 $this->mLinkHolders
['texts'][$key],
4324 $this->mLinkHolders
['queries'][$key] );
4325 } elseif ( $colours[$pdbk] == 1 ) {
4326 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4327 $this->mLinkHolders
['texts'][$key],
4328 $this->mLinkHolders
['queries'][$key] );
4329 } elseif ( $colours[$pdbk] == 2 ) {
4330 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4331 $this->mLinkHolders
['texts'][$key],
4332 $this->mLinkHolders
['queries'][$key] );
4335 $replacer = new HashtableReplacer( $replacePairs, 1 );
4336 wfProfileOut( $fname.'-construct' );
4339 wfProfileIn( $fname.'-replace' );
4340 $text = preg_replace_callback(
4341 '/(<!--LINK .*?-->)/',
4345 wfProfileOut( $fname.'-replace' );
4348 # Now process interwiki link holders
4349 # This is quite a bit simpler than internal links
4350 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4351 wfProfileIn( $fname.'-interwiki' );
4352 # Make interwiki link HTML
4353 $replacePairs = array();
4354 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4355 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4356 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4358 $replacer = new HashtableReplacer( $replacePairs, 1 );
4360 $text = preg_replace_callback(
4361 '/<!--IWLINK (.*?)-->/',
4364 wfProfileOut( $fname.'-interwiki' );
4367 wfProfileOut( $fname );
4372 * Replace <!--LINK--> link placeholders with plain text of links
4373 * (not HTML-formatted).
4374 * @param string $text
4377 function replaceLinkHoldersText( $text ) {
4378 $fname = 'Parser::replaceLinkHoldersText';
4379 wfProfileIn( $fname );
4381 $text = preg_replace_callback(
4382 '/<!--(LINK|IWLINK) (.*?)-->/',
4383 array( &$this, 'replaceLinkHoldersTextCallback' ),
4386 wfProfileOut( $fname );
4391 * @param array $matches
4395 function replaceLinkHoldersTextCallback( $matches ) {
4396 $type = $matches[1];
4398 if( $type == 'LINK' ) {
4399 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4400 return $this->mLinkHolders
['texts'][$key];
4402 } elseif( $type == 'IWLINK' ) {
4403 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4404 return $this->mInterwikiLinkHolders
['texts'][$key];
4411 * Tag hook handler for 'pre'.
4413 function renderPreTag( $text, $attribs ) {
4414 // Backwards-compatibility hack
4415 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4417 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4418 return wfOpenElement( 'pre', $attribs ) .
4419 Xml
::escapeTagsOnly( $content ) .
4424 * Renders an image gallery from a text with one line per image.
4425 * text labels may be given by using |-style alternative text. E.g.
4426 * Image:one.jpg|The number "1"
4427 * Image:tree.jpg|A tree
4428 * given as text will return the HTML of a gallery with two images,
4429 * labeled 'The number "1"' and
4432 function renderImageGallery( $text, $params ) {
4433 $ig = new ImageGallery();
4434 $ig->setContextTitle( $this->mTitle
);
4435 $ig->setShowBytes( false );
4436 $ig->setShowFilename( false );
4437 $ig->setParser( $this );
4438 $ig->setHideBadImages();
4439 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4440 $ig->useSkin( $this->mOptions
->getSkin() );
4441 $ig->mRevisionId
= $this->mRevisionId
;
4443 if( isset( $params['caption'] ) ) {
4444 $caption = $params['caption'];
4445 $caption = htmlspecialchars( $caption );
4446 $caption = $this->replaceInternalLinks( $caption );
4447 $ig->setCaptionHtml( $caption );
4449 if( isset( $params['perrow'] ) ) {
4450 $ig->setPerRow( $params['perrow'] );
4452 if( isset( $params['widths'] ) ) {
4453 $ig->setWidths( $params['widths'] );
4455 if( isset( $params['heights'] ) ) {
4456 $ig->setHeights( $params['heights'] );
4459 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4461 $lines = explode( "\n", $text );
4462 foreach ( $lines as $line ) {
4463 # match lines like these:
4464 # Image:someimage.jpg|This is some image
4466 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4468 if ( count( $matches ) == 0 ) {
4471 $tp = Title
::newFromText( $matches[1] );
4473 if( is_null( $nt ) ) {
4474 # Bogus title. Ignore these so we don't bomb out later.
4477 if ( isset( $matches[3] ) ) {
4478 $label = $matches[3];
4483 $pout = $this->parse( $label,
4486 false, // Strip whitespace...?
4487 false // Don't clear state!
4489 $html = $pout->getText();
4491 $ig->add( $nt, $html );
4493 # Only add real images (bug #5586)
4494 if ( $nt->getNamespace() == NS_IMAGE
) {
4495 $this->mOutput
->addImage( $nt->getDBkey() );
4498 return $ig->toHTML();
4501 function getImageParams( $handler ) {
4503 $handlerClass = get_class( $handler );
4507 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4508 // Initialise static lists
4509 static $internalParamNames = array(
4510 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4511 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4512 'bottom', 'text-bottom' ),
4513 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4514 'upright', 'border' ),
4516 static $internalParamMap;
4517 if ( !$internalParamMap ) {
4518 $internalParamMap = array();
4519 foreach ( $internalParamNames as $type => $names ) {
4520 foreach ( $names as $name ) {
4521 $magicName = str_replace( '-', '_', "img_$name" );
4522 $internalParamMap[$magicName] = array( $type, $name );
4527 // Add handler params
4528 $paramMap = $internalParamMap;
4530 $handlerParamMap = $handler->getParamMap();
4531 foreach ( $handlerParamMap as $magic => $paramName ) {
4532 $paramMap[$magic] = array( 'handler', $paramName );
4535 $this->mImageParams
[$handlerClass] = $paramMap;
4536 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4538 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4542 * Parse image options text and use it to make an image
4544 function makeImage( $title, $options ) {
4545 # @TODO: let the MediaHandler specify its transform parameters
4547 # Check if the options text is of the form "options|alt text"
4549 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4550 # * left no resizing, just left align. label is used for alt= only
4551 # * right same, but right aligned
4552 # * none same, but not aligned
4553 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4554 # * center center the image
4555 # * framed Keep original image size, no magnify-button.
4556 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4557 # * upright reduce width for upright images, rounded to full __0 px
4558 # * border draw a 1px border around the image
4559 # vertical-align values (no % or length right now):
4569 $parts = array_map( 'trim', explode( '|', $options) );
4570 $sk = $this->mOptions
->getSkin();
4572 # Give extensions a chance to select the file revision for us
4573 $skip = $time = false;
4574 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4577 return $sk->makeLinkObj( $title );
4581 $file = wfFindFile( $title, $time );
4582 $handler = $file ?
$file->getHandler() : false;
4584 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4586 # Process the input parameters
4588 $params = array( 'frame' => array(), 'handler' => array(),
4589 'horizAlign' => array(), 'vertAlign' => array() );
4590 foreach( $parts as $part ) {
4591 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4592 if ( isset( $paramMap[$magicName] ) ) {
4593 list( $type, $paramName ) = $paramMap[$magicName];
4594 $params[$type][$paramName] = $value;
4596 // Special case; width and height come in one variable together
4597 if( $type == 'handler' && $paramName == 'width' ) {
4599 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4600 $params[$type]['width'] = intval( $m[1] );
4601 $params[$type]['height'] = intval( $m[2] );
4603 $params[$type]['width'] = intval( $value );
4611 # Process alignment parameters
4612 if ( $params['horizAlign'] ) {
4613 $params['frame']['align'] = key( $params['horizAlign'] );
4615 if ( $params['vertAlign'] ) {
4616 $params['frame']['valign'] = key( $params['vertAlign'] );
4619 # Validate the handler parameters
4621 foreach ( $params['handler'] as $name => $value ) {
4622 if ( !$handler->validateParam( $name, $value ) ) {
4623 unset( $params['handler'][$name] );
4628 # Strip bad stuff out of the alt text
4629 $alt = $this->replaceLinkHoldersText( $caption );
4631 # make sure there are no placeholders in thumbnail attributes
4632 # that are later expanded to html- so expand them now and
4634 $alt = $this->mStripState
->unstripBoth( $alt );
4635 $alt = Sanitizer
::stripAllTags( $alt );
4637 $params['frame']['alt'] = $alt;
4638 $params['frame']['caption'] = $caption;
4640 # Linker does the rest
4641 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4643 # Give the handler a chance to modify the parser object
4645 $handler->parserTransformHook( $this, $file );
4652 * Set a flag in the output object indicating that the content is dynamic and
4653 * shouldn't be cached.
4655 function disableCache() {
4656 wfDebug( "Parser output marked as uncacheable.\n" );
4657 $this->mOutput
->mCacheTime
= -1;
4661 * Callback from the Sanitizer for expanding items found in HTML attribute
4662 * values, so they can be safely tested and escaped.
4663 * @param string $text
4664 * @param array $args
4668 function attributeStripCallback( &$text, $args ) {
4669 $text = $this->replaceVariables( $text, $args );
4670 $text = $this->mStripState
->unstripBoth( $text );
4679 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4680 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4681 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4687 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4692 * Break wikitext input into sections, and either pull or replace
4693 * some particular section's text.
4695 * External callers should use the getSection and replaceSection methods.
4697 * @param $text Page wikitext
4698 * @param $section Numbered section. 0 pulls the text before the first
4699 * heading; other numbers will pull the given section
4700 * along with its lower-level subsections.
4701 * @param $mode One of "get" or "replace"
4702 * @param $newtext Replacement text for section data.
4703 * @return string for "get", the extracted section text.
4704 * for "replace", the whole page with the section replaced.
4706 private function extractSections( $text, $section, $mode, $newtext='' ) {
4707 # I.... _hope_ this is right.
4708 # Otherwise, sometimes we don't have things initialized properly.
4709 $this->clearState();
4711 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4712 # comments to be stripped as well)
4713 $stripState = new StripState
;
4715 $oldOutputType = $this->mOutputType
;
4716 $oldOptions = $this->mOptions
;
4717 $this->mOptions
= new ParserOptions();
4718 $this->setOutputType( OT_WIKI
);
4720 $striptext = $this->strip( $text, $stripState, true );
4722 $this->setOutputType( $oldOutputType );
4723 $this->mOptions
= $oldOptions;
4725 # now that we can be sure that no pseudo-sections are in the source,
4726 # split it up by section
4727 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4728 $comment = "(?:$uniq-!--.*?QINU\x07)";
4733 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4734 (=+) # Should this be limited to 6?
4735 .+? # Section title...
4736 \\2 # Ending = count must match start
4737 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4746 PREG_SPLIT_DELIM_CAPTURE
);
4748 if( $mode == "get" ) {
4749 if( $section == 0 ) {
4750 // "Section 0" returns the content before any other section.
4753 //track missing section, will replace if found.
4756 } elseif( $mode == "replace" ) {
4757 if( $section == 0 ) {
4758 $rv = $newtext . "\n\n";
4767 for( $index = 1; $index < count( $secs ); ) {
4768 $headerLine = $secs[$index++
];
4769 if( $secs[$index] ) {
4771 $headerLevel = strlen( $secs[$index++
] );
4775 $headerLevel = intval( $secs[$index++
] );
4777 $content = $secs[$index++
];
4780 if( $mode == "get" ) {
4781 if( $count == $section ) {
4782 $rv = $headerLine . $content;
4783 $sectionLevel = $headerLevel;
4784 } elseif( $count > $section ) {
4785 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4786 $rv .= $headerLine . $content;
4788 // Broke out to a higher-level section
4792 } elseif( $mode == "replace" ) {
4793 if( $count < $section ) {
4794 $rv .= $headerLine . $content;
4795 } elseif( $count == $section ) {
4796 $rv .= $newtext . "\n\n";
4797 $sectionLevel = $headerLevel;
4798 } elseif( $count > $section ) {
4799 if( $headerLevel <= $sectionLevel ) {
4800 // Passed the section's sub-parts.
4804 $rv .= $headerLine . $content;
4810 # reinsert stripped tags
4811 $rv = trim( $stripState->unstripBoth( $rv ) );
4817 * This function returns the text of a section, specified by a number ($section).
4818 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4819 * the first section before any such heading (section 0).
4821 * If a section contains subsections, these are also returned.
4823 * @param $text String: text to look in
4824 * @param $section Integer: section number
4825 * @param $deftext: default to return if section is not found
4826 * @return string text of the requested section
4828 public function getSection( $text, $section, $deftext='' ) {
4829 return $this->extractSections( $text, $section, "get", $deftext );
4832 public function replaceSection( $oldtext, $section, $text ) {
4833 return $this->extractSections( $oldtext, $section, "replace", $text );
4837 * Get the timestamp associated with the current revision, adjusted for
4838 * the default server-local timestamp
4840 function getRevisionTimestamp() {
4841 if ( is_null( $this->mRevisionTimestamp
) ) {
4842 wfProfileIn( __METHOD__
);
4844 $dbr = wfGetDB( DB_SLAVE
);
4845 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4846 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4848 // Normalize timestamp to internal MW format for timezone processing.
4849 // This has the added side-effect of replacing a null value with
4850 // the current time, which gives us more sensible behavior for
4852 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4854 // The cryptic '' timezone parameter tells to use the site-default
4855 // timezone offset instead of the user settings.
4857 // Since this value will be saved into the parser cache, served
4858 // to other users, and potentially even used inside links and such,
4859 // it needs to be consistent for all visitors.
4860 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4862 wfProfileOut( __METHOD__
);
4864 return $this->mRevisionTimestamp
;
4868 * Mutator for $mDefaultSort
4870 * @param $sort New value
4872 public function setDefaultSort( $sort ) {
4873 $this->mDefaultSort
= $sort;
4877 * Accessor for $mDefaultSort
4878 * Will use the title/prefixed title if none is set
4882 public function getDefaultSort() {
4883 if( $this->mDefaultSort
!== false ) {
4884 return $this->mDefaultSort
;
4886 return $this->mTitle
->getNamespace() == NS_CATEGORY
4887 ?
$this->mTitle
->getText()
4888 : $this->mTitle
->getPrefixedText();
4893 * Try to guess the section anchor name based on a wikitext fragment
4894 * presumably extracted from a heading, for example "Header" from
4897 public function guessSectionNameFromWikiText( $text ) {
4898 # Strip out wikitext links(they break the anchor)
4899 $text = $this->stripSectionName( $text );
4900 $headline = Sanitizer
::decodeCharReferences( $text );
4902 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4903 $headline = trim( $headline );
4904 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4905 $replacearray = array(
4910 array_keys( $replacearray ),
4911 array_values( $replacearray ),
4916 * Strips a text string of wikitext for use in a section anchor
4918 * Accepts a text string and then removes all wikitext from the
4919 * string and leaves only the resultant text (i.e. the result of
4920 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4921 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4922 * to create valid section anchors by mimicing the output of the
4923 * parser when headings are parsed.
4925 * @param $text string Text string to be stripped of wikitext
4926 * for use in a Section anchor
4927 * @return Filtered text string
4929 public function stripSectionName( $text ) {
4930 # Strip internal link markup
4931 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4932 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4934 # Strip external link markup (FIXME: Not Tolerant to blank link text
4935 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4936 # on how many empty links there are on the page - need to figure that out.
4937 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4939 # Parse wikitext quotes (italics & bold)
4940 $text = $this->doQuotes($text);
4943 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4949 * @todo document, briefly.
4950 * @addtogroup Parser
4952 class OnlyIncludeReplacer
{
4955 function replace( $matches ) {
4956 if ( substr( $matches[1], -1 ) == "\n" ) {
4957 $this->output
.= substr( $matches[1], 0, -1 );
4959 $this->output
.= $matches[1];
4965 * @todo document, briefly.
4966 * @addtogroup Parser
4969 var $general, $nowiki;
4971 function __construct() {
4972 $this->general
= new ReplacementArray
;
4973 $this->nowiki
= new ReplacementArray
;
4976 function unstripGeneral( $text ) {
4977 wfProfileIn( __METHOD__
);
4978 $text = $this->general
->replace( $text );
4979 wfProfileOut( __METHOD__
);
4983 function unstripNoWiki( $text ) {
4984 wfProfileIn( __METHOD__
);
4985 $text = $this->nowiki
->replace( $text );
4986 wfProfileOut( __METHOD__
);
4990 function unstripBoth( $text ) {
4991 wfProfileIn( __METHOD__
);
4992 $text = $this->general
->replace( $text );
4993 $text = $this->nowiki
->replace( $text );
4994 wfProfileOut( __METHOD__
);