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;
102 # Cleared with clearState():
103 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
104 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
106 var $mIncludeSizes, $mDefaultSort;
107 var $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
113 # These are variables reset at least once per parse regardless of $clearState
114 var $mOptions, // ParserOptions object
115 $mTitle, // Title context, used for self-link rendering and similar things
116 $mOutputType, // Output type, one of the OT_xxx constants
117 $ot, // Shortcut alias, see setOutputType()
118 $mRevisionId, // ID to display in {{REVISIONID}} tags
119 $mRevisionTimestamp, // The timestamp of the specified revision ID
120 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
130 $this->mTagHooks
= array();
131 $this->mTransparentTagHooks
= array();
132 $this->mFunctionHooks
= array();
133 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
134 $this->mFirstCall
= true;
138 * Do various kinds of initialisation on the first call of the parser
140 function firstCallInit() {
141 if ( !$this->mFirstCall
) {
145 wfProfileIn( __METHOD__
);
146 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
148 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
150 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
172 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
173 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
174 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
175 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
177 if ( $wgAllowDisplayTitle ) {
178 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
180 if ( $wgAllowSlowParserFunctions ) {
181 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
184 $this->initialiseVariables();
185 $this->mFirstCall
= false;
186 wfProfileOut( __METHOD__
);
194 function clearState() {
195 wfProfileIn( __METHOD__
);
196 if ( $this->mFirstCall
) {
197 $this->firstCallInit();
199 $this->mOutput
= new ParserOutput
;
200 $this->mAutonumber
= 0;
201 $this->mLastSection
= '';
202 $this->mDTopen
= false;
203 $this->mIncludeCount
= array();
204 $this->mStripState
= new StripState
;
205 $this->mArgStack
= array();
206 $this->mInPre
= false;
207 $this->mInterwikiLinkHolders
= array(
211 $this->mLinkHolders
= array(
212 'namespaces' => array(),
214 'queries' => array(),
218 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
221 * Prefix for temporary replacement strings for the multipass parser.
222 * \x07 should never appear in input as it's disallowed in XML.
223 * Using it at the front also gives us a little extra robustness
224 * since it shouldn't match when butted up against identifier-like
227 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
229 # Clear these on every parse, bug 4549
230 $this->mTemplates
= array();
231 $this->mTemplatePath
= array();
233 $this->mShowToc
= true;
234 $this->mForceTocPosition
= false;
235 $this->mIncludeSizes
= array(
240 $this->mDefaultSort
= false;
242 wfRunHooks( 'ParserClearState', array( &$this ) );
243 wfProfileOut( __METHOD__
);
246 function setOutputType( $ot ) {
247 $this->mOutputType
= $ot;
250 'html' => $ot == OT_HTML
,
251 'wiki' => $ot == OT_WIKI
,
252 'msg' => $ot == OT_MSG
,
253 'pre' => $ot == OT_PREPROCESS
,
258 * Accessor for mUniqPrefix.
262 function uniqPrefix() {
263 return $this->mUniqPrefix
;
267 * Convert wikitext to HTML
268 * Do not call this function recursively.
270 * @param string $text Text we want to parse
271 * @param Title &$title A title object
272 * @param array $options
273 * @param boolean $linestart
274 * @param boolean $clearState
275 * @param int $revid number to pass in {{REVISIONID}}
276 * @return ParserOutput a ParserOutput
278 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
280 * First pass--just handle <nowiki> sections, pass the rest off
281 * to internalParse() which does all the real work.
284 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
285 $fname = 'Parser::parse-' . wfGetCaller();
286 wfProfileIn( __METHOD__
);
287 wfProfileIn( $fname );
293 $this->mOptions
= $options;
294 $this->mTitle
=& $title;
295 $oldRevisionId = $this->mRevisionId
;
296 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
297 if( $revid !== null ) {
298 $this->mRevisionId
= $revid;
299 $this->mRevisionTimestamp
= null;
301 $this->setOutputType( OT_HTML
);
302 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
303 $text = $this->strip( $text, $this->mStripState
);
304 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
305 $text = $this->internalParse( $text );
306 $text = $this->mStripState
->unstripGeneral( $text );
308 # Clean up special characters, only run once, next-to-last before doBlockLevels
310 # french spaces, last one Guillemet-left
311 # only if there is something before the space
312 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
313 # french spaces, Guillemet-right
314 '/(\\302\\253) /' => '\\1 ',
316 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
319 $text = $this->doBlockLevels( $text, $linestart );
321 $this->replaceLinkHolders( $text );
323 # the position of the parserConvert() call should not be changed. it
324 # assumes that the links are all replaced and the only thing left
325 # is the <nowiki> mark.
326 # Side-effects: this calls $this->mOutput->setTitleText()
327 $text = $wgContLang->parserConvert( $text, $this );
329 $text = $this->mStripState
->unstripNoWiki( $text );
331 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
333 //!JF Move to its own function
335 $uniq_prefix = $this->mUniqPrefix
;
337 $elements = array_keys( $this->mTransparentTagHooks
);
338 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
340 foreach( $matches as $marker => $data ) {
341 list( $element, $content, $params, $tag ) = $data;
342 $tagName = strtolower( $element );
343 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
344 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
345 array( $content, $params, $this ) );
349 $this->mStripState
->general
->setPair( $marker, $output );
351 $text = $this->mStripState
->unstripGeneral( $text );
353 $text = Sanitizer
::normalizeCharReferences( $text );
355 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
356 $text = Parser
::tidy($text);
358 # attempt to sanitize at least some nesting problems
359 # (bug #2702 and quite a few others)
361 # ''Something [http://www.cool.com cool''] -->
362 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
363 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
364 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
365 # fix up an anchor inside another anchor, only
366 # at least for a single single nested link (bug 3695)
367 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
368 '\\1\\2</a>\\3</a>\\1\\4</a>',
369 # fix div inside inline elements- doBlockLevels won't wrap a line which
370 # contains a div, so fix it up here; replace
371 # div with escaped text
372 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
373 '\\1\\3<div\\5>\\6</div>\\8\\9',
374 # remove empty italic or bold tag pairs, some
375 # introduced by rules above
376 '/<([bi])><\/\\1>/' => '',
379 $text = preg_replace(
380 array_keys( $tidyregs ),
381 array_values( $tidyregs ),
385 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
387 # Information on include size limits, for the benefit of users who try to skirt them
388 if ( max( $this->mIncludeSizes
) > 1000 ) {
389 $max = $this->mOptions
->getMaxIncludeSize();
391 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
392 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
393 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
394 "Maximum: $max bytes\n" .
397 $this->mOutput
->setText( $text );
398 $this->mRevisionId
= $oldRevisionId;
399 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
400 wfProfileOut( $fname );
401 wfProfileOut( __METHOD__
);
403 return $this->mOutput
;
407 * Recursive parser entry point that can be called from an extension tag
410 function recursiveTagParse( $text ) {
411 wfProfileIn( __METHOD__
);
412 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
413 $text = $this->strip( $text, $this->mStripState
);
414 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
415 $text = $this->internalParse( $text );
416 wfProfileOut( __METHOD__
);
421 * Expand templates and variables in the text, producing valid, static wikitext.
422 * Also removes comments.
424 function preprocess( $text, $title, $options, $revid = null ) {
425 wfProfileIn( __METHOD__
);
427 $this->setOutputType( OT_PREPROCESS
);
428 $this->mOptions
= $options;
429 $this->mTitle
= $title;
430 if( $revid !== null ) {
431 $this->mRevisionId
= $revid;
433 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->strip( $text, $this->mStripState
);
435 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
436 if ( $this->mOptions
->getRemoveComments() ) {
437 $text = Sanitizer
::removeHTMLcomments( $text );
439 $text = $this->replaceVariables( $text );
440 $text = $this->mStripState
->unstripBoth( $text );
441 wfProfileOut( __METHOD__
);
446 * Get a random string
451 function getRandomString() {
452 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
455 function &getTitle() { return $this->mTitle
; }
456 function getOptions() { return $this->mOptions
; }
458 function getFunctionLang() {
459 global $wgLang, $wgContLang;
460 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
464 * Replaces all occurrences of HTML-style comments and the given tags
465 * in the text with a random marker and returns teh next text. The output
466 * parameter $matches will be an associative array filled with data in
468 * 'UNIQ-xxxxx' => array(
471 * array( 'param' => 'x' ),
472 * '<element param="x">tag content</element>' ) )
474 * @param $elements list of element names. Comments are always extracted.
475 * @param $text Source text string.
476 * @param $uniq_prefix
481 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
486 $taglist = implode( '|', $elements );
487 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
489 while ( '' != $text ) {
490 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
492 if( count( $p ) < 5 ) {
495 if( count( $p ) > 5 ) {
509 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . "-QINU\x07";
510 $stripped .= $marker;
512 if ( $close === '/>' ) {
513 // Empty element tag, <tag />
518 if( $element == '!--' ) {
521 $end = "/(<\\/$element\\s*>)/i";
523 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
525 if( count( $q ) < 3 ) {
526 # No end tag -- let it run out to the end of the text.
535 $matches[$marker] = array( $element,
537 Sanitizer
::decodeTagAttributes( $attributes ),
538 "<$element$attributes$close$content$tail" );
544 * Strips and renders nowiki, pre, math, hiero
545 * If $render is set, performs necessary rendering operations on plugins
546 * Returns the text, and fills an array with data needed in unstrip()
548 * @param StripState $state
550 * @param bool $stripcomments when set, HTML comments <!-- like this -->
551 * will be stripped in addition to other tags. This is important
552 * for section editing, where these comments cause confusion when
553 * counting the sections in the wikisource
555 * @param array dontstrip contains tags which should not be stripped;
556 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
560 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
562 wfProfileIn( __METHOD__
);
563 $render = ($this->mOutputType
== OT_HTML
);
565 $uniq_prefix = $this->mUniqPrefix
;
566 $commentState = new ReplacementArray
;
567 $nowikiItems = array();
568 $generalItems = array();
570 $elements = array_merge(
571 array( 'nowiki', 'gallery' ),
572 array_keys( $this->mTagHooks
) );
575 $elements[] = 'html';
577 if( $this->mOptions
->getUseTeX() ) {
578 $elements[] = 'math';
581 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
582 foreach ( $elements AS $k => $v ) {
583 if ( !in_array ( $v , $dontstrip ) ) continue;
584 unset ( $elements[$k] );
588 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
590 foreach( $matches as $marker => $data ) {
591 list( $element, $content, $params, $tag ) = $data;
593 $tagName = strtolower( $element );
594 wfProfileIn( __METHOD__
."-render-$tagName" );
598 if( substr( $tag, -3 ) == '-->' ) {
601 // Unclosed comment in input.
602 // Close it so later stripping can remove it
611 // Shouldn't happen otherwise. :)
613 $output = Xml
::escapeTagsOnly( $content );
616 $output = $wgContLang->armourMath(
617 MathRenderer
::renderMath( $content, $params ) );
620 $output = $this->renderImageGallery( $content, $params );
623 if( isset( $this->mTagHooks
[$tagName] ) ) {
624 $output = call_user_func_array( $this->mTagHooks
[$tagName],
625 array( $content, $params, $this ) );
627 throw new MWException( "Invalid call hook $element" );
630 wfProfileOut( __METHOD__
."-render-$tagName" );
632 // Just stripping tags; keep the source
636 // Unstrip the output, to support recursive strip() calls
637 $output = $state->unstripBoth( $output );
639 if( !$stripcomments && $element == '!--' ) {
640 $commentState->setPair( $marker, $output );
641 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
642 $nowikiItems[$marker] = $output;
644 $generalItems[$marker] = $output;
647 # Add the new items to the state
648 # We do this after the loop instead of during it to avoid slowing
649 # down the recursive unstrip
650 $state->nowiki
->mergeArray( $nowikiItems );
651 $state->general
->mergeArray( $generalItems );
653 # Unstrip comments unless explicitly told otherwise.
654 # (The comments are always stripped prior to this point, so as to
655 # not invoke any extension tags / parser hooks contained within
657 if ( !$stripcomments ) {
658 // Put them all back and forget them
659 $text = $commentState->replace( $text );
662 wfProfileOut( __METHOD__
);
667 * Restores pre, math, and other extensions removed by strip()
669 * always call unstripNoWiki() after this one
671 * @deprecated use $this->mStripState->unstrip()
673 function unstrip( $text, $state ) {
674 return $state->unstripGeneral( $text );
678 * Always call this after unstrip() to preserve the order
681 * @deprecated use $this->mStripState->unstrip()
683 function unstripNoWiki( $text, $state ) {
684 return $state->unstripNoWiki( $text );
688 * @deprecated use $this->mStripState->unstripBoth()
690 function unstripForHTML( $text ) {
691 return $this->mStripState
->unstripBoth( $text );
695 * Add an item to the strip state
696 * Returns the unique tag which must be inserted into the stripped text
697 * The tag will be replaced with the original text in unstrip()
701 function insertStripItem( $text, &$state ) {
702 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
703 $state->general
->setPair( $rnd, $text );
708 * Interface with html tidy, used if $wgUseTidy = true.
709 * If tidy isn't able to correct the markup, the original will be
710 * returned in all its glory with a warning comment appended.
712 * Either the external tidy program or the in-process tidy extension
713 * will be used depending on availability. Override the default
714 * $wgTidyInternal setting to disable the internal if it's not working.
716 * @param string $text Hideous HTML input
717 * @return string Corrected HTML output
721 function tidy( $text ) {
722 global $wgTidyInternal;
723 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
724 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
725 '<head><title>test</title></head><body>'.$text.'</body></html>';
726 if( $wgTidyInternal ) {
727 $correctedtext = Parser
::internalTidy( $wrappedtext );
729 $correctedtext = Parser
::externalTidy( $wrappedtext );
731 if( is_null( $correctedtext ) ) {
732 wfDebug( "Tidy error detected!\n" );
733 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
735 return $correctedtext;
739 * Spawn an external HTML tidy process and get corrected markup back from it.
744 function externalTidy( $text ) {
745 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
746 $fname = 'Parser::externalTidy';
747 wfProfileIn( $fname );
752 $descriptorspec = array(
753 0 => array('pipe', 'r'),
754 1 => array('pipe', 'w'),
755 2 => array('file', '/dev/null', 'a') // FIXME: this line in UNIX-specific, it generates a warning on Windows, because /dev/null is not a valid Windows file.
758 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
759 if (is_resource($process)) {
760 // Theoretically, this style of communication could cause a deadlock
761 // here. If the stdout buffer fills up, then writes to stdin could
762 // block. This doesn't appear to happen with tidy, because tidy only
763 // writes to stdout after it's finished reading from stdin. Search
764 // for tidyParseStdin and tidySaveStdout in console/tidy.c
765 fwrite($pipes[0], $text);
767 while (!feof($pipes[1])) {
768 $cleansource .= fgets($pipes[1], 1024);
771 proc_close($process);
774 wfProfileOut( $fname );
776 if( $cleansource == '' && $text != '') {
777 // Some kind of error happened, so we couldn't get the corrected text.
778 // Just give up; we'll use the source text and append a warning.
786 * Use the HTML tidy PECL extension to use the tidy library in-process,
787 * saving the overhead of spawning a new process. Currently written to
788 * the PHP 4.3.x version of the extension, may not work on PHP 5.
790 * 'pear install tidy' should be able to compile the extension module.
795 function internalTidy( $text ) {
797 $fname = 'Parser::internalTidy';
798 wfProfileIn( $fname );
800 tidy_load_config( $wgTidyConf );
801 tidy_set_encoding( 'utf8' );
802 tidy_parse_string( $text );
804 if( tidy_get_status() == 2 ) {
805 // 2 is magic number for fatal error
806 // http://www.php.net/manual/en/function.tidy-get-status.php
809 $cleansource = tidy_get_output();
811 wfProfileOut( $fname );
816 * parse the wiki syntax used to render tables
820 function doTableStuff ( $text ) {
821 $fname = 'Parser::doTableStuff';
822 wfProfileIn( $fname );
824 $lines = explode ( "\n" , $text );
825 $td_history = array (); // Is currently a td tag open?
826 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
827 $tr_history = array (); // Is currently a tr tag open?
828 $tr_attributes = array (); // history of tr attributes
829 $has_opened_tr = array(); // Did this table open a <tr> element?
830 $indent_level = 0; // indent level of the table
831 foreach ( $lines as $key => $line )
833 $line = trim ( $line );
835 if( $line == '' ) { // empty line, go to next line
838 $first_character = $line{0};
841 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
842 // First check if we are starting a new table
843 $indent_level = strlen( $matches[1] );
845 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
846 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
848 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
849 array_push ( $td_history , false );
850 array_push ( $last_tag_history , '' );
851 array_push ( $tr_history , false );
852 array_push ( $tr_attributes , '' );
853 array_push ( $has_opened_tr , false );
854 } else if ( count ( $td_history ) == 0 ) {
855 // Don't do any of the following
857 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
858 // We are ending a table
859 $line = '</table>' . substr ( $line , 2 );
860 $last_tag = array_pop ( $last_tag_history );
862 if ( !array_pop ( $has_opened_tr ) ) {
863 $line = "<tr><td></td></tr>{$line}";
866 if ( array_pop ( $tr_history ) ) {
867 $line = "</tr>{$line}";
870 if ( array_pop ( $td_history ) ) {
871 $line = "</{$last_tag}>{$line}";
873 array_pop ( $tr_attributes );
874 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
875 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
876 // Now we have a table row
877 $line = preg_replace( '#^\|-+#', '', $line );
879 // Whats after the tag is now only attributes
880 $attributes = $this->mStripState
->unstripBoth( $line );
881 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
882 array_pop ( $tr_attributes );
883 array_push ( $tr_attributes , $attributes );
886 $last_tag = array_pop ( $last_tag_history );
887 array_pop ( $has_opened_tr );
888 array_push ( $has_opened_tr , true );
890 if ( array_pop ( $tr_history ) ) {
894 if ( array_pop ( $td_history ) ) {
895 $line = "</{$last_tag}>{$line}";
898 $lines[$key] = $line;
899 array_push ( $tr_history , false );
900 array_push ( $td_history , false );
901 array_push ( $last_tag_history , '' );
903 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
904 // This might be cell elements, td, th or captions
905 if ( substr ( $line , 0 , 2 ) == '|+' ) {
906 $first_character = '+';
907 $line = substr ( $line , 1 );
910 $line = substr ( $line , 1 );
912 if ( $first_character == '!' ) {
913 $line = str_replace ( '!!' , '||' , $line );
916 // Split up multiple cells on the same line.
917 // FIXME : This can result in improper nesting of tags processed
918 // by earlier parser steps, but should avoid splitting up eg
919 // attribute values containing literal "||".
920 $cells = StringUtils
::explodeMarkup( '||' , $line );
924 // Loop through each table cell
925 foreach ( $cells as $cell )
928 if ( $first_character != '+' )
930 $tr_after = array_pop ( $tr_attributes );
931 if ( !array_pop ( $tr_history ) ) {
932 $previous = "<tr{$tr_after}>\n";
934 array_push ( $tr_history , true );
935 array_push ( $tr_attributes , '' );
936 array_pop ( $has_opened_tr );
937 array_push ( $has_opened_tr , true );
940 $last_tag = array_pop ( $last_tag_history );
942 if ( array_pop ( $td_history ) ) {
943 $previous = "</{$last_tag}>{$previous}";
946 if ( $first_character == '|' ) {
948 } else if ( $first_character == '!' ) {
950 } else if ( $first_character == '+' ) {
951 $last_tag = 'caption';
956 array_push ( $last_tag_history , $last_tag );
958 // A cell could contain both parameters and data
959 $cell_data = explode ( '|' , $cell , 2 );
961 // Bug 553: Note that a '|' inside an invalid link should not
962 // be mistaken as delimiting cell parameters
963 if ( strpos( $cell_data[0], '[[' ) !== false ) {
964 $cell = "{$previous}<{$last_tag}>{$cell}";
965 } else if ( count ( $cell_data ) == 1 )
966 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
968 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
969 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
970 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
973 $lines[$key] .= $cell;
974 array_push ( $td_history , true );
979 // Closing open td, tr && table
980 while ( count ( $td_history ) > 0 )
982 if ( array_pop ( $td_history ) ) {
985 if ( array_pop ( $tr_history ) ) {
988 if ( !array_pop ( $has_opened_tr ) ) {
989 $lines[] = "<tr><td></td></tr>" ;
992 $lines[] = '</table>' ;
995 $output = implode ( "\n" , $lines ) ;
997 // special case: don't return empty table
998 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
1002 wfProfileOut( $fname );
1008 * Helper function for parse() that transforms wiki markup into
1009 * HTML. Only called for $mOutputType == OT_HTML.
1013 function internalParse( $text ) {
1016 $fname = 'Parser::internalParse';
1017 wfProfileIn( $fname );
1019 # Hook to suspend the parser in this state
1020 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1021 wfProfileOut( $fname );
1025 # Remove <noinclude> tags and <includeonly> sections
1026 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
1027 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
1028 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1030 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), array(), array_keys( $this->mTransparentTagHooks
) );
1032 $text = $this->replaceVariables( $text, $args );
1033 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1035 // Tables need to come after variable replacement for things to work
1036 // properly; putting them before other transformations should keep
1037 // exciting things like link expansions from showing up in surprising
1039 $text = $this->doTableStuff( $text );
1041 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1043 $text = $this->stripToc( $text );
1044 $this->stripNoGallery( $text );
1045 $text = $this->doHeadings( $text );
1046 if($this->mOptions
->getUseDynamicDates()) {
1047 $df =& DateFormatter
::getInstance();
1048 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1050 $text = $this->doAllQuotes( $text );
1051 $text = $this->replaceInternalLinks( $text );
1052 $text = $this->replaceExternalLinks( $text );
1054 # replaceInternalLinks may sometimes leave behind
1055 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1056 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1058 $text = $this->doMagicLinks( $text );
1059 $text = $this->formatHeadings( $text, $isMain );
1061 wfProfileOut( $fname );
1066 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1067 * magic external links.
1071 function &doMagicLinks( &$text ) {
1072 wfProfileIn( __METHOD__
);
1073 $text = preg_replace_callback(
1075 <a.*?</a> | # Skip link text
1076 <.*?> | # Skip stuff inside HTML elements
1077 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1078 ISBN\s+(\b # ISBN, capture number as m[2]
1079 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1080 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1081 [0-9Xx] # check digit
1083 )!x', array( &$this, 'magicLinkCallback' ), $text );
1084 wfProfileOut( __METHOD__
);
1088 function magicLinkCallback( $m ) {
1089 if ( substr( $m[0], 0, 1 ) == '<' ) {
1092 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1094 $num = strtr( $isbn, array(
1099 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1100 $text = '<a href="' .
1101 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1102 "\" class=\"internal\">ISBN $isbn</a>";
1104 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1108 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1110 $urlmsg = 'pubmedurl';
1113 throw new MWException( __METHOD__
.': unrecognised match type "' .
1114 substr($m[0], 0, 20 ) . '"' );
1117 $url = wfMsg( $urlmsg, $id);
1118 $sk = $this->mOptions
->getSkin();
1119 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1120 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1126 * Parse headers and return html
1130 function doHeadings( $text ) {
1131 $fname = 'Parser::doHeadings';
1132 wfProfileIn( $fname );
1133 for ( $i = 6; $i >= 1; --$i ) {
1134 $h = str_repeat( '=', $i );
1135 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1136 "<h{$i}>\\1</h{$i}>\\2", $text );
1138 wfProfileOut( $fname );
1143 * Replace single quotes with HTML markup
1145 * @return string the altered text
1147 function doAllQuotes( $text ) {
1148 $fname = 'Parser::doAllQuotes';
1149 wfProfileIn( $fname );
1151 $lines = explode( "\n", $text );
1152 foreach ( $lines as $line ) {
1153 $outtext .= $this->doQuotes ( $line ) . "\n";
1155 $outtext = substr($outtext, 0,-1);
1156 wfProfileOut( $fname );
1161 * Helper function for doAllQuotes()
1164 function doQuotes( $text ) {
1165 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1166 if ( count( $arr ) == 1 )
1170 # First, do some preliminary work. This may shift some apostrophes from
1171 # being mark-up to being text. It also counts the number of occurrences
1172 # of bold and italics mark-ups.
1176 foreach ( $arr as $r )
1178 if ( ( $i %
2 ) == 1 )
1180 # If there are ever four apostrophes, assume the first is supposed to
1181 # be text, and the remaining three constitute mark-up for bold text.
1182 if ( strlen( $arr[$i] ) == 4 )
1187 # If there are more than 5 apostrophes in a row, assume they're all
1188 # text except for the last 5.
1189 else if ( strlen( $arr[$i] ) > 5 )
1191 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1194 # Count the number of occurrences of bold and italics mark-ups.
1195 # We are not counting sequences of five apostrophes.
1196 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1197 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1198 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1203 # If there is an odd number of both bold and italics, it is likely
1204 # that one of the bold ones was meant to be an apostrophe followed
1205 # by italics. Which one we cannot know for certain, but it is more
1206 # likely to be one that has a single-letter word before it.
1207 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1210 $firstsingleletterword = -1;
1211 $firstmultiletterword = -1;
1213 foreach ( $arr as $r )
1215 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1217 $x1 = substr ($arr[$i-1], -1);
1218 $x2 = substr ($arr[$i-1], -2, 1);
1220 if ($firstspace == -1) $firstspace = $i;
1221 } else if ($x2 == ' ') {
1222 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1224 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1230 # If there is a single-letter word, use it!
1231 if ($firstsingleletterword > -1)
1233 $arr [ $firstsingleletterword ] = "''";
1234 $arr [ $firstsingleletterword-1 ] .= "'";
1236 # If not, but there's a multi-letter word, use that one.
1237 else if ($firstmultiletterword > -1)
1239 $arr [ $firstmultiletterword ] = "''";
1240 $arr [ $firstmultiletterword-1 ] .= "'";
1242 # ... otherwise use the first one that has neither.
1243 # (notice that it is possible for all three to be -1 if, for example,
1244 # there is only one pentuple-apostrophe in the line)
1245 else if ($firstspace > -1)
1247 $arr [ $firstspace ] = "''";
1248 $arr [ $firstspace-1 ] .= "'";
1252 # Now let's actually convert our apostrophic mush to HTML!
1257 foreach ($arr as $r)
1261 if ($state == 'both')
1268 if (strlen ($r) == 2)
1271 { $output .= '</i>'; $state = ''; }
1272 else if ($state == 'bi')
1273 { $output .= '</i>'; $state = 'b'; }
1274 else if ($state == 'ib')
1275 { $output .= '</b></i><b>'; $state = 'b'; }
1276 else if ($state == 'both')
1277 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1278 else # $state can be 'b' or ''
1279 { $output .= '<i>'; $state .= 'i'; }
1281 else if (strlen ($r) == 3)
1284 { $output .= '</b>'; $state = ''; }
1285 else if ($state == 'bi')
1286 { $output .= '</i></b><i>'; $state = 'i'; }
1287 else if ($state == 'ib')
1288 { $output .= '</b>'; $state = 'i'; }
1289 else if ($state == 'both')
1290 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1291 else # $state can be 'i' or ''
1292 { $output .= '<b>'; $state .= 'b'; }
1294 else if (strlen ($r) == 5)
1297 { $output .= '</b><i>'; $state = 'i'; }
1298 else if ($state == 'i')
1299 { $output .= '</i><b>'; $state = 'b'; }
1300 else if ($state == 'bi')
1301 { $output .= '</i></b>'; $state = ''; }
1302 else if ($state == 'ib')
1303 { $output .= '</b></i>'; $state = ''; }
1304 else if ($state == 'both')
1305 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1306 else # ($state == '')
1307 { $buffer = ''; $state = 'both'; }
1312 # Now close all remaining tags. Notice that the order is important.
1313 if ($state == 'b' ||
$state == 'ib')
1315 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1319 # There might be lonely ''''', so make sure we have a buffer
1320 if ($state == 'both' && $buffer)
1321 $output .= '<b><i>'.$buffer.'</i></b>';
1327 * Replace external links
1329 * Note: this is all very hackish and the order of execution matters a lot.
1330 * Make sure to run maintenance/parserTests.php if you change this code.
1334 function replaceExternalLinks( $text ) {
1336 $fname = 'Parser::replaceExternalLinks';
1337 wfProfileIn( $fname );
1339 $sk = $this->mOptions
->getSkin();
1341 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1343 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1346 while ( $i<count( $bits ) ) {
1348 $protocol = $bits[$i++
];
1349 $text = $bits[$i++
];
1350 $trail = $bits[$i++
];
1352 # The characters '<' and '>' (which were escaped by
1353 # removeHTMLtags()) should not be included in
1354 # URLs, per RFC 2396.
1356 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1357 $text = substr($url, $m2[0][1]) . ' ' . $text;
1358 $url = substr($url, 0, $m2[0][1]);
1361 # If the link text is an image URL, replace it with an <img> tag
1362 # This happened by accident in the original parser, but some people used it extensively
1363 $img = $this->maybeMakeExternalImage( $text );
1364 if ( $img !== false ) {
1370 # Set linktype for CSS - if URL==text, link is essentially free
1371 $linktype = ($text == $url) ?
'free' : 'text';
1373 # No link text, e.g. [http://domain.tld/some.link]
1374 if ( $text == '' ) {
1375 # Autonumber if allowed. See bug #5918
1376 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1377 $text = '[' . ++
$this->mAutonumber
. ']';
1378 $linktype = 'autonumber';
1380 # Otherwise just use the URL
1381 $text = htmlspecialchars( $url );
1385 # Have link text, e.g. [http://domain.tld/some.link text]s
1387 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1390 $text = $wgContLang->markNoConversion($text);
1392 $url = Sanitizer
::cleanUrl( $url );
1394 # Process the trail (i.e. everything after this link up until start of the next link),
1395 # replacing any non-bracketed links
1396 $trail = $this->replaceFreeExternalLinks( $trail );
1398 # Use the encoded URL
1399 # This means that users can paste URLs directly into the text
1400 # Funny characters like ö aren't valid in URLs anyway
1401 # This was changed in August 2004
1402 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1404 # Register link in the output object.
1405 # Replace unnecessary URL escape codes with the referenced character
1406 # This prevents spammers from hiding links from the filters
1407 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1408 $this->mOutput
->addExternalLink( $pasteurized );
1411 wfProfileOut( $fname );
1416 * Replace anything that looks like a URL with a link
1419 function replaceFreeExternalLinks( $text ) {
1421 $fname = 'Parser::replaceFreeExternalLinks';
1422 wfProfileIn( $fname );
1424 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1425 $s = array_shift( $bits );
1428 $sk = $this->mOptions
->getSkin();
1430 while ( $i < count( $bits ) ){
1431 $protocol = $bits[$i++
];
1432 $remainder = $bits[$i++
];
1435 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1436 # Found some characters after the protocol that look promising
1437 $url = $protocol . $m[1];
1440 # special case: handle urls as url args:
1441 # http://www.example.com/foo?=http://www.example.com/bar
1442 if(strlen($trail) == 0 &&
1444 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1445 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1448 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1453 # The characters '<' and '>' (which were escaped by
1454 # removeHTMLtags()) should not be included in
1455 # URLs, per RFC 2396.
1457 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1458 $trail = substr($url, $m2[0][1]) . $trail;
1459 $url = substr($url, 0, $m2[0][1]);
1462 # Move trailing punctuation to $trail
1464 # If there is no left bracket, then consider right brackets fair game too
1465 if ( strpos( $url, '(' ) === false ) {
1469 $numSepChars = strspn( strrev( $url ), $sep );
1470 if ( $numSepChars ) {
1471 $trail = substr( $url, -$numSepChars ) . $trail;
1472 $url = substr( $url, 0, -$numSepChars );
1475 $url = Sanitizer
::cleanUrl( $url );
1477 # Is this an external image?
1478 $text = $this->maybeMakeExternalImage( $url );
1479 if ( $text === false ) {
1480 # Not an image, make a link
1481 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1482 # Register it in the output object...
1483 # Replace unnecessary URL escape codes with their equivalent characters
1484 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1485 $this->mOutput
->addExternalLink( $pasteurized );
1487 $s .= $text . $trail;
1489 $s .= $protocol . $remainder;
1492 wfProfileOut( $fname );
1497 * Replace unusual URL escape codes with their equivalent characters
1501 * @todo This can merge genuinely required bits in the path or query string,
1502 * breaking legit URLs. A proper fix would treat the various parts of
1503 * the URL differently; as a workaround, just use the output for
1504 * statistical records, not for actual linking/output.
1506 static function replaceUnusualEscapes( $url ) {
1507 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1508 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1512 * Callback function used in replaceUnusualEscapes().
1513 * Replaces unusual URL escape codes with their equivalent character
1517 private static function replaceUnusualEscapesCallback( $matches ) {
1518 $char = urldecode( $matches[0] );
1519 $ord = ord( $char );
1520 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1521 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1522 // No, shouldn't be escaped
1525 // Yes, leave it escaped
1531 * make an image if it's allowed, either through the global
1532 * option or through the exception
1535 function maybeMakeExternalImage( $url ) {
1536 $sk = $this->mOptions
->getSkin();
1537 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1538 $imagesexception = !empty($imagesfrom);
1540 if ( $this->mOptions
->getAllowExternalImages()
1541 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1542 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1544 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1551 * Process [[ ]] wikilinks
1555 function replaceInternalLinks( $s ) {
1557 static $fname = 'Parser::replaceInternalLinks' ;
1559 wfProfileIn( $fname );
1561 wfProfileIn( $fname.'-setup' );
1563 # the % is needed to support urlencoded titles as well
1564 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1566 $sk = $this->mOptions
->getSkin();
1568 #split the entire text string on occurences of [[
1569 $a = explode( '[[', ' ' . $s );
1570 #get the first element (all text up to first [[), and remove the space we added
1571 $s = array_shift( $a );
1572 $s = substr( $s, 1 );
1574 # Match a link having the form [[namespace:link|alternate]]trail
1576 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1577 # Match cases where there is no "]]", which might still be images
1578 static $e1_img = FALSE;
1579 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1580 # Match the end of a line for a word that's not followed by whitespace,
1581 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1582 $e2 = wfMsgForContent( 'linkprefix' );
1584 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1585 if( is_null( $this->mTitle
) ) {
1586 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1588 $nottalk = !$this->mTitle
->isTalkPage();
1590 if ( $useLinkPrefixExtension ) {
1592 if ( preg_match( $e2, $s, $m ) ) {
1593 $first_prefix = $m[2];
1595 $first_prefix = false;
1601 if($wgContLang->hasVariants()) {
1602 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1604 $selflink = array($this->mTitle
->getPrefixedText());
1606 $useSubpages = $this->areSubpagesAllowed();
1607 wfProfileOut( $fname.'-setup' );
1609 # Loop for each link
1610 for ($k = 0; isset( $a[$k] ); $k++
) {
1612 if ( $useLinkPrefixExtension ) {
1613 wfProfileIn( $fname.'-prefixhandling' );
1614 if ( preg_match( $e2, $s, $m ) ) {
1622 $prefix = $first_prefix;
1623 $first_prefix = false;
1625 wfProfileOut( $fname.'-prefixhandling' );
1628 $might_be_img = false;
1630 wfProfileIn( "$fname-e1" );
1631 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1633 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1634 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1635 # the real problem is with the $e1 regex
1638 # Still some problems for cases where the ] is meant to be outside punctuation,
1639 # and no image is in sight. See bug 2095.
1642 substr( $m[3], 0, 1 ) === ']' &&
1643 strpos($text, '[') !== false
1646 $text .= ']'; # so that replaceExternalLinks($text) works later
1647 $m[3] = substr( $m[3], 1 );
1649 # fix up urlencoded title texts
1650 if( strpos( $m[1], '%' ) !== false ) {
1651 # Should anchors '#' also be rejected?
1652 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1655 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1656 $might_be_img = true;
1658 if ( strpos( $m[1], '%' ) !== false ) {
1659 $m[1] = urldecode($m[1]);
1662 } else { # Invalid form; output directly
1663 $s .= $prefix . '[[' . $line ;
1664 wfProfileOut( "$fname-e1" );
1667 wfProfileOut( "$fname-e1" );
1668 wfProfileIn( "$fname-misc" );
1670 # Don't allow internal links to pages containing
1671 # PROTO: where PROTO is a valid URL protocol; these
1672 # should be external links.
1673 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1674 $s .= $prefix . '[[' . $line ;
1678 # Make subpage if necessary
1679 if( $useSubpages ) {
1680 $link = $this->maybeDoSubpageLink( $m[1], $text );
1685 $noforce = (substr($m[1], 0, 1) != ':');
1687 # Strip off leading ':'
1688 $link = substr($link, 1);
1691 wfProfileOut( "$fname-misc" );
1692 wfProfileIn( "$fname-title" );
1693 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1695 $s .= $prefix . '[[' . $line;
1696 wfProfileOut( "$fname-title" );
1700 $ns = $nt->getNamespace();
1701 $iw = $nt->getInterWiki();
1702 wfProfileOut( "$fname-title" );
1704 if ($might_be_img) { # if this is actually an invalid link
1705 wfProfileIn( "$fname-might_be_img" );
1706 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1708 while (isset ($a[$k+
1]) ) {
1709 #look at the next 'line' to see if we can close it there
1710 $spliced = array_splice( $a, $k +
1, 1 );
1711 $next_line = array_shift( $spliced );
1712 $m = explode( ']]', $next_line, 3 );
1713 if ( count( $m ) == 3 ) {
1714 # the first ]] closes the inner link, the second the image
1716 $text .= "[[{$m[0]}]]{$m[1]}";
1719 } elseif ( count( $m ) == 2 ) {
1720 #if there's exactly one ]] that's fine, we'll keep looking
1721 $text .= "[[{$m[0]}]]{$m[1]}";
1723 #if $next_line is invalid too, we need look no further
1724 $text .= '[[' . $next_line;
1729 # we couldn't find the end of this imageLink, so output it raw
1730 #but don't ignore what might be perfectly normal links in the text we've examined
1731 $text = $this->replaceInternalLinks($text);
1732 $s .= "{$prefix}[[$link|$text";
1733 # note: no $trail, because without an end, there *is* no trail
1734 wfProfileOut( "$fname-might_be_img" );
1737 } else { #it's not an image, so output it raw
1738 $s .= "{$prefix}[[$link|$text";
1739 # note: no $trail, because without an end, there *is* no trail
1740 wfProfileOut( "$fname-might_be_img" );
1743 wfProfileOut( "$fname-might_be_img" );
1746 $wasblank = ( '' == $text );
1747 if( $wasblank ) $text = $link;
1749 # Link not escaped by : , create the various objects
1753 wfProfileIn( "$fname-interwiki" );
1754 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1755 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1756 $s = rtrim($s . $prefix);
1757 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1758 wfProfileOut( "$fname-interwiki" );
1761 wfProfileOut( "$fname-interwiki" );
1763 if ( $ns == NS_IMAGE
) {
1764 wfProfileIn( "$fname-image" );
1765 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1766 # recursively parse links inside the image caption
1767 # actually, this will parse them in any other parameters, too,
1768 # but it might be hard to fix that, and it doesn't matter ATM
1769 $text = $this->replaceExternalLinks($text);
1770 $text = $this->replaceInternalLinks($text);
1772 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1773 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1774 $this->mOutput
->addImage( $nt->getDBkey() );
1776 wfProfileOut( "$fname-image" );
1779 # We still need to record the image's presence on the page
1780 $this->mOutput
->addImage( $nt->getDBkey() );
1782 wfProfileOut( "$fname-image" );
1786 if ( $ns == NS_CATEGORY
) {
1787 wfProfileIn( "$fname-category" );
1788 $s = rtrim($s . "\n"); # bug 87
1791 $sortkey = $this->getDefaultSort();
1795 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1796 $sortkey = str_replace( "\n", '', $sortkey );
1797 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1798 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1801 * Strip the whitespace Category links produce, see bug 87
1802 * @todo We might want to use trim($tmp, "\n") here.
1804 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1806 wfProfileOut( "$fname-category" );
1811 # Self-link checking
1812 if( $nt->getFragment() === '' ) {
1813 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1814 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1819 # Special and Media are pseudo-namespaces; no pages actually exist in them
1820 if( $ns == NS_MEDIA
) {
1821 $link = $sk->makeMediaLinkObj( $nt, $text );
1822 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1823 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1824 $this->mOutput
->addImage( $nt->getDBkey() );
1826 } elseif( $ns == NS_SPECIAL
) {
1827 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1828 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1830 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1833 } elseif( $ns == NS_IMAGE
) {
1834 $img = wfFindFile( $nt );
1836 // Force a blue link if the file exists; may be a remote
1837 // upload on the shared repository, and we want to see its
1838 // auto-generated page.
1839 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1840 $this->mOutput
->addLink( $nt );
1844 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1846 wfProfileOut( $fname );
1851 * Make a link placeholder. The text returned can be later resolved to a real link with
1852 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1853 * parsing of interwiki links, and secondly to allow all existence checks and
1854 * article length checks (for stub links) to be bundled into a single query.
1857 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1858 wfProfileIn( __METHOD__
);
1859 if ( ! is_object($nt) ) {
1861 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1863 # Separate the link trail from the rest of the link
1864 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1866 if ( $nt->isExternal() ) {
1867 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1868 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1869 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1871 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1872 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1873 $this->mLinkHolders
['queries'][] = $query;
1874 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1875 $this->mLinkHolders
['titles'][] = $nt;
1877 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1880 wfProfileOut( __METHOD__
);
1885 * Render a forced-blue link inline; protect against double expansion of
1886 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1887 * Since this little disaster has to split off the trail text to avoid
1888 * breaking URLs in the following text without breaking trails on the
1889 * wiki links, it's been made into a horrible function.
1892 * @param string $text
1893 * @param string $query
1894 * @param string $trail
1895 * @param string $prefix
1896 * @return string HTML-wikitext mix oh yuck
1898 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1899 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1900 $sk = $this->mOptions
->getSkin();
1901 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1902 return $this->armorLinks( $link ) . $trail;
1906 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1907 * going to go through further parsing steps before inline URL expansion.
1909 * In particular this is important when using action=render, which causes
1910 * full URLs to be included.
1912 * Oh man I hate our multi-layer parser!
1914 * @param string more-or-less HTML
1915 * @return string less-or-more HTML with NOPARSE bits
1917 function armorLinks( $text ) {
1918 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1919 "{$this->mUniqPrefix}NOPARSE$1", $text );
1923 * Return true if subpage links should be expanded on this page.
1926 function areSubpagesAllowed() {
1927 # Some namespaces don't allow subpages
1928 global $wgNamespacesWithSubpages;
1929 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1933 * Handle link to subpage if necessary
1934 * @param string $target the source of the link
1935 * @param string &$text the link text, modified as necessary
1936 * @return string the full name of the link
1939 function maybeDoSubpageLink($target, &$text) {
1942 # :Foobar -- override special treatment of prefix (images, language links)
1943 # /Foobar -- convert to CurrentPage/Foobar
1944 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1945 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1946 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1948 $fname = 'Parser::maybeDoSubpageLink';
1949 wfProfileIn( $fname );
1950 $ret = $target; # default return value is no change
1952 # Some namespaces don't allow subpages,
1953 # so only perform processing if subpages are allowed
1954 if( $this->areSubpagesAllowed() ) {
1955 $hash = strpos( $target, '#' );
1956 if( $hash !== false ) {
1957 $suffix = substr( $target, $hash );
1958 $target = substr( $target, 0, $hash );
1963 $target = trim( $target );
1964 # Look at the first character
1965 if( $target != '' && $target{0} == '/' ) {
1966 # / at end means we don't want the slash to be shown
1968 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1969 if( $trailingSlashes ) {
1970 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1972 $noslash = substr( $target, 1 );
1975 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1976 if( '' === $text ) {
1977 $text = $target . $suffix;
1978 } # this might be changed for ugliness reasons
1980 # check for .. subpage backlinks
1982 $nodotdot = $target;
1983 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1985 $nodotdot = substr( $nodotdot, 3 );
1987 if($dotdotcount > 0) {
1988 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1989 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1990 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1991 # / at the end means don't show full path
1992 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1993 $nodotdot = substr( $nodotdot, 0, -1 );
1994 if( '' === $text ) {
1995 $text = $nodotdot . $suffix;
1998 $nodotdot = trim( $nodotdot );
1999 if( $nodotdot != '' ) {
2000 $ret .= '/' . $nodotdot;
2008 wfProfileOut( $fname );
2013 * Used by doBlockLevels()
2016 /* private */ function closeParagraph() {
2018 if ( '' != $this->mLastSection
) {
2019 $result = '</' . $this->mLastSection
. ">\n";
2021 $this->mInPre
= false;
2022 $this->mLastSection
= '';
2025 # getCommon() returns the length of the longest common substring
2026 # of both arguments, starting at the beginning of both.
2028 /* private */ function getCommon( $st1, $st2 ) {
2029 $fl = strlen( $st1 );
2030 $shorter = strlen( $st2 );
2031 if ( $fl < $shorter ) { $shorter = $fl; }
2033 for ( $i = 0; $i < $shorter; ++
$i ) {
2034 if ( $st1{$i} != $st2{$i} ) { break; }
2038 # These next three functions open, continue, and close the list
2039 # element appropriate to the prefix character passed into them.
2041 /* private */ function openList( $char ) {
2042 $result = $this->closeParagraph();
2044 if ( '*' == $char ) { $result .= '<ul><li>'; }
2045 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2046 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2047 else if ( ';' == $char ) {
2048 $result .= '<dl><dt>';
2049 $this->mDTopen
= true;
2051 else { $result = '<!-- ERR 1 -->'; }
2056 /* private */ function nextItem( $char ) {
2057 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2058 else if ( ':' == $char ||
';' == $char ) {
2060 if ( $this->mDTopen
) { $close = '</dt>'; }
2061 if ( ';' == $char ) {
2062 $this->mDTopen
= true;
2063 return $close . '<dt>';
2065 $this->mDTopen
= false;
2066 return $close . '<dd>';
2069 return '<!-- ERR 2 -->';
2072 /* private */ function closeList( $char ) {
2073 if ( '*' == $char ) { $text = '</li></ul>'; }
2074 else if ( '#' == $char ) { $text = '</li></ol>'; }
2075 else if ( ':' == $char ) {
2076 if ( $this->mDTopen
) {
2077 $this->mDTopen
= false;
2078 $text = '</dt></dl>';
2080 $text = '</dd></dl>';
2083 else { return '<!-- ERR 3 -->'; }
2089 * Make lists from lines starting with ':', '*', '#', etc.
2092 * @return string the lists rendered as HTML
2094 function doBlockLevels( $text, $linestart ) {
2095 $fname = 'Parser::doBlockLevels';
2096 wfProfileIn( $fname );
2098 # Parsing through the text line by line. The main thing
2099 # happening here is handling of block-level elements p, pre,
2100 # and making lists from lines starting with * # : etc.
2102 $textLines = explode( "\n", $text );
2104 $lastPrefix = $output = '';
2105 $this->mDTopen
= $inBlockElem = false;
2107 $paragraphStack = false;
2109 if ( !$linestart ) {
2110 $output .= array_shift( $textLines );
2112 foreach ( $textLines as $oLine ) {
2113 $lastPrefixLength = strlen( $lastPrefix );
2114 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2115 $preOpenMatch = preg_match('/<pre/i', $oLine );
2116 if ( !$this->mInPre
) {
2117 # Multiple prefixes may abut each other for nested lists.
2118 $prefixLength = strspn( $oLine, '*#:;' );
2119 $pref = substr( $oLine, 0, $prefixLength );
2122 $pref2 = str_replace( ';', ':', $pref );
2123 $t = substr( $oLine, $prefixLength );
2124 $this->mInPre
= !empty($preOpenMatch);
2126 # Don't interpret any other prefixes in preformatted text
2128 $pref = $pref2 = '';
2133 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2134 # Same as the last item, so no need to deal with nesting or opening stuff
2135 $output .= $this->nextItem( substr( $pref, -1 ) );
2136 $paragraphStack = false;
2138 if ( substr( $pref, -1 ) == ';') {
2139 # The one nasty exception: definition lists work like this:
2140 # ; title : definition text
2141 # So we check for : in the remainder text to split up the
2142 # title and definition, without b0rking links.
2144 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2146 $output .= $term . $this->nextItem( ':' );
2149 } elseif( $prefixLength ||
$lastPrefixLength ) {
2150 # Either open or close a level...
2151 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2152 $paragraphStack = false;
2154 while( $commonPrefixLength < $lastPrefixLength ) {
2155 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2156 --$lastPrefixLength;
2158 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2159 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2161 while ( $prefixLength > $commonPrefixLength ) {
2162 $char = substr( $pref, $commonPrefixLength, 1 );
2163 $output .= $this->openList( $char );
2165 if ( ';' == $char ) {
2166 # FIXME: This is dupe of code above
2167 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2169 $output .= $term . $this->nextItem( ':' );
2172 ++
$commonPrefixLength;
2174 $lastPrefix = $pref2;
2176 if( 0 == $prefixLength ) {
2177 wfProfileIn( "$fname-paragraph" );
2178 # No prefix (not in list)--go to paragraph mode
2179 // XXX: use a stack for nestable elements like span, table and div
2180 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2181 $closematch = preg_match(
2182 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2183 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2184 if ( $openmatch or $closematch ) {
2185 $paragraphStack = false;
2186 #Â TODO bug 5718: paragraph closed
2187 $output .= $this->closeParagraph();
2188 if ( $preOpenMatch and !$preCloseMatch ) {
2189 $this->mInPre
= true;
2191 if ( $closematch ) {
2192 $inBlockElem = false;
2194 $inBlockElem = true;
2196 } else if ( !$inBlockElem && !$this->mInPre
) {
2197 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2199 if ($this->mLastSection
!= 'pre') {
2200 $paragraphStack = false;
2201 $output .= $this->closeParagraph().'<pre>';
2202 $this->mLastSection
= 'pre';
2204 $t = substr( $t, 1 );
2207 if ( '' == trim($t) ) {
2208 if ( $paragraphStack ) {
2209 $output .= $paragraphStack.'<br />';
2210 $paragraphStack = false;
2211 $this->mLastSection
= 'p';
2213 if ($this->mLastSection
!= 'p' ) {
2214 $output .= $this->closeParagraph();
2215 $this->mLastSection
= '';
2216 $paragraphStack = '<p>';
2218 $paragraphStack = '</p><p>';
2222 if ( $paragraphStack ) {
2223 $output .= $paragraphStack;
2224 $paragraphStack = false;
2225 $this->mLastSection
= 'p';
2226 } else if ($this->mLastSection
!= 'p') {
2227 $output .= $this->closeParagraph().'<p>';
2228 $this->mLastSection
= 'p';
2233 wfProfileOut( "$fname-paragraph" );
2235 // somewhere above we forget to get out of pre block (bug 785)
2236 if($preCloseMatch && $this->mInPre
) {
2237 $this->mInPre
= false;
2239 if ($paragraphStack === false) {
2243 while ( $prefixLength ) {
2244 $output .= $this->closeList( $pref2{$prefixLength-1} );
2247 if ( '' != $this->mLastSection
) {
2248 $output .= '</' . $this->mLastSection
. '>';
2249 $this->mLastSection
= '';
2252 wfProfileOut( $fname );
2257 * Split up a string on ':', ignoring any occurences inside tags
2258 * to prevent illegal overlapping.
2259 * @param string $str the string to split
2260 * @param string &$before set to everything before the ':'
2261 * @param string &$after set to everything after the ':'
2262 * return string the position of the ':', or false if none found
2264 function findColonNoLinks($str, &$before, &$after) {
2265 $fname = 'Parser::findColonNoLinks';
2266 wfProfileIn( $fname );
2268 $pos = strpos( $str, ':' );
2269 if( $pos === false ) {
2271 wfProfileOut( $fname );
2275 $lt = strpos( $str, '<' );
2276 if( $lt === false ||
$lt > $pos ) {
2277 // Easy; no tag nesting to worry about
2278 $before = substr( $str, 0, $pos );
2279 $after = substr( $str, $pos+
1 );
2280 wfProfileOut( $fname );
2284 // Ugly state machine to walk through avoiding tags.
2285 $state = MW_COLON_STATE_TEXT
;
2287 $len = strlen( $str );
2288 for( $i = 0; $i < $len; $i++
) {
2292 // (Using the number is a performance hack for common cases)
2293 case 0: // MW_COLON_STATE_TEXT:
2296 // Could be either a <start> tag or an </end> tag
2297 $state = MW_COLON_STATE_TAGSTART
;
2302 $before = substr( $str, 0, $i );
2303 $after = substr( $str, $i +
1 );
2304 wfProfileOut( $fname );
2307 // Embedded in a tag; don't break it.
2310 // Skip ahead looking for something interesting
2311 $colon = strpos( $str, ':', $i );
2312 if( $colon === false ) {
2313 // Nothing else interesting
2314 wfProfileOut( $fname );
2317 $lt = strpos( $str, '<', $i );
2318 if( $stack === 0 ) {
2319 if( $lt === false ||
$colon < $lt ) {
2321 $before = substr( $str, 0, $colon );
2322 $after = substr( $str, $colon +
1 );
2323 wfProfileOut( $fname );
2327 if( $lt === false ) {
2328 // Nothing else interesting to find; abort!
2329 // We're nested, but there's no close tags left. Abort!
2332 // Skip ahead to next tag start
2334 $state = MW_COLON_STATE_TAGSTART
;
2337 case 1: // MW_COLON_STATE_TAG:
2342 $state = MW_COLON_STATE_TEXT
;
2345 // Slash may be followed by >?
2346 $state = MW_COLON_STATE_TAGSLASH
;
2352 case 2: // MW_COLON_STATE_TAGSTART:
2355 $state = MW_COLON_STATE_CLOSETAG
;
2358 $state = MW_COLON_STATE_COMMENT
;
2361 // Illegal early close? This shouldn't happen D:
2362 $state = MW_COLON_STATE_TEXT
;
2365 $state = MW_COLON_STATE_TAG
;
2368 case 3: // MW_COLON_STATE_CLOSETAG:
2373 wfDebug( "Invalid input in $fname; too many close tags\n" );
2374 wfProfileOut( $fname );
2377 $state = MW_COLON_STATE_TEXT
;
2380 case MW_COLON_STATE_TAGSLASH
:
2382 // Yes, a self-closed tag <blah/>
2383 $state = MW_COLON_STATE_TEXT
;
2385 // Probably we're jumping the gun, and this is an attribute
2386 $state = MW_COLON_STATE_TAG
;
2389 case 5: // MW_COLON_STATE_COMMENT:
2391 $state = MW_COLON_STATE_COMMENTDASH
;
2394 case MW_COLON_STATE_COMMENTDASH
:
2396 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2398 $state = MW_COLON_STATE_COMMENT
;
2401 case MW_COLON_STATE_COMMENTDASHDASH
:
2403 $state = MW_COLON_STATE_TEXT
;
2405 $state = MW_COLON_STATE_COMMENT
;
2409 throw new MWException( "State machine error in $fname" );
2413 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2416 wfProfileOut( $fname );
2421 * Return value of a magic variable (like PAGENAME)
2425 function getVariableValue( $index ) {
2426 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2429 * Some of these require message or data lookups and can be
2430 * expensive to check many times.
2432 static $varCache = array();
2433 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2434 if ( isset( $varCache[$index] ) ) {
2435 return $varCache[$index];
2440 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2443 global $wgLocaltimezone;
2444 if ( isset( $wgLocaltimezone ) ) {
2445 $oldtz = getenv( 'TZ' );
2446 putenv( 'TZ='.$wgLocaltimezone );
2449 wfSuppressWarnings(); // E_STRICT system time bitching
2450 $localTimestamp = date( 'YmdHis', $ts );
2451 $localMonth = date( 'm', $ts );
2452 $localMonthName = date( 'n', $ts );
2453 $localDay = date( 'j', $ts );
2454 $localDay2 = date( 'd', $ts );
2455 $localDayOfWeek = date( 'w', $ts );
2456 $localWeek = date( 'W', $ts );
2457 $localYear = date( 'Y', $ts );
2458 $localHour = date( 'H', $ts );
2459 if ( isset( $wgLocaltimezone ) ) {
2460 putenv( 'TZ='.$oldtz );
2462 wfRestoreWarnings();
2465 case 'currentmonth':
2466 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2467 case 'currentmonthname':
2468 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2469 case 'currentmonthnamegen':
2470 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2471 case 'currentmonthabbrev':
2472 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2474 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2476 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2478 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2479 case 'localmonthname':
2480 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2481 case 'localmonthnamegen':
2482 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2483 case 'localmonthabbrev':
2484 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2486 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2488 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2490 return wfEscapeWikiText( $this->mTitle
->getText() );
2492 return $this->mTitle
->getPartialURL();
2493 case 'fullpagename':
2494 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2495 case 'fullpagenamee':
2496 return $this->mTitle
->getPrefixedURL();
2498 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2499 case 'subpagenamee':
2500 return $this->mTitle
->getSubpageUrlForm();
2501 case 'basepagename':
2502 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2503 case 'basepagenamee':
2504 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2505 case 'talkpagename':
2506 if( $this->mTitle
->canTalk() ) {
2507 $talkPage = $this->mTitle
->getTalkPage();
2508 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2512 case 'talkpagenamee':
2513 if( $this->mTitle
->canTalk() ) {
2514 $talkPage = $this->mTitle
->getTalkPage();
2515 return $talkPage->getPrefixedUrl();
2519 case 'subjectpagename':
2520 $subjPage = $this->mTitle
->getSubjectPage();
2521 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2522 case 'subjectpagenamee':
2523 $subjPage = $this->mTitle
->getSubjectPage();
2524 return $subjPage->getPrefixedUrl();
2526 return $this->mRevisionId
;
2528 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2529 case 'revisionday2':
2530 return substr( $this->getRevisionTimestamp(), 6, 2 );
2531 case 'revisionmonth':
2532 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2533 case 'revisionyear':
2534 return substr( $this->getRevisionTimestamp(), 0, 4 );
2535 case 'revisiontimestamp':
2536 return $this->getRevisionTimestamp();
2538 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2540 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2542 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2544 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2545 case 'subjectspace':
2546 return $this->mTitle
->getSubjectNsText();
2547 case 'subjectspacee':
2548 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2549 case 'currentdayname':
2550 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2552 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2554 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2556 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2558 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2559 // int to remove the padding
2560 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2562 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2563 case 'localdayname':
2564 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2566 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2568 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2570 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2572 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2573 // int to remove the padding
2574 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2576 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2577 case 'numberofarticles':
2578 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2579 case 'numberoffiles':
2580 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2581 case 'numberofusers':
2582 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2583 case 'numberofpages':
2584 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2585 case 'numberofadmins':
2586 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2587 case 'numberofedits':
2588 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2589 case 'currenttimestamp':
2590 return $varCache[$index] = wfTimestampNow();
2591 case 'localtimestamp':
2592 return $varCache[$index] = $localTimestamp;
2593 case 'currentversion':
2594 return $varCache[$index] = SpecialVersion
::getVersion();
2600 return $wgServerName;
2602 return $wgScriptPath;
2603 case 'directionmark':
2604 return $wgContLang->getDirMark();
2605 case 'contentlanguage':
2606 global $wgContLanguageCode;
2607 return $wgContLanguageCode;
2610 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2618 * initialise the magic variables (like CURRENTMONTHNAME)
2622 function initialiseVariables() {
2623 $fname = 'Parser::initialiseVariables';
2624 wfProfileIn( $fname );
2625 $variableIDs = MagicWord
::getVariableIDs();
2627 $this->mVariables
= array();
2628 foreach ( $variableIDs as $id ) {
2629 $mw =& MagicWord
::get( $id );
2630 $mw->addToArray( $this->mVariables
, $id );
2632 wfProfileOut( $fname );
2636 * parse any parentheses in format ((title|part|part))
2637 * and call callbacks to get a replacement text for any found piece
2639 * @param string $text The text to parse
2640 * @param array $callbacks rules in form:
2641 * '{' => array( # opening parentheses
2642 * 'end' => '}', # closing parentheses
2643 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2644 * 3 => callback # replacement callback to call if {{{..}}} is found
2647 * 'min' => 2, # Minimum parenthesis count in cb
2648 * 'max' => 3, # Maximum parenthesis count in cb
2651 function replace_callback ($text, $callbacks) {
2652 wfProfileIn( __METHOD__
);
2653 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2654 $lastOpeningBrace = -1; # last not closed parentheses
2656 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2659 while ( $i < strlen( $text ) ) {
2660 # Find next opening brace, closing brace or pipe
2661 if ( $lastOpeningBrace == -1 ) {
2662 $currentClosing = '';
2663 $search = $validOpeningBraces;
2665 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2666 $search = $validOpeningBraces . '|' . $currentClosing;
2669 $i +
= strcspn( $text, $search, $i );
2670 if ( $i < strlen( $text ) ) {
2671 if ( $text[$i] == '|' ) {
2673 } elseif ( $text[$i] == $currentClosing ) {
2675 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2677 $rule = $callbacks[$text[$i]];
2679 # Some versions of PHP have a strcspn which stops on null characters
2680 # Ignore and continue
2689 if ( $found == 'open' ) {
2690 # found opening brace, let's add it to parentheses stack
2691 $piece = array('brace' => $text[$i],
2692 'braceEnd' => $rule['end'],
2696 # count opening brace characters
2697 $piece['count'] = strspn( $text, $piece['brace'], $i );
2698 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2699 $i +
= $piece['count'];
2701 # we need to add to stack only if opening brace count is enough for one of the rules
2702 if ( $piece['count'] >= $rule['min'] ) {
2703 $lastOpeningBrace ++
;
2704 $openingBraceStack[$lastOpeningBrace] = $piece;
2706 } elseif ( $found == 'close' ) {
2707 # lets check if it is enough characters for closing brace
2708 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2709 $count = strspn( $text, $text[$i], $i, $maxCount );
2711 # check for maximum matching characters (if there are 5 closing
2712 # characters, we will probably need only 3 - depending on the rules)
2714 $matchingCallback = null;
2715 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2716 if ( $count > $cbType['max'] ) {
2717 # The specified maximum exists in the callback array, unless the caller
2719 $matchingCount = $cbType['max'];
2721 # Count is less than the maximum
2722 # Skip any gaps in the callback array to find the true largest match
2723 # Need to use array_key_exists not isset because the callback can be null
2724 $matchingCount = $count;
2725 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2730 if ($matchingCount <= 0) {
2734 $matchingCallback = $cbType['cb'][$matchingCount];
2736 # let's set a title or last part (if '|' was found)
2737 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2738 $openingBraceStack[$lastOpeningBrace]['title'] =
2739 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2740 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2742 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2743 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2744 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2748 $pieceEnd = $i +
$matchingCount;
2750 if( is_callable( $matchingCallback ) ) {
2752 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2753 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2754 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2755 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2757 # finally we can call a user callback and replace piece of text
2758 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2759 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2760 $i = $pieceStart +
strlen($replaceWith);
2762 # null value for callback means that parentheses should be parsed, but not replaced
2763 $i +
= $matchingCount;
2766 # reset last opening parentheses, but keep it in case there are unused characters
2767 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2768 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2769 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2772 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2773 $openingBraceStack[$lastOpeningBrace--] = null;
2775 if ($matchingCount < $piece['count']) {
2776 $piece['count'] -= $matchingCount;
2777 $piece['startAt'] -= $matchingCount;
2778 $piece['partStart'] = $piece['startAt'];
2779 # do we still qualify for any callback with remaining count?
2780 $currentCbList = $callbacks[$piece['brace']]['cb'];
2781 while ( $piece['count'] ) {
2782 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2783 $lastOpeningBrace++
;
2784 $openingBraceStack[$lastOpeningBrace] = $piece;
2790 } elseif ( $found == 'pipe' ) {
2791 # lets set a title if it is a first separator, or next part otherwise
2792 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2793 $openingBraceStack[$lastOpeningBrace]['title'] =
2794 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2795 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2796 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2798 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2799 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2800 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2802 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2806 wfProfileOut( __METHOD__
);
2811 * Replace magic variables, templates, and template arguments
2812 * with the appropriate text. Templates are substituted recursively,
2813 * taking care to avoid infinite loops.
2815 * Note that the substitution depends on value of $mOutputType:
2816 * OT_WIKI: only {{subst:}} templates
2817 * OT_MSG: only magic variables
2818 * OT_HTML: all templates and magic variables
2820 * @param string $tex The text to transform
2821 * @param array $args Key-value pairs representing template parameters to substitute
2822 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2825 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2826 # Prevent too big inclusions
2827 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2831 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2832 wfProfileIn( $fname );
2834 # This function is called recursively. To keep track of arguments we need a stack:
2835 array_push( $this->mArgStack
, $args );
2837 $braceCallbacks = array();
2839 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2841 if ( $this->mOutputType
!= OT_MSG
) {
2842 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2844 if ( $braceCallbacks ) {
2848 'cb' => $braceCallbacks,
2849 'min' => $argsOnly ?
3 : 2,
2850 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2854 'cb' => array(2=>null),
2859 $text = $this->replace_callback ($text, $callbacks);
2861 array_pop( $this->mArgStack
);
2863 wfProfileOut( $fname );
2868 * Replace magic variables
2871 function variableSubstitution( $matches ) {
2873 $fname = 'Parser::variableSubstitution';
2874 $varname = $wgContLang->lc($matches[1]);
2875 wfProfileIn( $fname );
2877 if ( $this->mOutputType
== OT_WIKI
) {
2878 # Do only magic variables prefixed by SUBST
2879 $mwSubst =& MagicWord
::get( 'subst' );
2880 if (!$mwSubst->matchStartAndRemove( $varname ))
2882 # Note that if we don't substitute the variable below,
2883 # we don't remove the {{subst:}} magic word, in case
2884 # it is a template rather than a magic variable.
2886 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2887 $id = $this->mVariables
[$varname];
2888 # Now check if we did really match, case sensitive or not
2889 $mw =& MagicWord
::get( $id );
2890 if ($mw->match($matches[1])) {
2891 $text = $this->getVariableValue( $id );
2892 $this->mOutput
->mContainsOldMagic
= true;
2894 $text = $matches[0];
2897 $text = $matches[0];
2899 wfProfileOut( $fname );
2904 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2905 static function createAssocArgs( $args ) {
2906 $assocArgs = array();
2908 foreach( $args as $arg ) {
2909 $eqpos = strpos( $arg, '=' );
2910 if ( $eqpos === false ) {
2911 $assocArgs[$index++
] = $arg;
2913 $name = trim( substr( $arg, 0, $eqpos ) );
2914 $value = trim( substr( $arg, $eqpos+
1 ) );
2915 if ( $value === false ) {
2918 if ( $name !== false ) {
2919 $assocArgs[$name] = $value;
2928 * Return the text of a template, after recursively
2929 * replacing any variables or templates within the template.
2931 * @param array $piece The parts of the template
2932 * $piece['text']: matched text
2933 * $piece['title']: the title, i.e. the part before the |
2934 * $piece['parts']: the parameter array
2935 * @return string the text of the template
2938 function braceSubstitution( $piece ) {
2939 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2940 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2941 wfProfileIn( $fname );
2942 wfProfileIn( __METHOD__
.'-setup' );
2945 $found = false; # $text has been filled
2946 $nowiki = false; # wiki markup in $text should be escaped
2947 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2948 $noargs = false; # Don't replace triple-brace arguments in $text
2949 $replaceHeadings = false; # Make the edit section links go to the template not the article
2950 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2951 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2952 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2954 # Title object, where $text came from
2960 # $part1 is the bit before the first |, and must contain only title characters
2961 # $args is a list of arguments, starting from index 0, not including $part1
2963 $titleText = $part1 = $piece['title'];
2964 # If the third subpattern matched anything, it will start with |
2966 if (null == $piece['parts']) {
2967 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2968 if ($replaceWith != $piece['text']) {
2969 $text = $replaceWith;
2976 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2977 wfProfileOut( __METHOD__
.'-setup' );
2980 wfProfileIn( __METHOD__
.'-modifiers' );
2982 $mwSubst =& MagicWord
::get( 'subst' );
2983 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2984 # One of two possibilities is true:
2985 # 1) Found SUBST but not in the PST phase
2986 # 2) Didn't find SUBST and in the PST phase
2987 # In either case, return without further processing
2988 $text = $piece['text'];
2995 # MSG, MSGNW and RAW
2998 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2999 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3002 # Remove obsolete MSG:
3003 $mwMsg =& MagicWord
::get( 'msg' );
3004 $mwMsg->matchStartAndRemove( $part1 );
3008 $mwRaw =& MagicWord
::get( 'raw' );
3009 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3010 $forceRawInterwiki = true;
3013 wfProfileOut( __METHOD__
.'-modifiers' );
3015 //save path level before recursing into functions & templates.
3016 $lastPathLevel = $this->mTemplatePath
;
3020 wfProfileIn( __METHOD__
. '-pfunc' );
3022 $colonPos = strpos( $part1, ':' );
3023 if ( $colonPos !== false ) {
3024 # Case sensitive functions
3025 $function = substr( $part1, 0, $colonPos );
3026 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3027 $function = $this->mFunctionSynonyms
[1][$function];
3029 # Case insensitive functions
3030 $function = strtolower( $function );
3031 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3032 $function = $this->mFunctionSynonyms
[0][$function];
3038 $funcArgs = array_map( 'trim', $args );
3039 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
3040 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
3043 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3047 if ( is_array( $result ) ) {
3048 if ( isset( $result[0] ) ) {
3049 $text = $linestart . $result[0];
3050 unset( $result[0] );
3053 // Extract flags into the local scope
3054 // This allows callers to set flags such as nowiki, noparse, found, etc.
3057 $text = $linestart . $result;
3061 wfProfileOut( __METHOD__
. '-pfunc' );
3064 # Template table test
3066 # Did we encounter this template already? If yes, it is in the cache
3067 # and we need to check for loops.
3068 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3071 # Infinite loop test
3072 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3076 $text = $linestart .
3077 "[[$part1]]<!-- WARNING: template loop detected -->";
3078 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3080 # set $text to cached message.
3081 $text = $linestart . $this->mTemplates
[$piece['title']];
3082 #treat title for cached page the same as others
3085 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3086 if ($subpage !== '') {
3087 $ns = $this->mTitle
->getNamespace();
3089 $title = Title
::newFromText( $part1, $ns );
3090 //used by include size checking
3091 $titleText = $title->getPrefixedText();
3092 //used by edit section links
3093 $replaceHeadings = true;
3098 # Load from database
3100 wfProfileIn( __METHOD__
. '-loadtpl' );
3102 # declaring $subpage directly in the function call
3103 # does not work correctly with references and breaks
3104 # {{/subpage}}-style inclusions
3106 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3107 if ($subpage !== '') {
3108 $ns = $this->mTitle
->getNamespace();
3110 $title = Title
::newFromText( $part1, $ns );
3113 if ( !is_null( $title ) ) {
3114 $titleText = $title->getPrefixedText();
3115 # Check for language variants if the template is not found
3116 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3117 $wgContLang->findVariantLink($part1, $title);
3120 if ( !$title->isExternal() ) {
3121 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3122 $text = SpecialPage
::capturePath( $title );
3123 if ( is_string( $text ) ) {
3128 $this->disableCache();
3130 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3131 $found = false; //access denied
3132 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3134 list($articleContent,$title) = $this->fetchTemplateAndtitle( $title );
3135 if ( $articleContent !== false ) {
3137 $text = $articleContent;
3138 $replaceHeadings = true;
3142 # If the title is valid but undisplayable, make a link to it
3143 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3144 $text = "[[:$titleText]]";
3147 } elseif ( $title->isTrans() ) {
3148 // Interwiki transclusion
3149 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3150 $text = $this->interwikiTransclude( $title, 'render' );
3154 $text = $this->interwikiTransclude( $title, 'raw' );
3155 $replaceHeadings = true;
3160 # Template cache array insertion
3161 # Use the original $piece['title'] not the mangled $part1, so that
3162 # modifiers such as RAW: produce separate cache entries
3165 // A special page; don't store it in the template cache.
3167 $this->mTemplates
[$piece['title']] = $text;
3169 $text = $linestart . $text;
3172 wfProfileOut( __METHOD__
. '-loadtpl' );
3175 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3176 # Error, oversize inclusion
3177 $text = $linestart .
3178 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3183 # Recursive parsing, escaping and link table handling
3184 # Only for HTML output
3185 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3186 $text = wfEscapeWikiText( $text );
3187 } elseif ( !$this->ot
['msg'] && $found ) {
3189 $assocArgs = array();
3191 # Clean up argument array
3192 $assocArgs = self
::createAssocArgs($args);
3193 # Add a new element to the templace recursion path
3194 $this->mTemplatePath
[$part1] = 1;
3198 # If there are any <onlyinclude> tags, only include them
3199 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3200 $replacer = new OnlyIncludeReplacer
;
3201 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3202 array( &$replacer, 'replace' ), $text );
3203 $text = $replacer->output
;
3205 # Remove <noinclude> sections and <includeonly> tags
3206 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3207 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3209 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3210 # Strip <nowiki>, <pre>, etc.
3211 $text = $this->strip( $text, $this->mStripState
);
3212 if ( $this->ot
['html'] ) {
3213 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3214 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3215 $text = Sanitizer
::removeHTMLcomments( $text );
3218 $text = $this->replaceVariables( $text, $assocArgs );
3220 # If the template begins with a table or block-level
3221 # element, it should be treated as beginning a new line.
3222 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3223 $text = "\n" . $text;
3225 } elseif ( !$noargs ) {
3226 # $noparse and !$noargs
3227 # Just replace the arguments, not any double-brace items
3228 # This is used for rendered interwiki transclusion
3229 $text = $this->replaceVariables( $text, $assocArgs, true );
3232 # Prune lower levels off the recursion check path
3233 $this->mTemplatePath
= $lastPathLevel;
3235 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3236 # Error, oversize inclusion
3237 $text = $linestart .
3238 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3244 wfProfileOut( $fname );
3245 return $piece['text'];
3247 wfProfileIn( __METHOD__
. '-placeholders' );
3249 # Replace raw HTML by a placeholder
3250 # Add a blank line preceding, to prevent it from mucking up
3251 # immediately preceding headings
3252 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3254 # replace ==section headers==
3255 # XXX this needs to go away once we have a better parser.
3256 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3257 if( !is_null( $title ) )
3258 $encodedname = base64_encode($title->getPrefixedDBkey());
3260 $encodedname = base64_encode("");
3261 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3262 PREG_SPLIT_DELIM_CAPTURE
);
3264 $nsec = $headingOffset;
3266 for( $i = 0; $i < count($m); $i +
= 2 ) {
3268 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3270 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3275 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3276 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3277 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3283 wfProfileOut( __METHOD__
. '-placeholders' );
3286 # Prune lower levels off the recursion check path
3287 $this->mTemplatePath
= $lastPathLevel;
3290 wfProfileOut( $fname );
3291 return $piece['text'];
3293 wfProfileOut( $fname );
3299 * Fetch the unparsed text of a template and register a reference to it.
3301 function fetchTemplateAndtitle( $title ) {
3302 $text = $skip = false;
3303 $finalTitle = $title;
3304 // Loop to fetch the article, with up to 1 redirect
3305 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3306 # Give extensions a chance to select the revision instead
3307 $id = false; // Assume current
3308 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( &$this, &$title, &$skip, &$id ) );
3312 $this->mOutput
->addTemplate( $title, $title->getArticleID(), null );
3315 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3316 $rev_id = $rev ?
$rev->getId() : 0;
3318 $this->mOutput
->addTemplate( $title, $title->getArticleID(), $rev_id );
3321 $text = $rev->getText();
3322 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3324 $message = $wgLang->lcfirst( $title->getText() );
3325 $text = wfMsgForContentNoTrans( $message );
3326 if( wfEmptyMsg( $message, $text ) ) {
3333 if ( $text === false ) {
3337 $finalTitle = $title;
3338 $title = Title
::newFromRedirect( $text );
3340 return array($text,$finalTitle);
3343 function fetchTemplate( $title ) {
3344 $rv = $this->fetchTemplateAndtitle($title);
3349 * Transclude an interwiki link.
3351 function interwikiTransclude( $title, $action ) {
3352 global $wgEnableScaryTranscluding;
3354 if (!$wgEnableScaryTranscluding)
3355 return wfMsg('scarytranscludedisabled');
3357 $url = $title->getFullUrl( "action=$action" );
3359 if (strlen($url) > 255)
3360 return wfMsg('scarytranscludetoolong');
3361 return $this->fetchScaryTemplateMaybeFromCache($url);
3364 function fetchScaryTemplateMaybeFromCache($url) {
3365 global $wgTranscludeCacheExpiry;
3366 $dbr = wfGetDB(DB_SLAVE
);
3367 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3368 array('tc_url' => $url));
3370 $time = $obj->tc_time
;
3371 $text = $obj->tc_contents
;
3372 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3377 $text = Http
::get($url);
3379 return wfMsg('scarytranscludefailed', $url);
3381 $dbw = wfGetDB(DB_MASTER
);
3382 $dbw->replace('transcache', array('tc_url'), array(
3384 'tc_time' => time(),
3385 'tc_contents' => $text));
3391 * Triple brace replacement -- used for template arguments
3394 function argSubstitution( $matches ) {
3395 $arg = trim( $matches['title'] );
3396 $text = $matches['text'];
3397 $inputArgs = end( $this->mArgStack
);
3399 if ( array_key_exists( $arg, $inputArgs ) ) {
3400 $text = $inputArgs[$arg];
3401 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3402 null != $matches['parts'] && count($matches['parts']) > 0) {
3403 $text = $matches['parts'][0];
3405 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3406 $text = $matches['text'] .
3407 '<!-- WARNING: argument omitted, expansion size too large -->';
3414 * Increment an include size counter
3416 * @param string $type The type of expansion
3417 * @param integer $size The size of the text
3418 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3420 function incrementIncludeSize( $type, $size ) {
3421 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3424 $this->mIncludeSizes
[$type] +
= $size;
3430 * Detect __NOGALLERY__ magic word and set a placeholder
3432 function stripNoGallery( &$text ) {
3433 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3435 $mw = MagicWord
::get( 'nogallery' );
3436 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3440 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3441 * placeholder that will then be replaced by the real TOC in
3442 * ->formatHeadings, this works because at this points real
3443 * comments will have already been discarded by the sanitizer.
3445 * Any additional __TOC__ magic words left over will be discarded
3446 * as there can only be one TOC on the page.
3448 function stripToc( $text ) {
3449 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3451 $mw = MagicWord
::get( 'notoc' );
3452 if( $mw->matchAndRemove( $text ) ) {
3453 $this->mShowToc
= false;
3456 $mw = MagicWord
::get( 'toc' );
3457 if( $mw->match( $text ) ) {
3458 $this->mShowToc
= true;
3459 $this->mForceTocPosition
= true;
3461 // Set a placeholder. At the end we'll fill it in with the TOC.
3462 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3464 // Only keep the first one.
3465 $text = $mw->replace( '', $text );
3471 * This function accomplishes several tasks:
3472 * 1) Auto-number headings if that option is enabled
3473 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3474 * 3) Add a Table of contents on the top for users who have enabled the option
3475 * 4) Auto-anchor headings
3477 * It loops through all headlines, collects the necessary data, then splits up the
3478 * string and re-inserts the newly formatted headlines.
3480 * @param string $text
3481 * @param boolean $isMain
3484 function formatHeadings( $text, $isMain=true ) {
3485 global $wgMaxTocLevel, $wgContLang;
3487 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3488 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3491 $showEditLink = $this->mOptions
->getEditSection();
3494 # Inhibit editsection links if requested in the page
3495 $esw =& MagicWord
::get( 'noeditsection' );
3496 if( $esw->matchAndRemove( $text ) ) {
3500 # Get all headlines for numbering them and adding funky stuff like [edit]
3501 # links - this is for later, but we need the number of headlines right now
3503 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3505 # if there are fewer than 4 headlines in the article, do not show TOC
3506 # unless it's been explicitly enabled.
3507 $enoughToc = $this->mShowToc
&&
3508 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3510 # Allow user to stipulate that a page should have a "new section"
3511 # link added via __NEWSECTIONLINK__
3512 $mw =& MagicWord
::get( 'newsectionlink' );
3513 if( $mw->matchAndRemove( $text ) )
3514 $this->mOutput
->setNewSection( true );
3516 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3517 # override above conditions and always show TOC above first header
3518 $mw =& MagicWord
::get( 'forcetoc' );
3519 if ($mw->matchAndRemove( $text ) ) {
3520 $this->mShowToc
= true;
3524 # We need this to perform operations on the HTML
3525 $sk = $this->mOptions
->getSkin();
3529 $sectionCount = 0; # headlineCount excluding template sections
3532 # Ugh .. the TOC should have neat indentation levels which can be
3533 # passed to the skin functions. These are determined here
3537 $sublevelCount = array();
3538 $levelCount = array();
3545 foreach( $matches[3] as $headline ) {
3547 $templatetitle = '';
3548 $templatesection = 0;
3551 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3553 $templatetitle = base64_decode($mat[1]);
3554 $templatesection = 1 +
(int)base64_decode($mat[2]);
3555 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3559 $prevlevel = $level;
3560 $prevtoclevel = $toclevel;
3562 $level = $matches[1][$headlineCount];
3564 if( $doNumberHeadings ||
$enoughToc ) {
3566 if ( $level > $prevlevel ) {
3567 # Increase TOC level
3569 $sublevelCount[$toclevel] = 0;
3570 if( $toclevel<$wgMaxTocLevel ) {
3571 $prevtoclevel = $toclevel;
3572 $toc .= $sk->tocIndent();
3576 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3577 # Decrease TOC level, find level to jump to
3579 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3580 # Can only go down to level 1
3583 for ($i = $toclevel; $i > 0; $i--) {
3584 if ( $levelCount[$i] == $level ) {
3585 # Found last matching level
3589 elseif ( $levelCount[$i] < $level ) {
3590 # Found first matching level below current level
3596 if( $toclevel<$wgMaxTocLevel ) {
3597 if($prevtoclevel < $wgMaxTocLevel) {
3598 # Unindent only if the previous toc level was shown :p
3599 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3601 $toc .= $sk->tocLineEnd();
3606 # No change in level, end TOC line
3607 if( $toclevel<$wgMaxTocLevel ) {
3608 $toc .= $sk->tocLineEnd();
3612 $levelCount[$toclevel] = $level;
3614 # count number of headlines for each level
3615 @$sublevelCount[$toclevel]++
;
3617 for( $i = 1; $i <= $toclevel; $i++
) {
3618 if( !empty( $sublevelCount[$i] ) ) {
3622 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3628 # The canonized header is a version of the header text safe to use for links
3629 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3630 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3632 # Remove link placeholders by the link text.
3633 # <!--LINK number-->
3635 # link text with suffix
3636 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3637 "\$this->mLinkHolders['texts'][\$1]",
3638 $canonized_headline );
3639 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3640 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3641 $canonized_headline );
3644 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3645 $tocline = trim( $canonized_headline );
3646 # Save headline for section edit hint before it's escaped
3647 $headline_hint = trim( $canonized_headline );
3648 $canonized_headline = Sanitizer
::escapeId( $tocline );
3649 $refers[$headlineCount] = $canonized_headline;
3651 # count how many in assoc. array so we can track dupes in anchors
3652 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3653 $refcount[$headlineCount]=$refers[$canonized_headline];
3655 # Don't number the heading if it is the only one (looks silly)
3656 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3657 # the two are different if the line contains a link
3658 $headline=$numbering . ' ' . $headline;
3661 # Create the anchor for linking from the TOC to the section
3662 $anchor = $canonized_headline;
3663 if($refcount[$headlineCount] > 1 ) {
3664 $anchor .= '_' . $refcount[$headlineCount];
3666 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3667 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3669 # give headline the correct <h#> tag
3670 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3672 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3674 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3678 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3685 # Never ever show TOC if no headers
3686 if( $numVisible < 1 ) {
3691 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3692 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3694 $toc = $sk->tocList( $toc );
3697 # split up and insert constructed headlines
3699 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3702 foreach( $blocks as $block ) {
3703 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3704 # This is the [edit] link that appears for the top block of text when
3705 # section editing is enabled
3707 # Disabled because it broke block formatting
3708 # For example, a bullet point in the top line
3709 # $full .= $sk->editSectionLink(0);
3712 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3713 # Top anchor now in skin
3717 if( !empty( $head[$i] ) ) {
3722 if( $this->mForceTocPosition
) {
3723 return str_replace( '<!--MWTOC-->', $toc, $full );
3730 * Transform wiki markup when saving a page by doing \r\n -> \n
3731 * conversion, substitting signatures, {{subst:}} templates, etc.
3733 * @param string $text the text to transform
3734 * @param Title &$title the Title object for the current article
3735 * @param User &$user the User object describing the current user
3736 * @param ParserOptions $options parsing options
3737 * @param bool $clearState whether to clear the parser state first
3738 * @return string the altered wiki markup
3741 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3742 $this->mOptions
= $options;
3743 $this->mTitle
=& $title;
3744 $this->setOutputType( OT_WIKI
);
3746 if ( $clearState ) {
3747 $this->clearState();
3750 $stripState = new StripState
;
3754 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3755 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3756 $text = $this->pstPass2( $text, $stripState, $user );
3757 $text = $stripState->unstripBoth( $text );
3762 * Pre-save transform helper function
3765 function pstPass2( $text, &$stripState, $user ) {
3766 global $wgContLang, $wgLocaltimezone;
3768 /* Note: This is the timestamp saved as hardcoded wikitext to
3769 * the database, we use $wgContLang here in order to give
3770 * everyone the same signature and use the default one rather
3771 * than the one selected in each user's preferences.
3773 if ( isset( $wgLocaltimezone ) ) {
3774 $oldtz = getenv( 'TZ' );
3775 putenv( 'TZ='.$wgLocaltimezone );
3777 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3778 ' (' . date( 'T' ) . ')';
3779 if ( isset( $wgLocaltimezone ) ) {
3780 putenv( 'TZ='.$oldtz );
3783 # Variable replacement
3784 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3785 $text = $this->replaceVariables( $text );
3787 # Strip out <nowiki> etc. added via replaceVariables
3788 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3791 $sigText = $this->getUserSig( $user );
3792 $text = strtr( $text, array(
3794 '~~~~' => "$sigText $d",
3798 # Context links: [[|name]] and [[name (context)|]]
3800 global $wgLegalTitleChars;
3801 $tc = "[$wgLegalTitleChars]";
3802 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3804 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3805 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3806 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3808 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3809 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3810 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3812 $t = $this->mTitle
->getText();
3814 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3815 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3816 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3817 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3819 # if there's no context, don't bother duplicating the title
3820 $text = preg_replace( $p2, '[[\\1]]', $text );
3823 # Trim trailing whitespace
3824 $text = rtrim( $text );
3830 * Fetch the user's signature text, if any, and normalize to
3831 * validated, ready-to-insert wikitext.
3837 function getUserSig( &$user ) {
3838 global $wgMaxSigChars;
3840 $username = $user->getName();
3841 $nickname = $user->getOption( 'nickname' );
3842 $nickname = $nickname === '' ?
$username : $nickname;
3844 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3845 $nickname = $username;
3846 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3847 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3848 # Sig. might contain markup; validate this
3849 if( $this->validateSig( $nickname ) !== false ) {
3850 # Validated; clean up (if needed) and return it
3851 return $this->cleanSig( $nickname, true );
3853 # Failed to validate; fall back to the default
3854 $nickname = $username;
3855 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3859 // Make sure nickname doesnt get a sig in a sig
3860 $nickname = $this->cleanSigInSig( $nickname );
3862 # If we're still here, make it a link to the user page
3863 $userpage = $user->getUserPage();
3864 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3868 * Check that the user's signature contains no bad XML
3870 * @param string $text
3871 * @return mixed An expanded string, or false if invalid.
3873 function validateSig( $text ) {
3874 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3878 * Clean up signature text
3880 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3881 * 2) Substitute all transclusions
3883 * @param string $text
3884 * @param $parsing Whether we're cleaning (preferences save) or parsing
3885 * @return string Signature text
3887 function cleanSig( $text, $parsing = false ) {
3889 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3891 $substWord = MagicWord
::get( 'subst' );
3892 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3893 $substText = '{{' . $substWord->getSynonym( 0 );
3895 $text = preg_replace( $substRegex, $substText, $text );
3896 $text = $this->cleanSigInSig( $text );
3897 $text = $this->replaceVariables( $text );
3899 $this->clearState();
3904 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3905 * @param string $text
3906 * @return string Signature text with /~{3,5}/ removed
3908 function cleanSigInSig( $text ) {
3909 $text = preg_replace( '/~{3,5}/', '', $text );
3914 * Set up some variables which are usually set up in parse()
3915 * so that an external function can call some class members with confidence
3918 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3919 $this->mTitle
=& $title;
3920 $this->mOptions
= $options;
3921 $this->setOutputType( $outputType );
3922 if ( $clearState ) {
3923 $this->clearState();
3928 * Transform a MediaWiki message by replacing magic variables.
3930 * @param string $text the text to transform
3931 * @param ParserOptions $options options
3932 * @return string the text with variables substituted
3935 function transformMsg( $text, $options ) {
3937 static $executing = false;
3939 $fname = "Parser::transformMsg";
3941 # Guard against infinite recursion
3947 wfProfileIn($fname);
3949 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3950 $this->mTitle
= $wgTitle;
3952 $this->mTitle
= Title
::newFromText('msg');
3954 $this->mOptions
= $options;
3955 $this->setOutputType( OT_MSG
);
3956 $this->clearState();
3957 $text = $this->replaceVariables( $text );
3960 wfProfileOut($fname);
3965 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3966 * The callback should have the following form:
3967 * function myParserHook( $text, $params, &$parser ) { ... }
3969 * Transform and return $text. Use $parser for any required context, e.g. use
3970 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3974 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3975 * @param mixed $callback The callback function (and object) to use for the tag
3977 * @return The old value of the mTagHooks array associated with the hook
3979 function setHook( $tag, $callback ) {
3980 $tag = strtolower( $tag );
3981 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3982 $this->mTagHooks
[$tag] = $callback;
3987 function setTransparentTagHook( $tag, $callback ) {
3988 $tag = strtolower( $tag );
3989 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3990 $this->mTransparentTagHooks
[$tag] = $callback;
3996 * Create a function, e.g. {{sum:1|2|3}}
3997 * The callback function should have the form:
3998 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4000 * The callback may either return the text result of the function, or an array with the text
4001 * in element 0, and a number of flags in the other elements. The names of the flags are
4002 * specified in the keys. Valid flags are:
4003 * found The text returned is valid, stop processing the template. This
4005 * nowiki Wiki markup in the return value should be escaped
4006 * noparse Unsafe HTML tags should not be stripped, etc.
4007 * noargs Don't replace triple-brace arguments in the return value
4008 * isHTML The returned text is HTML, armour it against wikitext transformation
4012 * @param string $id The magic word ID
4013 * @param mixed $callback The callback function (and object) to use
4014 * @param integer $flags a combination of the following flags:
4015 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4017 * @return The old callback function for this name, if any
4019 function setFunctionHook( $id, $callback, $flags = 0 ) {
4020 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
4021 $this->mFunctionHooks
[$id] = $callback;
4023 # Add to function cache
4024 $mw = MagicWord
::get( $id );
4026 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4028 $synonyms = $mw->getSynonyms();
4029 $sensitive = intval( $mw->isCaseSensitive() );
4031 foreach ( $synonyms as $syn ) {
4033 if ( !$sensitive ) {
4034 $syn = strtolower( $syn );
4037 if ( !( $flags & SFH_NO_HASH
) ) {
4040 # Remove trailing colon
4041 if ( substr( $syn, -1, 1 ) == ':' ) {
4042 $syn = substr( $syn, 0, -1 );
4044 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4050 * Get all registered function hook identifiers
4054 function getFunctionHooks() {
4055 return array_keys( $this->mFunctionHooks
);
4059 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4060 * Placeholders created in Skin::makeLinkObj()
4061 * Returns an array of links found, indexed by PDBK:
4065 * $options is a bit field, RLH_FOR_UPDATE to select for update
4067 function replaceLinkHolders( &$text, $options = 0 ) {
4071 $fname = 'Parser::replaceLinkHolders';
4072 wfProfileIn( $fname );
4076 $sk = $this->mOptions
->getSkin();
4077 $linkCache =& LinkCache
::singleton();
4079 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4080 wfProfileIn( $fname.'-check' );
4081 $dbr = wfGetDB( DB_SLAVE
);
4082 $page = $dbr->tableName( 'page' );
4083 $threshold = $wgUser->getOption('stubthreshold');
4086 asort( $this->mLinkHolders
['namespaces'] );
4091 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4093 $title = $this->mLinkHolders
['titles'][$key];
4095 # Skip invalid entries.
4096 # Result will be ugly, but prevents crash.
4097 if ( is_null( $title ) ) {
4100 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4102 # Check if it's a static known link, e.g. interwiki
4103 if ( $title->isAlwaysKnown() ) {
4104 $colours[$pdbk] = 1;
4105 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4106 $colours[$pdbk] = 1;
4107 $this->mOutput
->addLink( $title, $id );
4108 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4109 $colours[$pdbk] = 0;
4110 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4111 $colours[$pdbk] = 0;
4113 # Not in the link cache, add it to the query
4114 if ( !isset( $current ) ) {
4116 $query = "SELECT page_id, page_namespace, page_title";
4117 if ( $threshold > 0 ) {
4118 $query .= ', page_len, page_is_redirect';
4120 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4121 } elseif ( $current != $ns ) {
4123 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4128 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4133 if ( $options & RLH_FOR_UPDATE
) {
4134 $query .= ' FOR UPDATE';
4137 $res = $dbr->query( $query, $fname );
4139 # Fetch data and form into an associative array
4140 # non-existent = broken
4143 while ( $s = $dbr->fetchObject($res) ) {
4144 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4145 $pdbk = $title->getPrefixedDBkey();
4146 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4147 $this->mOutput
->addLink( $title, $s->page_id
);
4149 $colours[$pdbk] = ( $threshold == 0 ||
(
4150 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4151 $s->page_is_redirect ||
4152 !Namespace::isContent( $s->page_namespace
) )
4156 wfProfileOut( $fname.'-check' );
4158 # Do a second query for different language variants of links and categories
4159 if($wgContLang->hasVariants()){
4160 $linkBatch = new LinkBatch();
4161 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4162 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4163 $varCategories = array(); // category replacements oldDBkey => newDBkey
4165 $categories = $this->mOutput
->getCategoryLinks();
4167 // Add variants of links to link batch
4168 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4169 $title = $this->mLinkHolders
['titles'][$key];
4170 if ( is_null( $title ) )
4173 $pdbk = $title->getPrefixedDBkey();
4174 $titleText = $title->getText();
4176 // generate all variants of the link title text
4177 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4179 // if link was not found (in first query), add all variants to query
4180 if ( !isset($colours[$pdbk]) ){
4181 foreach($allTextVariants as $textVariant){
4182 if($textVariant != $titleText){
4183 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4184 if(is_null($variantTitle)) continue;
4185 $linkBatch->addObj( $variantTitle );
4186 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4192 // process categories, check if a category exists in some variant
4193 foreach( $categories as $category ){
4194 $variants = $wgContLang->convertLinkToAllVariants($category);
4195 foreach($variants as $variant){
4196 if($variant != $category){
4197 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4198 if(is_null($variantTitle)) continue;
4199 $linkBatch->addObj( $variantTitle );
4200 $categoryMap[$variant] = $category;
4206 if(!$linkBatch->isEmpty()){
4208 $titleClause = $linkBatch->constructSet('page', $dbr);
4210 $variantQuery = "SELECT page_id, page_namespace, page_title";
4211 if ( $threshold > 0 ) {
4212 $variantQuery .= ', page_len, page_is_redirect';
4215 $variantQuery .= " FROM $page WHERE $titleClause";
4216 if ( $options & RLH_FOR_UPDATE
) {
4217 $variantQuery .= ' FOR UPDATE';
4220 $varRes = $dbr->query( $variantQuery, $fname );
4222 // for each found variants, figure out link holders and replace
4223 while ( $s = $dbr->fetchObject($varRes) ) {
4225 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4226 $varPdbk = $variantTitle->getPrefixedDBkey();
4227 $vardbk = $variantTitle->getDBkey();
4229 $holderKeys = array();
4230 if(isset($variantMap[$varPdbk])){
4231 $holderKeys = $variantMap[$varPdbk];
4232 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4233 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4236 // loop over link holders
4237 foreach($holderKeys as $key){
4238 $title = $this->mLinkHolders
['titles'][$key];
4239 if ( is_null( $title ) ) continue;
4241 $pdbk = $title->getPrefixedDBkey();
4243 if(!isset($colours[$pdbk])){
4244 // found link in some of the variants, replace the link holder data
4245 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4246 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4248 // set pdbk and colour
4249 $pdbks[$key] = $varPdbk;
4250 if ( $threshold > 0 ) {
4251 $size = $s->page_len
;
4252 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4253 $colours[$varPdbk] = 1;
4255 $colours[$varPdbk] = 2;
4259 $colours[$varPdbk] = 1;
4264 // check if the object is a variant of a category
4265 if(isset($categoryMap[$vardbk])){
4266 $oldkey = $categoryMap[$vardbk];
4267 if($oldkey != $vardbk)
4268 $varCategories[$oldkey]=$vardbk;
4272 // rebuild the categories in original order (if there are replacements)
4273 if(count($varCategories)>0){
4275 $originalCats = $this->mOutput
->getCategories();
4276 foreach($originalCats as $cat => $sortkey){
4277 // make the replacement
4278 if( array_key_exists($cat,$varCategories) )
4279 $newCats[$varCategories[$cat]] = $sortkey;
4280 else $newCats[$cat] = $sortkey;
4282 $this->mOutput
->setCategoryLinks($newCats);
4287 # Construct search and replace arrays
4288 wfProfileIn( $fname.'-construct' );
4289 $replacePairs = array();
4290 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4291 $pdbk = $pdbks[$key];
4292 $searchkey = "<!--LINK $key-->";
4293 $title = $this->mLinkHolders
['titles'][$key];
4294 if ( empty( $colours[$pdbk] ) ) {
4295 $linkCache->addBadLinkObj( $title );
4296 $colours[$pdbk] = 0;
4297 $this->mOutput
->addLink( $title, 0 );
4298 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4299 $this->mLinkHolders
['texts'][$key],
4300 $this->mLinkHolders
['queries'][$key] );
4301 } elseif ( $colours[$pdbk] == 1 ) {
4302 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4303 $this->mLinkHolders
['texts'][$key],
4304 $this->mLinkHolders
['queries'][$key] );
4305 } elseif ( $colours[$pdbk] == 2 ) {
4306 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4307 $this->mLinkHolders
['texts'][$key],
4308 $this->mLinkHolders
['queries'][$key] );
4311 $replacer = new HashtableReplacer( $replacePairs, 1 );
4312 wfProfileOut( $fname.'-construct' );
4315 wfProfileIn( $fname.'-replace' );
4316 $text = preg_replace_callback(
4317 '/(<!--LINK .*?-->)/',
4321 wfProfileOut( $fname.'-replace' );
4324 # Now process interwiki link holders
4325 # This is quite a bit simpler than internal links
4326 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4327 wfProfileIn( $fname.'-interwiki' );
4328 # Make interwiki link HTML
4329 $replacePairs = array();
4330 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4331 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4332 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4334 $replacer = new HashtableReplacer( $replacePairs, 1 );
4336 $text = preg_replace_callback(
4337 '/<!--IWLINK (.*?)-->/',
4340 wfProfileOut( $fname.'-interwiki' );
4343 wfProfileOut( $fname );
4348 * Replace <!--LINK--> link placeholders with plain text of links
4349 * (not HTML-formatted).
4350 * @param string $text
4353 function replaceLinkHoldersText( $text ) {
4354 $fname = 'Parser::replaceLinkHoldersText';
4355 wfProfileIn( $fname );
4357 $text = preg_replace_callback(
4358 '/<!--(LINK|IWLINK) (.*?)-->/',
4359 array( &$this, 'replaceLinkHoldersTextCallback' ),
4362 wfProfileOut( $fname );
4367 * @param array $matches
4371 function replaceLinkHoldersTextCallback( $matches ) {
4372 $type = $matches[1];
4374 if( $type == 'LINK' ) {
4375 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4376 return $this->mLinkHolders
['texts'][$key];
4378 } elseif( $type == 'IWLINK' ) {
4379 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4380 return $this->mInterwikiLinkHolders
['texts'][$key];
4387 * Tag hook handler for 'pre'.
4389 function renderPreTag( $text, $attribs ) {
4390 // Backwards-compatibility hack
4391 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4393 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4394 return wfOpenElement( 'pre', $attribs ) .
4395 Xml
::escapeTagsOnly( $content ) .
4400 * Renders an image gallery from a text with one line per image.
4401 * text labels may be given by using |-style alternative text. E.g.
4402 * Image:one.jpg|The number "1"
4403 * Image:tree.jpg|A tree
4404 * given as text will return the HTML of a gallery with two images,
4405 * labeled 'The number "1"' and
4408 function renderImageGallery( $text, $params ) {
4409 $ig = new ImageGallery();
4410 $ig->setContextTitle( $this->mTitle
);
4411 $ig->setShowBytes( false );
4412 $ig->setShowFilename( false );
4414 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4415 $ig->useSkin( $this->mOptions
->getSkin() );
4416 $ig->mRevisionId
= $this->mRevisionId
;
4418 if( isset( $params['caption'] ) ) {
4419 $caption = $params['caption'];
4420 $caption = htmlspecialchars( $caption );
4421 $caption = $this->replaceInternalLinks( $caption );
4422 $ig->setCaptionHtml( $caption );
4424 if( isset( $params['perrow'] ) ) {
4425 $ig->setPerRow( $params['perrow'] );
4427 if( isset( $params['widths'] ) ) {
4428 $ig->setWidths( $params['widths'] );
4430 if( isset( $params['heights'] ) ) {
4431 $ig->setHeights( $params['heights'] );
4434 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4436 $lines = explode( "\n", $text );
4437 foreach ( $lines as $line ) {
4438 # match lines like these:
4439 # Image:someimage.jpg|This is some image
4441 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4443 if ( count( $matches ) == 0 ) {
4446 $tp = Title
::newFromText( $matches[1] );
4448 if( is_null( $nt ) ) {
4449 # Bogus title. Ignore these so we don't bomb out later.
4452 if ( isset( $matches[3] ) ) {
4453 $label = $matches[3];
4458 $pout = $this->parse( $label,
4461 false, // Strip whitespace...?
4462 false // Don't clear state!
4464 $html = $pout->getText();
4466 $ig->add( $nt, $html );
4468 # Only add real images (bug #5586)
4469 if ( $nt->getNamespace() == NS_IMAGE
) {
4470 $this->mOutput
->addImage( $nt->getDBkey() );
4473 return $ig->toHTML();
4477 * Parse image options text and use it to make an image
4479 function makeImage( $nt, $options ) {
4480 # @TODO: let the MediaHandler specify its transform parameters
4482 # Check if the options text is of the form "options|alt text"
4484 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4485 # * left no resizing, just left align. label is used for alt= only
4486 # * right same, but right aligned
4487 # * none same, but not aligned
4488 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4489 # * center center the image
4490 # * framed Keep original image size, no magnify-button.
4491 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4492 # * upright reduce width for upright images, rounded to full __0 px
4493 # * border draw a 1px border around the image
4494 # vertical-align values (no % or length right now):
4505 $part = array_map( 'trim', explode( '|', $options) );
4508 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4509 foreach ( $alignments as $alignment ) {
4510 $mwAlign[$alignment] =& MagicWord
::get( 'img_'.$alignment );
4512 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4513 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4514 $mwWidth =& MagicWord
::get( 'img_width' );
4515 $mwFramed =& MagicWord
::get( 'img_framed' );
4516 $mwFrameless =& MagicWord
::get( 'img_frameless' );
4517 $mwUpright =& MagicWord
::get( 'img_upright' );
4518 $mwBorder =& MagicWord
::get( 'img_border' );
4519 $mwPage =& MagicWord
::get( 'img_page' );
4523 $framed = $thumb = false;
4524 $manual_thumb = '' ;
4525 $align = $valign = '';
4526 $sk = $this->mOptions
->getSkin();
4528 foreach( $part as $val ) {
4529 if ( !is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4531 } elseif ( !is_null( $match = $mwUpright->matchVariableStartToEnd( $val ) ) ) {
4532 $params['upright'] = true;
4533 $params['upright_factor'] = floatval( $match );
4534 } elseif ( !is_null( $match = $mwFrameless->matchVariableStartToEnd( $val ) ) ) {
4535 $params['frameless'] = true;
4536 } elseif ( !is_null( $mwBorder->matchVariableStartToEnd( $val ) ) ) {
4537 $params['border'] = true;
4538 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4539 # use manually specified thumbnail
4541 $manual_thumb = $match;
4543 foreach( $alignments as $alignment ) {
4544 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4545 switch ( $alignment ) {
4546 case 'left': case 'right': case 'center': case 'none':
4547 $align = $alignment; break;
4549 $valign = $alignment;
4554 if ( ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4555 # Select a page in a multipage document
4556 $params['page'] = $match;
4557 } elseif ( !isset( $params['width'] ) && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4558 wfDebug( "img_width match: $match\n" );
4559 # $match is the image width in pixels
4561 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4562 $params['width'] = intval( $m[1] );
4563 $params['height'] = intval( $m[2] );
4565 $params['width'] = intval($match);
4567 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4574 # Strip bad stuff out of the alt text
4575 $alt = $this->replaceLinkHoldersText( $caption );
4577 # make sure there are no placeholders in thumbnail attributes
4578 # that are later expanded to html- so expand them now and
4580 $alt = $this->mStripState
->unstripBoth( $alt );
4581 $alt = Sanitizer
::stripAllTags( $alt );
4583 # Give extensions a chance to select the file revision for us
4584 $skip = $time = false;
4585 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
4587 # Linker does the rest
4589 $link = $sk->makeLinkObj( $nt );
4591 $link = $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $params, $framed, $thumb, $manual_thumb, $valign, $time );
4598 * Set a flag in the output object indicating that the content is dynamic and
4599 * shouldn't be cached.
4601 function disableCache() {
4602 wfDebug( "Parser output marked as uncacheable.\n" );
4603 $this->mOutput
->mCacheTime
= -1;
4607 * Callback from the Sanitizer for expanding items found in HTML attribute
4608 * values, so they can be safely tested and escaped.
4609 * @param string $text
4610 * @param array $args
4614 function attributeStripCallback( &$text, $args ) {
4615 $text = $this->replaceVariables( $text, $args );
4616 $text = $this->mStripState
->unstripBoth( $text );
4625 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4626 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4627 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4633 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4638 * Break wikitext input into sections, and either pull or replace
4639 * some particular section's text.
4641 * External callers should use the getSection and replaceSection methods.
4643 * @param $text Page wikitext
4644 * @param $section Numbered section. 0 pulls the text before the first
4645 * heading; other numbers will pull the given section
4646 * along with its lower-level subsections.
4647 * @param $mode One of "get" or "replace"
4648 * @param $newtext Replacement text for section data.
4649 * @return string for "get", the extracted section text.
4650 * for "replace", the whole page with the section replaced.
4652 private function extractSections( $text, $section, $mode, $newtext='' ) {
4653 # I.... _hope_ this is right.
4654 # Otherwise, sometimes we don't have things initialized properly.
4655 $this->clearState();
4657 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4658 # comments to be stripped as well)
4659 $stripState = new StripState
;
4661 $oldOutputType = $this->mOutputType
;
4662 $oldOptions = $this->mOptions
;
4663 $this->mOptions
= new ParserOptions();
4664 $this->setOutputType( OT_WIKI
);
4666 $striptext = $this->strip( $text, $stripState, true );
4668 $this->setOutputType( $oldOutputType );
4669 $this->mOptions
= $oldOptions;
4671 # now that we can be sure that no pseudo-sections are in the source,
4672 # split it up by section
4673 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4674 $comment = "(?:$uniq-!--.*?QINU\x07)";
4679 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4680 (=+) # Should this be limited to 6?
4681 .+? # Section title...
4682 \\2 # Ending = count must match start
4683 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4692 PREG_SPLIT_DELIM_CAPTURE
);
4694 if( $mode == "get" ) {
4695 if( $section == 0 ) {
4696 // "Section 0" returns the content before any other section.
4699 //track missing section, will replace if found.
4702 } elseif( $mode == "replace" ) {
4703 if( $section == 0 ) {
4704 $rv = $newtext . "\n\n";
4713 for( $index = 1; $index < count( $secs ); ) {
4714 $headerLine = $secs[$index++
];
4715 if( $secs[$index] ) {
4717 $headerLevel = strlen( $secs[$index++
] );
4721 $headerLevel = intval( $secs[$index++
] );
4723 $content = $secs[$index++
];
4726 if( $mode == "get" ) {
4727 if( $count == $section ) {
4728 $rv = $headerLine . $content;
4729 $sectionLevel = $headerLevel;
4730 } elseif( $count > $section ) {
4731 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4732 $rv .= $headerLine . $content;
4734 // Broke out to a higher-level section
4738 } elseif( $mode == "replace" ) {
4739 if( $count < $section ) {
4740 $rv .= $headerLine . $content;
4741 } elseif( $count == $section ) {
4742 $rv .= $newtext . "\n\n";
4743 $sectionLevel = $headerLevel;
4744 } elseif( $count > $section ) {
4745 if( $headerLevel <= $sectionLevel ) {
4746 // Passed the section's sub-parts.
4750 $rv .= $headerLine . $content;
4756 # reinsert stripped tags
4757 $rv = trim( $stripState->unstripBoth( $rv ) );
4763 * This function returns the text of a section, specified by a number ($section).
4764 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4765 * the first section before any such heading (section 0).
4767 * If a section contains subsections, these are also returned.
4769 * @param $text String: text to look in
4770 * @param $section Integer: section number
4771 * @param $deftext: default to return if section is not found
4772 * @return string text of the requested section
4774 public function getSection( $text, $section, $deftext='' ) {
4775 return $this->extractSections( $text, $section, "get", $deftext );
4778 public function replaceSection( $oldtext, $section, $text ) {
4779 return $this->extractSections( $oldtext, $section, "replace", $text );
4783 * Get the timestamp associated with the current revision, adjusted for
4784 * the default server-local timestamp
4786 function getRevisionTimestamp() {
4787 if ( is_null( $this->mRevisionTimestamp
) ) {
4788 wfProfileIn( __METHOD__
);
4790 $dbr = wfGetDB( DB_SLAVE
);
4791 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4792 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4794 // Normalize timestamp to internal MW format for timezone processing.
4795 // This has the added side-effect of replacing a null value with
4796 // the current time, which gives us more sensible behavior for
4798 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4800 // The cryptic '' timezone parameter tells to use the site-default
4801 // timezone offset instead of the user settings.
4803 // Since this value will be saved into the parser cache, served
4804 // to other users, and potentially even used inside links and such,
4805 // it needs to be consistent for all visitors.
4806 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4808 wfProfileOut( __METHOD__
);
4810 return $this->mRevisionTimestamp
;
4814 * Mutator for $mDefaultSort
4816 * @param $sort New value
4818 public function setDefaultSort( $sort ) {
4819 $this->mDefaultSort
= $sort;
4823 * Accessor for $mDefaultSort
4824 * Will use the title/prefixed title if none is set
4828 public function getDefaultSort() {
4829 if( $this->mDefaultSort
!== false ) {
4830 return $this->mDefaultSort
;
4832 return $this->mTitle
->getNamespace() == NS_CATEGORY
4833 ?
$this->mTitle
->getText()
4834 : $this->mTitle
->getPrefixedText();
4840 * @todo document, briefly.
4841 * @addtogroup Parser
4843 class OnlyIncludeReplacer
{
4846 function replace( $matches ) {
4847 if ( substr( $matches[1], -1 ) == "\n" ) {
4848 $this->output
.= substr( $matches[1], 0, -1 );
4850 $this->output
.= $matches[1];
4856 * @todo document, briefly.
4857 * @addtogroup Parser
4860 var $general, $nowiki;
4862 function __construct() {
4863 $this->general
= new ReplacementArray
;
4864 $this->nowiki
= new ReplacementArray
;
4867 function unstripGeneral( $text ) {
4868 wfProfileIn( __METHOD__
);
4869 $text = $this->general
->replace( $text );
4870 wfProfileOut( __METHOD__
);
4874 function unstripNoWiki( $text ) {
4875 wfProfileIn( __METHOD__
);
4876 $text = $this->nowiki
->replace( $text );
4877 wfProfileOut( __METHOD__
);
4881 function unstripBoth( $text ) {
4882 wfProfileIn( __METHOD__
);
4883 $text = $this->general
->replace( $text );
4884 $text = $this->nowiki
->replace( $text );
4885 wfProfileOut( __METHOD__
);