3 * File for Parser and related classes
9 * Update this version number when the ParserOutput format
10 * changes in an incompatible way, so the parser cache
11 * can automatically discard old data.
13 define( 'MW_PARSER_VERSION', '1.6.1' );
15 define( 'RLH_FOR_UPDATE', 1 );
17 # Allowed values for $mOutputType
18 define( 'OT_HTML', 1 );
19 define( 'OT_WIKI', 2 );
20 define( 'OT_MSG' , 3 );
21 define( 'OT_PREPROCESS', 4 );
23 # Flags for setFunctionHook
24 define( 'SFH_NO_HASH', 1 );
26 # string parameter for extractTags which will cause it
27 # to strip HTML comments in addition to regular
28 # <XML>-style tags. This should not be anything we
29 # may want to use in wikisyntax
30 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
32 # Constants needed for external link processing
33 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
34 # Everything except bracket, space, or control characters
35 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
36 # Including space, but excluding newlines
37 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
38 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
39 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
40 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
41 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
42 define( 'EXT_IMAGE_REGEX',
43 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
44 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
45 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
48 // State constants for the definition list colon extraction
49 define( 'MW_COLON_STATE_TEXT', 0 );
50 define( 'MW_COLON_STATE_TAG', 1 );
51 define( 'MW_COLON_STATE_TAGSTART', 2 );
52 define( 'MW_COLON_STATE_CLOSETAG', 3 );
53 define( 'MW_COLON_STATE_TAGSLASH', 4 );
54 define( 'MW_COLON_STATE_COMMENT', 5 );
55 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
56 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
59 * PHP Parser - Processes wiki markup (which uses a more user-friendly
60 * syntax, such as "[[link]]" for making links), and provides a one-way
61 * transformation of that wiki markup it into XHTML output / markup
62 * (which in turn the browser understands, and can display).
65 * There are four main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
73 * removes HTML comments and expands templates
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
86 * * only within ParserOptions
92 const VERSION
= MW_PARSER_VERSION
;
97 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
103 var $mIncludeSizes, $mDefaultSort;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId, // ID to display in {{REVISIONID}} tags
116 $mRevisionTimestamp, // The timestamp of the specified revision ID
117 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
127 $this->mTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mFirstCall
= true;
134 * Do various kinds of initialisation on the first call of the parser
136 function firstCallInit() {
137 if ( !$this->mFirstCall
) {
141 wfProfileIn( __METHOD__
);
142 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
144 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
146 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
170 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
172 if ( $wgAllowDisplayTitle ) {
173 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
175 if ( $wgAllowSlowParserFunctions ) {
176 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
179 $this->initialiseVariables();
180 $this->mFirstCall
= false;
181 wfProfileOut( __METHOD__
);
189 function clearState() {
190 wfProfileIn( __METHOD__
);
191 if ( $this->mFirstCall
) {
192 $this->firstCallInit();
194 $this->mOutput
= new ParserOutput
;
195 $this->mAutonumber
= 0;
196 $this->mLastSection
= '';
197 $this->mDTopen
= false;
198 $this->mIncludeCount
= array();
199 $this->mStripState
= new StripState
;
200 $this->mArgStack
= array();
201 $this->mInPre
= false;
202 $this->mInterwikiLinkHolders
= array(
206 $this->mLinkHolders
= array(
207 'namespaces' => array(),
209 'queries' => array(),
213 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
216 * Prefix for temporary replacement strings for the multipass parser.
217 * \x07 should never appear in input as it's disallowed in XML.
218 * Using it at the front also gives us a little extra robustness
219 * since it shouldn't match when butted up against identifier-like
222 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
224 # Clear these on every parse, bug 4549
225 $this->mTemplates
= array();
226 $this->mTemplatePath
= array();
228 $this->mShowToc
= true;
229 $this->mForceTocPosition
= false;
230 $this->mIncludeSizes
= array(
235 $this->mDefaultSort
= false;
237 wfRunHooks( 'ParserClearState', array( &$this ) );
238 wfProfileOut( __METHOD__
);
241 function setOutputType( $ot ) {
242 $this->mOutputType
= $ot;
245 'html' => $ot == OT_HTML
,
246 'wiki' => $ot == OT_WIKI
,
247 'msg' => $ot == OT_MSG
,
248 'pre' => $ot == OT_PREPROCESS
,
253 * Accessor for mUniqPrefix.
257 function uniqPrefix() {
258 return $this->mUniqPrefix
;
262 * Convert wikitext to HTML
263 * Do not call this function recursively.
265 * @param string $text Text we want to parse
266 * @param Title &$title A title object
267 * @param array $options
268 * @param boolean $linestart
269 * @param boolean $clearState
270 * @param int $revid number to pass in {{REVISIONID}}
271 * @return ParserOutput a ParserOutput
273 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
275 * First pass--just handle <nowiki> sections, pass the rest off
276 * to internalParse() which does all the real work.
279 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
280 $fname = 'Parser::parse-' . wfGetCaller();
281 wfProfileIn( __METHOD__
);
282 wfProfileIn( $fname );
288 $this->mOptions
= $options;
289 $this->mTitle
=& $title;
290 $oldRevisionId = $this->mRevisionId
;
291 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
292 if( $revid !== null ) {
293 $this->mRevisionId
= $revid;
294 $this->mRevisionTimestamp
= null;
296 $this->setOutputType( OT_HTML
);
297 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
298 $text = $this->strip( $text, $this->mStripState
);
299 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
300 $text = $this->internalParse( $text );
301 $text = $this->mStripState
->unstripGeneral( $text );
303 # Clean up special characters, only run once, next-to-last before doBlockLevels
305 # french spaces, last one Guillemet-left
306 # only if there is something before the space
307 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
308 # french spaces, Guillemet-right
309 '/(\\302\\253) /' => '\\1 ',
311 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
314 $text = $this->doBlockLevels( $text, $linestart );
316 $this->replaceLinkHolders( $text );
318 # the position of the parserConvert() call should not be changed. it
319 # assumes that the links are all replaced and the only thing left
320 # is the <nowiki> mark.
321 # Side-effects: this calls $this->mOutput->setTitleText()
322 $text = $wgContLang->parserConvert( $text, $this );
324 $text = $this->mStripState
->unstripNoWiki( $text );
326 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
328 $text = Sanitizer
::normalizeCharReferences( $text );
330 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
331 $text = Parser
::tidy($text);
333 # attempt to sanitize at least some nesting problems
334 # (bug #2702 and quite a few others)
336 # ''Something [http://www.cool.com cool''] -->
337 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
338 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
339 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
340 # fix up an anchor inside another anchor, only
341 # at least for a single single nested link (bug 3695)
342 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
343 '\\1\\2</a>\\3</a>\\1\\4</a>',
344 # fix div inside inline elements- doBlockLevels won't wrap a line which
345 # contains a div, so fix it up here; replace
346 # div with escaped text
347 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
348 '\\1\\3<div\\5>\\6</div>\\8\\9',
349 # remove empty italic or bold tag pairs, some
350 # introduced by rules above
351 '/<([bi])><\/\\1>/' => '',
354 $text = preg_replace(
355 array_keys( $tidyregs ),
356 array_values( $tidyregs ),
360 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
362 # Information on include size limits, for the benefit of users who try to skirt them
363 if ( max( $this->mIncludeSizes
) > 1000 ) {
364 $max = $this->mOptions
->getMaxIncludeSize();
366 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
367 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
368 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
369 "Maximum: $max bytes\n" .
372 $this->mOutput
->setText( $text );
373 $this->mRevisionId
= $oldRevisionId;
374 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
375 wfProfileOut( $fname );
376 wfProfileOut( __METHOD__
);
378 return $this->mOutput
;
382 * Recursive parser entry point that can be called from an extension tag
385 function recursiveTagParse( $text ) {
386 wfProfileIn( __METHOD__
);
387 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
388 $text = $this->strip( $text, $this->mStripState
);
389 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
390 $text = $this->internalParse( $text );
391 wfProfileOut( __METHOD__
);
396 * Expand templates and variables in the text, producing valid, static wikitext.
397 * Also removes comments.
399 function preprocess( $text, $title, $options ) {
400 wfProfileIn( __METHOD__
);
402 $this->setOutputType( OT_PREPROCESS
);
403 $this->mOptions
= $options;
404 $this->mTitle
= $title;
405 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
406 $text = $this->strip( $text, $this->mStripState
);
407 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
408 if ( $this->mOptions
->getRemoveComments() ) {
409 $text = Sanitizer
::removeHTMLcomments( $text );
411 $text = $this->replaceVariables( $text );
412 $text = $this->mStripState
->unstripBoth( $text );
413 wfProfileOut( __METHOD__
);
418 * Get a random string
423 function getRandomString() {
424 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
427 function &getTitle() { return $this->mTitle
; }
428 function getOptions() { return $this->mOptions
; }
430 function getFunctionLang() {
431 global $wgLang, $wgContLang;
432 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
436 * Replaces all occurrences of HTML-style comments and the given tags
437 * in the text with a random marker and returns teh next text. The output
438 * parameter $matches will be an associative array filled with data in
440 * 'UNIQ-xxxxx' => array(
443 * array( 'param' => 'x' ),
444 * '<element param="x">tag content</element>' ) )
446 * @param $elements list of element names. Comments are always extracted.
447 * @param $text Source text string.
448 * @param $uniq_prefix
453 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
458 $taglist = implode( '|', $elements );
459 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
461 while ( '' != $text ) {
462 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
464 if( count( $p ) < 5 ) {
467 if( count( $p ) > 5 ) {
481 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
482 $stripped .= $marker;
484 if ( $close === '/>' ) {
485 // Empty element tag, <tag />
490 if( $element == '!--' ) {
493 $end = "/(<\\/$element\\s*>)/i";
495 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
497 if( count( $q ) < 3 ) {
498 # No end tag -- let it run out to the end of the text.
507 $matches[$marker] = array( $element,
509 Sanitizer
::decodeTagAttributes( $attributes ),
510 "<$element$attributes$close$content$tail" );
516 * Strips and renders nowiki, pre, math, hiero
517 * If $render is set, performs necessary rendering operations on plugins
518 * Returns the text, and fills an array with data needed in unstrip()
520 * @param StripState $state
522 * @param bool $stripcomments when set, HTML comments <!-- like this -->
523 * will be stripped in addition to other tags. This is important
524 * for section editing, where these comments cause confusion when
525 * counting the sections in the wikisource
527 * @param array dontstrip contains tags which should not be stripped;
528 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
532 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
534 wfProfileIn( __METHOD__
);
535 $render = ($this->mOutputType
== OT_HTML
);
537 $uniq_prefix = $this->mUniqPrefix
;
538 $commentState = new ReplacementArray
;
539 $nowikiItems = array();
540 $generalItems = array();
542 $elements = array_merge(
543 array( 'nowiki', 'gallery' ),
544 array_keys( $this->mTagHooks
) );
547 $elements[] = 'html';
549 if( $this->mOptions
->getUseTeX() ) {
550 $elements[] = 'math';
553 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
554 foreach ( $elements AS $k => $v ) {
555 if ( !in_array ( $v , $dontstrip ) ) continue;
556 unset ( $elements[$k] );
560 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
562 foreach( $matches as $marker => $data ) {
563 list( $element, $content, $params, $tag ) = $data;
565 $tagName = strtolower( $element );
566 wfProfileIn( __METHOD__
."-render-$tagName" );
570 if( substr( $tag, -3 ) == '-->' ) {
573 // Unclosed comment in input.
574 // Close it so later stripping can remove it
583 // Shouldn't happen otherwise. :)
585 $output = Xml
::escapeTagsOnly( $content );
588 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
591 $output = $this->renderImageGallery( $content, $params );
594 if( isset( $this->mTagHooks
[$tagName] ) ) {
595 $output = call_user_func_array( $this->mTagHooks
[$tagName],
596 array( $content, $params, $this ) );
598 throw new MWException( "Invalid call hook $element" );
601 wfProfileOut( __METHOD__
."-render-$tagName" );
603 // Just stripping tags; keep the source
607 // Unstrip the output, to support recursive strip() calls
608 $output = $state->unstripBoth( $output );
610 if( !$stripcomments && $element == '!--' ) {
611 $commentState->setPair( $marker, $output );
612 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
613 $nowikiItems[$marker] = $output;
615 $generalItems[$marker] = $output;
618 # Add the new items to the state
619 # We do this after the loop instead of during it to avoid slowing
620 # down the recursive unstrip
621 $state->nowiki
->mergeArray( $nowikiItems );
622 $state->general
->mergeArray( $generalItems );
624 # Unstrip comments unless explicitly told otherwise.
625 # (The comments are always stripped prior to this point, so as to
626 # not invoke any extension tags / parser hooks contained within
628 if ( !$stripcomments ) {
629 // Put them all back and forget them
630 $text = $commentState->replace( $text );
633 wfProfileOut( __METHOD__
);
638 * Restores pre, math, and other extensions removed by strip()
640 * always call unstripNoWiki() after this one
642 * @deprecated use $this->mStripState->unstrip()
644 function unstrip( $text, $state ) {
645 return $state->unstripGeneral( $text );
649 * Always call this after unstrip() to preserve the order
652 * @deprecated use $this->mStripState->unstrip()
654 function unstripNoWiki( $text, $state ) {
655 return $state->unstripNoWiki( $text );
659 * @deprecated use $this->mStripState->unstripBoth()
661 function unstripForHTML( $text ) {
662 return $this->mStripState
->unstripBoth( $text );
666 * Add an item to the strip state
667 * Returns the unique tag which must be inserted into the stripped text
668 * The tag will be replaced with the original text in unstrip()
672 function insertStripItem( $text, &$state ) {
673 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
674 $state->general
->setPair( $rnd, $text );
679 * Interface with html tidy, used if $wgUseTidy = true.
680 * If tidy isn't able to correct the markup, the original will be
681 * returned in all its glory with a warning comment appended.
683 * Either the external tidy program or the in-process tidy extension
684 * will be used depending on availability. Override the default
685 * $wgTidyInternal setting to disable the internal if it's not working.
687 * @param string $text Hideous HTML input
688 * @return string Corrected HTML output
692 function tidy( $text ) {
693 global $wgTidyInternal;
694 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
695 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
696 '<head><title>test</title></head><body>'.$text.'</body></html>';
697 if( $wgTidyInternal ) {
698 $correctedtext = Parser
::internalTidy( $wrappedtext );
700 $correctedtext = Parser
::externalTidy( $wrappedtext );
702 if( is_null( $correctedtext ) ) {
703 wfDebug( "Tidy error detected!\n" );
704 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
706 return $correctedtext;
710 * Spawn an external HTML tidy process and get corrected markup back from it.
715 function externalTidy( $text ) {
716 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
717 $fname = 'Parser::externalTidy';
718 wfProfileIn( $fname );
723 $descriptorspec = array(
724 0 => array('pipe', 'r'),
725 1 => array('pipe', 'w'),
726 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.
729 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
730 if (is_resource($process)) {
731 // Theoretically, this style of communication could cause a deadlock
732 // here. If the stdout buffer fills up, then writes to stdin could
733 // block. This doesn't appear to happen with tidy, because tidy only
734 // writes to stdout after it's finished reading from stdin. Search
735 // for tidyParseStdin and tidySaveStdout in console/tidy.c
736 fwrite($pipes[0], $text);
738 while (!feof($pipes[1])) {
739 $cleansource .= fgets($pipes[1], 1024);
742 proc_close($process);
745 wfProfileOut( $fname );
747 if( $cleansource == '' && $text != '') {
748 // Some kind of error happened, so we couldn't get the corrected text.
749 // Just give up; we'll use the source text and append a warning.
757 * Use the HTML tidy PECL extension to use the tidy library in-process,
758 * saving the overhead of spawning a new process. Currently written to
759 * the PHP 4.3.x version of the extension, may not work on PHP 5.
761 * 'pear install tidy' should be able to compile the extension module.
766 function internalTidy( $text ) {
768 $fname = 'Parser::internalTidy';
769 wfProfileIn( $fname );
771 tidy_load_config( $wgTidyConf );
772 tidy_set_encoding( 'utf8' );
773 tidy_parse_string( $text );
775 if( tidy_get_status() == 2 ) {
776 // 2 is magic number for fatal error
777 // http://www.php.net/manual/en/function.tidy-get-status.php
780 $cleansource = tidy_get_output();
782 wfProfileOut( $fname );
787 * parse the wiki syntax used to render tables
791 function doTableStuff ( $text ) {
792 $fname = 'Parser::doTableStuff';
793 wfProfileIn( $fname );
795 $lines = explode ( "\n" , $text );
796 $td_history = array (); // Is currently a td tag open?
797 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
798 $tr_history = array (); // Is currently a tr tag open?
799 $tr_attributes = array (); // history of tr attributes
800 $has_opened_tr = array(); // Did this table open a <tr> element?
801 $indent_level = 0; // indent level of the table
802 foreach ( $lines as $key => $line )
804 $line = trim ( $line );
806 if( $line == '' ) { // empty line, go to next line
809 $first_character = $line{0};
812 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
813 // First check if we are starting a new table
814 $indent_level = strlen( $matches[1] );
816 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
817 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
819 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
820 array_push ( $td_history , false );
821 array_push ( $last_tag_history , '' );
822 array_push ( $tr_history , false );
823 array_push ( $tr_attributes , '' );
824 array_push ( $has_opened_tr , false );
825 } else if ( count ( $td_history ) == 0 ) {
826 // Don't do any of the following
828 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
829 // We are ending a table
830 $line = '</table>' . substr ( $line , 2 );
831 $last_tag = array_pop ( $last_tag_history );
833 if ( !array_pop ( $has_opened_tr ) ) {
834 $line = "<tr><td></td></tr>{$line}";
837 if ( array_pop ( $tr_history ) ) {
838 $line = "</tr>{$line}";
841 if ( array_pop ( $td_history ) ) {
842 $line = "</{$last_tag}>{$line}";
844 array_pop ( $tr_attributes );
845 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
846 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
847 // Now we have a table row
848 $line = preg_replace( '#^\|-+#', '', $line );
850 // Whats after the tag is now only attributes
851 $attributes = $this->mStripState
->unstripBoth( $line );
852 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
853 array_pop ( $tr_attributes );
854 array_push ( $tr_attributes , $attributes );
857 $last_tag = array_pop ( $last_tag_history );
858 array_pop ( $has_opened_tr );
859 array_push ( $has_opened_tr , true );
861 if ( array_pop ( $tr_history ) ) {
865 if ( array_pop ( $td_history ) ) {
866 $line = "</{$last_tag}>{$line}";
869 $lines[$key] = $line;
870 array_push ( $tr_history , false );
871 array_push ( $td_history , false );
872 array_push ( $last_tag_history , '' );
874 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
875 // This might be cell elements, td, th or captions
876 if ( substr ( $line , 0 , 2 ) == '|+' ) {
877 $first_character = '+';
878 $line = substr ( $line , 1 );
881 $line = substr ( $line , 1 );
883 if ( $first_character == '!' ) {
884 $line = str_replace ( '!!' , '||' , $line );
887 // Split up multiple cells on the same line.
888 // FIXME : This can result in improper nesting of tags processed
889 // by earlier parser steps, but should avoid splitting up eg
890 // attribute values containing literal "||".
891 $cells = StringUtils
::explodeMarkup( '||' , $line );
895 // Loop through each table cell
896 foreach ( $cells as $cell )
899 if ( $first_character != '+' )
901 $tr_after = array_pop ( $tr_attributes );
902 if ( !array_pop ( $tr_history ) ) {
903 $previous = "<tr{$tr_after}>\n";
905 array_push ( $tr_history , true );
906 array_push ( $tr_attributes , '' );
907 array_pop ( $has_opened_tr );
908 array_push ( $has_opened_tr , true );
911 $last_tag = array_pop ( $last_tag_history );
913 if ( array_pop ( $td_history ) ) {
914 $previous = "</{$last_tag}>{$previous}";
917 if ( $first_character == '|' ) {
919 } else if ( $first_character == '!' ) {
921 } else if ( $first_character == '+' ) {
922 $last_tag = 'caption';
927 array_push ( $last_tag_history , $last_tag );
929 // A cell could contain both parameters and data
930 $cell_data = explode ( '|' , $cell , 2 );
932 // Bug 553: Note that a '|' inside an invalid link should not
933 // be mistaken as delimiting cell parameters
934 if ( strpos( $cell_data[0], '[[' ) !== false ) {
935 $cell = "{$previous}<{$last_tag}>{$cell}";
936 } else if ( count ( $cell_data ) == 1 )
937 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
939 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
940 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
941 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
944 $lines[$key] .= $cell;
945 array_push ( $td_history , true );
950 // Closing open td, tr && table
951 while ( count ( $td_history ) > 0 )
953 if ( array_pop ( $td_history ) ) {
956 if ( array_pop ( $tr_history ) ) {
959 if ( !array_pop ( $has_opened_tr ) ) {
960 $lines[] = "<tr><td></td></tr>" ;
963 $lines[] = '</table>' ;
966 $output = implode ( "\n" , $lines ) ;
968 // special case: don't return empty table
969 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
973 wfProfileOut( $fname );
979 * Helper function for parse() that transforms wiki markup into
980 * HTML. Only called for $mOutputType == OT_HTML.
984 function internalParse( $text ) {
987 $fname = 'Parser::internalParse';
988 wfProfileIn( $fname );
990 # Hook to suspend the parser in this state
991 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
992 wfProfileOut( $fname );
996 # Remove <noinclude> tags and <includeonly> sections
997 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
998 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
999 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1001 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1003 $text = $this->replaceVariables( $text, $args );
1004 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text ) );
1006 // Tables need to come after variable replacement for things to work
1007 // properly; putting them before other transformations should keep
1008 // exciting things like link expansions from showing up in surprising
1010 $text = $this->doTableStuff( $text );
1012 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1014 $text = $this->stripToc( $text );
1015 $this->stripNoGallery( $text );
1016 $text = $this->doHeadings( $text );
1017 if($this->mOptions
->getUseDynamicDates()) {
1018 $df =& DateFormatter
::getInstance();
1019 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1021 $text = $this->doAllQuotes( $text );
1022 $text = $this->replaceInternalLinks( $text );
1023 $text = $this->replaceExternalLinks( $text );
1025 # replaceInternalLinks may sometimes leave behind
1026 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1027 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1029 $text = $this->doMagicLinks( $text );
1030 $text = $this->formatHeadings( $text, $isMain );
1032 wfProfileOut( $fname );
1037 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1038 * magic external links.
1042 function &doMagicLinks( &$text ) {
1043 wfProfileIn( __METHOD__
);
1044 $text = preg_replace_callback(
1046 <a.*?</a> | # Skip link text
1047 <.*?> | # Skip stuff inside HTML elements
1048 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1049 ISBN\s+(\b # ISBN, capture number as m[2]
1050 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1051 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1052 [0-9Xx] # check digit
1054 )!x', array( &$this, 'magicLinkCallback' ), $text );
1055 wfProfileOut( __METHOD__
);
1059 function magicLinkCallback( $m ) {
1060 if ( substr( $m[0], 0, 1 ) == '<' ) {
1063 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1065 $num = strtr( $isbn, array(
1070 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
1071 $text = '<a href="' .
1072 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1073 "\" class=\"internal\">ISBN $isbn</a>";
1075 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1079 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1081 $urlmsg = 'pubmedurl';
1084 throw new MWException( __METHOD__
.': unrecognised match type "' .
1085 substr($m[0], 0, 20 ) . '"' );
1088 $url = wfMsg( $urlmsg, $id);
1089 $sk = $this->mOptions
->getSkin();
1090 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1091 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1097 * Parse headers and return html
1101 function doHeadings( $text ) {
1102 $fname = 'Parser::doHeadings';
1103 wfProfileIn( $fname );
1104 for ( $i = 6; $i >= 1; --$i ) {
1105 $h = str_repeat( '=', $i );
1106 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1107 "<h{$i}>\\1</h{$i}>\\2", $text );
1109 wfProfileOut( $fname );
1114 * Replace single quotes with HTML markup
1116 * @return string the altered text
1118 function doAllQuotes( $text ) {
1119 $fname = 'Parser::doAllQuotes';
1120 wfProfileIn( $fname );
1122 $lines = explode( "\n", $text );
1123 foreach ( $lines as $line ) {
1124 $outtext .= $this->doQuotes ( $line ) . "\n";
1126 $outtext = substr($outtext, 0,-1);
1127 wfProfileOut( $fname );
1132 * Helper function for doAllQuotes()
1135 function doQuotes( $text ) {
1136 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1137 if ( count( $arr ) == 1 )
1141 # First, do some preliminary work. This may shift some apostrophes from
1142 # being mark-up to being text. It also counts the number of occurrences
1143 # of bold and italics mark-ups.
1147 foreach ( $arr as $r )
1149 if ( ( $i %
2 ) == 1 )
1151 # If there are ever four apostrophes, assume the first is supposed to
1152 # be text, and the remaining three constitute mark-up for bold text.
1153 if ( strlen( $arr[$i] ) == 4 )
1158 # If there are more than 5 apostrophes in a row, assume they're all
1159 # text except for the last 5.
1160 else if ( strlen( $arr[$i] ) > 5 )
1162 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1165 # Count the number of occurrences of bold and italics mark-ups.
1166 # We are not counting sequences of five apostrophes.
1167 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1168 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1169 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1174 # If there is an odd number of both bold and italics, it is likely
1175 # that one of the bold ones was meant to be an apostrophe followed
1176 # by italics. Which one we cannot know for certain, but it is more
1177 # likely to be one that has a single-letter word before it.
1178 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1181 $firstsingleletterword = -1;
1182 $firstmultiletterword = -1;
1184 foreach ( $arr as $r )
1186 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1188 $x1 = substr ($arr[$i-1], -1);
1189 $x2 = substr ($arr[$i-1], -2, 1);
1191 if ($firstspace == -1) $firstspace = $i;
1192 } else if ($x2 == ' ') {
1193 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1195 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1201 # If there is a single-letter word, use it!
1202 if ($firstsingleletterword > -1)
1204 $arr [ $firstsingleletterword ] = "''";
1205 $arr [ $firstsingleletterword-1 ] .= "'";
1207 # If not, but there's a multi-letter word, use that one.
1208 else if ($firstmultiletterword > -1)
1210 $arr [ $firstmultiletterword ] = "''";
1211 $arr [ $firstmultiletterword-1 ] .= "'";
1213 # ... otherwise use the first one that has neither.
1214 # (notice that it is possible for all three to be -1 if, for example,
1215 # there is only one pentuple-apostrophe in the line)
1216 else if ($firstspace > -1)
1218 $arr [ $firstspace ] = "''";
1219 $arr [ $firstspace-1 ] .= "'";
1223 # Now let's actually convert our apostrophic mush to HTML!
1228 foreach ($arr as $r)
1232 if ($state == 'both')
1239 if (strlen ($r) == 2)
1242 { $output .= '</i>'; $state = ''; }
1243 else if ($state == 'bi')
1244 { $output .= '</i>'; $state = 'b'; }
1245 else if ($state == 'ib')
1246 { $output .= '</b></i><b>'; $state = 'b'; }
1247 else if ($state == 'both')
1248 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1249 else # $state can be 'b' or ''
1250 { $output .= '<i>'; $state .= 'i'; }
1252 else if (strlen ($r) == 3)
1255 { $output .= '</b>'; $state = ''; }
1256 else if ($state == 'bi')
1257 { $output .= '</i></b><i>'; $state = 'i'; }
1258 else if ($state == 'ib')
1259 { $output .= '</b>'; $state = 'i'; }
1260 else if ($state == 'both')
1261 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1262 else # $state can be 'i' or ''
1263 { $output .= '<b>'; $state .= 'b'; }
1265 else if (strlen ($r) == 5)
1268 { $output .= '</b><i>'; $state = 'i'; }
1269 else if ($state == 'i')
1270 { $output .= '</i><b>'; $state = 'b'; }
1271 else if ($state == 'bi')
1272 { $output .= '</i></b>'; $state = ''; }
1273 else if ($state == 'ib')
1274 { $output .= '</b></i>'; $state = ''; }
1275 else if ($state == 'both')
1276 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1277 else # ($state == '')
1278 { $buffer = ''; $state = 'both'; }
1283 # Now close all remaining tags. Notice that the order is important.
1284 if ($state == 'b' ||
$state == 'ib')
1286 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1290 # There might be lonely ''''', so make sure we have a buffer
1291 if ($state == 'both' && $buffer)
1292 $output .= '<b><i>'.$buffer.'</i></b>';
1298 * Replace external links
1300 * Note: this is all very hackish and the order of execution matters a lot.
1301 * Make sure to run maintenance/parserTests.php if you change this code.
1305 function replaceExternalLinks( $text ) {
1307 $fname = 'Parser::replaceExternalLinks';
1308 wfProfileIn( $fname );
1310 $sk = $this->mOptions
->getSkin();
1312 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1314 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1317 while ( $i<count( $bits ) ) {
1319 $protocol = $bits[$i++
];
1320 $text = $bits[$i++
];
1321 $trail = $bits[$i++
];
1323 # The characters '<' and '>' (which were escaped by
1324 # removeHTMLtags()) should not be included in
1325 # URLs, per RFC 2396.
1327 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1328 $text = substr($url, $m2[0][1]) . ' ' . $text;
1329 $url = substr($url, 0, $m2[0][1]);
1332 # If the link text is an image URL, replace it with an <img> tag
1333 # This happened by accident in the original parser, but some people used it extensively
1334 $img = $this->maybeMakeExternalImage( $text );
1335 if ( $img !== false ) {
1341 # Set linktype for CSS - if URL==text, link is essentially free
1342 $linktype = ($text == $url) ?
'free' : 'text';
1344 # No link text, e.g. [http://domain.tld/some.link]
1345 if ( $text == '' ) {
1346 # Autonumber if allowed. See bug #5918
1347 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1348 $text = '[' . ++
$this->mAutonumber
. ']';
1349 $linktype = 'autonumber';
1351 # Otherwise just use the URL
1352 $text = htmlspecialchars( $url );
1356 # Have link text, e.g. [http://domain.tld/some.link text]s
1358 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1361 $text = $wgContLang->markNoConversion($text);
1363 $url = Sanitizer
::cleanUrl( $url );
1365 # Process the trail (i.e. everything after this link up until start of the next link),
1366 # replacing any non-bracketed links
1367 $trail = $this->replaceFreeExternalLinks( $trail );
1369 # Use the encoded URL
1370 # This means that users can paste URLs directly into the text
1371 # Funny characters like ö aren't valid in URLs anyway
1372 # This was changed in August 2004
1373 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1375 # Register link in the output object.
1376 # Replace unnecessary URL escape codes with the referenced character
1377 # This prevents spammers from hiding links from the filters
1378 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1379 $this->mOutput
->addExternalLink( $pasteurized );
1382 wfProfileOut( $fname );
1387 * Replace anything that looks like a URL with a link
1390 function replaceFreeExternalLinks( $text ) {
1392 $fname = 'Parser::replaceFreeExternalLinks';
1393 wfProfileIn( $fname );
1395 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1396 $s = array_shift( $bits );
1399 $sk = $this->mOptions
->getSkin();
1401 while ( $i < count( $bits ) ){
1402 $protocol = $bits[$i++
];
1403 $remainder = $bits[$i++
];
1406 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1407 # Found some characters after the protocol that look promising
1408 $url = $protocol . $m[1];
1411 # special case: handle urls as url args:
1412 # http://www.example.com/foo?=http://www.example.com/bar
1413 if(strlen($trail) == 0 &&
1415 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1416 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1419 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1424 # The characters '<' and '>' (which were escaped by
1425 # removeHTMLtags()) should not be included in
1426 # URLs, per RFC 2396.
1428 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1429 $trail = substr($url, $m2[0][1]) . $trail;
1430 $url = substr($url, 0, $m2[0][1]);
1433 # Move trailing punctuation to $trail
1435 # If there is no left bracket, then consider right brackets fair game too
1436 if ( strpos( $url, '(' ) === false ) {
1440 $numSepChars = strspn( strrev( $url ), $sep );
1441 if ( $numSepChars ) {
1442 $trail = substr( $url, -$numSepChars ) . $trail;
1443 $url = substr( $url, 0, -$numSepChars );
1446 $url = Sanitizer
::cleanUrl( $url );
1448 # Is this an external image?
1449 $text = $this->maybeMakeExternalImage( $url );
1450 if ( $text === false ) {
1451 # Not an image, make a link
1452 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1453 # Register it in the output object...
1454 # Replace unnecessary URL escape codes with their equivalent characters
1455 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1456 $this->mOutput
->addExternalLink( $pasteurized );
1458 $s .= $text . $trail;
1460 $s .= $protocol . $remainder;
1463 wfProfileOut( $fname );
1468 * Replace unusual URL escape codes with their equivalent characters
1472 * @todo This can merge genuinely required bits in the path or query string,
1473 * breaking legit URLs. A proper fix would treat the various parts of
1474 * the URL differently; as a workaround, just use the output for
1475 * statistical records, not for actual linking/output.
1477 static function replaceUnusualEscapes( $url ) {
1478 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1479 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1483 * Callback function used in replaceUnusualEscapes().
1484 * Replaces unusual URL escape codes with their equivalent character
1488 private static function replaceUnusualEscapesCallback( $matches ) {
1489 $char = urldecode( $matches[0] );
1490 $ord = ord( $char );
1491 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1492 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1493 // No, shouldn't be escaped
1496 // Yes, leave it escaped
1502 * make an image if it's allowed, either through the global
1503 * option or through the exception
1506 function maybeMakeExternalImage( $url ) {
1507 $sk = $this->mOptions
->getSkin();
1508 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1509 $imagesexception = !empty($imagesfrom);
1511 if ( $this->mOptions
->getAllowExternalImages()
1512 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1513 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1515 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1522 * Process [[ ]] wikilinks
1526 function replaceInternalLinks( $s ) {
1528 static $fname = 'Parser::replaceInternalLinks' ;
1530 wfProfileIn( $fname );
1532 wfProfileIn( $fname.'-setup' );
1534 # the % is needed to support urlencoded titles as well
1535 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1537 $sk = $this->mOptions
->getSkin();
1539 #split the entire text string on occurences of [[
1540 $a = explode( '[[', ' ' . $s );
1541 #get the first element (all text up to first [[), and remove the space we added
1542 $s = array_shift( $a );
1543 $s = substr( $s, 1 );
1545 # Match a link having the form [[namespace:link|alternate]]trail
1547 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1548 # Match cases where there is no "]]", which might still be images
1549 static $e1_img = FALSE;
1550 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1551 # Match the end of a line for a word that's not followed by whitespace,
1552 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1553 $e2 = wfMsgForContent( 'linkprefix' );
1555 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1556 if( is_null( $this->mTitle
) ) {
1557 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1559 $nottalk = !$this->mTitle
->isTalkPage();
1561 if ( $useLinkPrefixExtension ) {
1563 if ( preg_match( $e2, $s, $m ) ) {
1564 $first_prefix = $m[2];
1566 $first_prefix = false;
1572 if($wgContLang->hasVariants()) {
1573 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1575 $selflink = array($this->mTitle
->getPrefixedText());
1577 $useSubpages = $this->areSubpagesAllowed();
1578 wfProfileOut( $fname.'-setup' );
1580 # Loop for each link
1581 for ($k = 0; isset( $a[$k] ); $k++
) {
1583 if ( $useLinkPrefixExtension ) {
1584 wfProfileIn( $fname.'-prefixhandling' );
1585 if ( preg_match( $e2, $s, $m ) ) {
1593 $prefix = $first_prefix;
1594 $first_prefix = false;
1596 wfProfileOut( $fname.'-prefixhandling' );
1599 $might_be_img = false;
1601 wfProfileIn( "$fname-e1" );
1602 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1604 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1605 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1606 # the real problem is with the $e1 regex
1609 # Still some problems for cases where the ] is meant to be outside punctuation,
1610 # and no image is in sight. See bug 2095.
1613 substr( $m[3], 0, 1 ) === ']' &&
1614 strpos($text, '[') !== false
1617 $text .= ']'; # so that replaceExternalLinks($text) works later
1618 $m[3] = substr( $m[3], 1 );
1620 # fix up urlencoded title texts
1621 if( strpos( $m[1], '%' ) !== false ) {
1622 # Should anchors '#' also be rejected?
1623 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1626 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1627 $might_be_img = true;
1629 if ( strpos( $m[1], '%' ) !== false ) {
1630 $m[1] = urldecode($m[1]);
1633 } else { # Invalid form; output directly
1634 $s .= $prefix . '[[' . $line ;
1635 wfProfileOut( "$fname-e1" );
1638 wfProfileOut( "$fname-e1" );
1639 wfProfileIn( "$fname-misc" );
1641 # Don't allow internal links to pages containing
1642 # PROTO: where PROTO is a valid URL protocol; these
1643 # should be external links.
1644 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1645 $s .= $prefix . '[[' . $line ;
1649 # Make subpage if necessary
1650 if( $useSubpages ) {
1651 $link = $this->maybeDoSubpageLink( $m[1], $text );
1656 $noforce = (substr($m[1], 0, 1) != ':');
1658 # Strip off leading ':'
1659 $link = substr($link, 1);
1662 wfProfileOut( "$fname-misc" );
1663 wfProfileIn( "$fname-title" );
1664 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1666 $s .= $prefix . '[[' . $line;
1667 wfProfileOut( "$fname-title" );
1671 $ns = $nt->getNamespace();
1672 $iw = $nt->getInterWiki();
1673 wfProfileOut( "$fname-title" );
1675 if ($might_be_img) { # if this is actually an invalid link
1676 wfProfileIn( "$fname-might_be_img" );
1677 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1679 while (isset ($a[$k+
1]) ) {
1680 #look at the next 'line' to see if we can close it there
1681 $spliced = array_splice( $a, $k +
1, 1 );
1682 $next_line = array_shift( $spliced );
1683 $m = explode( ']]', $next_line, 3 );
1684 if ( count( $m ) == 3 ) {
1685 # the first ]] closes the inner link, the second the image
1687 $text .= "[[{$m[0]}]]{$m[1]}";
1690 } elseif ( count( $m ) == 2 ) {
1691 #if there's exactly one ]] that's fine, we'll keep looking
1692 $text .= "[[{$m[0]}]]{$m[1]}";
1694 #if $next_line is invalid too, we need look no further
1695 $text .= '[[' . $next_line;
1700 # we couldn't find the end of this imageLink, so output it raw
1701 #but don't ignore what might be perfectly normal links in the text we've examined
1702 $text = $this->replaceInternalLinks($text);
1703 $s .= "{$prefix}[[$link|$text";
1704 # note: no $trail, because without an end, there *is* no trail
1705 wfProfileOut( "$fname-might_be_img" );
1708 } else { #it's not an image, so output it raw
1709 $s .= "{$prefix}[[$link|$text";
1710 # note: no $trail, because without an end, there *is* no trail
1711 wfProfileOut( "$fname-might_be_img" );
1714 wfProfileOut( "$fname-might_be_img" );
1717 $wasblank = ( '' == $text );
1718 if( $wasblank ) $text = $link;
1720 # Link not escaped by : , create the various objects
1724 wfProfileIn( "$fname-interwiki" );
1725 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1726 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1727 $s = rtrim($s . $prefix);
1728 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1729 wfProfileOut( "$fname-interwiki" );
1732 wfProfileOut( "$fname-interwiki" );
1734 if ( $ns == NS_IMAGE
) {
1735 wfProfileIn( "$fname-image" );
1736 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1737 # recursively parse links inside the image caption
1738 # actually, this will parse them in any other parameters, too,
1739 # but it might be hard to fix that, and it doesn't matter ATM
1740 $text = $this->replaceExternalLinks($text);
1741 $text = $this->replaceInternalLinks($text);
1743 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1744 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1745 $this->mOutput
->addImage( $nt->getDBkey() );
1747 wfProfileOut( "$fname-image" );
1750 # We still need to record the image's presence on the page
1751 $this->mOutput
->addImage( $nt->getDBkey() );
1753 wfProfileOut( "$fname-image" );
1757 if ( $ns == NS_CATEGORY
) {
1758 wfProfileIn( "$fname-category" );
1759 $s = rtrim($s . "\n"); # bug 87
1762 $sortkey = $this->getDefaultSort();
1766 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1767 $sortkey = str_replace( "\n", '', $sortkey );
1768 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1769 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1772 * Strip the whitespace Category links produce, see bug 87
1773 * @todo We might want to use trim($tmp, "\n") here.
1775 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1777 wfProfileOut( "$fname-category" );
1782 # Self-link checking
1783 if( $nt->getFragment() === '' ) {
1784 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1785 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1790 # Special and Media are pseudo-namespaces; no pages actually exist in them
1791 if( $ns == NS_MEDIA
) {
1792 $link = $sk->makeMediaLinkObj( $nt, $text );
1793 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1794 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1795 $this->mOutput
->addImage( $nt->getDBkey() );
1797 } elseif( $ns == NS_SPECIAL
) {
1798 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1800 } elseif( $ns == NS_IMAGE
) {
1801 $img = new Image( $nt );
1802 if( $img->exists() ) {
1803 // Force a blue link if the file exists; may be a remote
1804 // upload on the shared repository, and we want to see its
1805 // auto-generated page.
1806 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1807 $this->mOutput
->addLink( $nt );
1811 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1813 wfProfileOut( $fname );
1818 * Make a link placeholder. The text returned can be later resolved to a real link with
1819 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1820 * parsing of interwiki links, and secondly to allow all existence checks and
1821 * article length checks (for stub links) to be bundled into a single query.
1824 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1825 wfProfileIn( __METHOD__
);
1826 if ( ! is_object($nt) ) {
1828 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1830 # Separate the link trail from the rest of the link
1831 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1833 if ( $nt->isExternal() ) {
1834 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1835 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1836 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1838 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1839 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1840 $this->mLinkHolders
['queries'][] = $query;
1841 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1842 $this->mLinkHolders
['titles'][] = $nt;
1844 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1847 wfProfileOut( __METHOD__
);
1852 * Render a forced-blue link inline; protect against double expansion of
1853 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1854 * Since this little disaster has to split off the trail text to avoid
1855 * breaking URLs in the following text without breaking trails on the
1856 * wiki links, it's been made into a horrible function.
1859 * @param string $text
1860 * @param string $query
1861 * @param string $trail
1862 * @param string $prefix
1863 * @return string HTML-wikitext mix oh yuck
1865 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1866 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1867 $sk = $this->mOptions
->getSkin();
1868 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1869 return $this->armorLinks( $link ) . $trail;
1873 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1874 * going to go through further parsing steps before inline URL expansion.
1876 * In particular this is important when using action=render, which causes
1877 * full URLs to be included.
1879 * Oh man I hate our multi-layer parser!
1881 * @param string more-or-less HTML
1882 * @return string less-or-more HTML with NOPARSE bits
1884 function armorLinks( $text ) {
1885 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1886 "{$this->mUniqPrefix}NOPARSE$1", $text );
1890 * Return true if subpage links should be expanded on this page.
1893 function areSubpagesAllowed() {
1894 # Some namespaces don't allow subpages
1895 global $wgNamespacesWithSubpages;
1896 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1900 * Handle link to subpage if necessary
1901 * @param string $target the source of the link
1902 * @param string &$text the link text, modified as necessary
1903 * @return string the full name of the link
1906 function maybeDoSubpageLink($target, &$text) {
1909 # :Foobar -- override special treatment of prefix (images, language links)
1910 # /Foobar -- convert to CurrentPage/Foobar
1911 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1912 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1913 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1915 $fname = 'Parser::maybeDoSubpageLink';
1916 wfProfileIn( $fname );
1917 $ret = $target; # default return value is no change
1920 $target = trim( $target );
1922 # Some namespaces don't allow subpages,
1923 # so only perform processing if subpages are allowed
1924 if( $this->areSubpagesAllowed() ) {
1925 # Look at the first character
1926 if( $target != '' && $target{0} == '/' ) {
1927 # / at end means we don't want the slash to be shown
1928 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1929 if( $trailingSlashes ) {
1930 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1932 $noslash = substr( $target, 1 );
1935 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1936 if( '' === $text ) {
1938 } # this might be changed for ugliness reasons
1940 # check for .. subpage backlinks
1942 $nodotdot = $target;
1943 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1945 $nodotdot = substr( $nodotdot, 3 );
1947 if($dotdotcount > 0) {
1948 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1949 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1950 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1951 # / at the end means don't show full path
1952 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1953 $nodotdot = substr( $nodotdot, 0, -1 );
1954 if( '' === $text ) {
1958 $nodotdot = trim( $nodotdot );
1959 if( $nodotdot != '' ) {
1960 $ret .= '/' . $nodotdot;
1967 wfProfileOut( $fname );
1972 * Used by doBlockLevels()
1975 /* private */ function closeParagraph() {
1977 if ( '' != $this->mLastSection
) {
1978 $result = '</' . $this->mLastSection
. ">\n";
1980 $this->mInPre
= false;
1981 $this->mLastSection
= '';
1984 # getCommon() returns the length of the longest common substring
1985 # of both arguments, starting at the beginning of both.
1987 /* private */ function getCommon( $st1, $st2 ) {
1988 $fl = strlen( $st1 );
1989 $shorter = strlen( $st2 );
1990 if ( $fl < $shorter ) { $shorter = $fl; }
1992 for ( $i = 0; $i < $shorter; ++
$i ) {
1993 if ( $st1{$i} != $st2{$i} ) { break; }
1997 # These next three functions open, continue, and close the list
1998 # element appropriate to the prefix character passed into them.
2000 /* private */ function openList( $char ) {
2001 $result = $this->closeParagraph();
2003 if ( '*' == $char ) { $result .= '<ul><li>'; }
2004 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2005 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2006 else if ( ';' == $char ) {
2007 $result .= '<dl><dt>';
2008 $this->mDTopen
= true;
2010 else { $result = '<!-- ERR 1 -->'; }
2015 /* private */ function nextItem( $char ) {
2016 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2017 else if ( ':' == $char ||
';' == $char ) {
2019 if ( $this->mDTopen
) { $close = '</dt>'; }
2020 if ( ';' == $char ) {
2021 $this->mDTopen
= true;
2022 return $close . '<dt>';
2024 $this->mDTopen
= false;
2025 return $close . '<dd>';
2028 return '<!-- ERR 2 -->';
2031 /* private */ function closeList( $char ) {
2032 if ( '*' == $char ) { $text = '</li></ul>'; }
2033 else if ( '#' == $char ) { $text = '</li></ol>'; }
2034 else if ( ':' == $char ) {
2035 if ( $this->mDTopen
) {
2036 $this->mDTopen
= false;
2037 $text = '</dt></dl>';
2039 $text = '</dd></dl>';
2042 else { return '<!-- ERR 3 -->'; }
2048 * Make lists from lines starting with ':', '*', '#', etc.
2051 * @return string the lists rendered as HTML
2053 function doBlockLevels( $text, $linestart ) {
2054 $fname = 'Parser::doBlockLevels';
2055 wfProfileIn( $fname );
2057 # Parsing through the text line by line. The main thing
2058 # happening here is handling of block-level elements p, pre,
2059 # and making lists from lines starting with * # : etc.
2061 $textLines = explode( "\n", $text );
2063 $lastPrefix = $output = '';
2064 $this->mDTopen
= $inBlockElem = false;
2066 $paragraphStack = false;
2068 if ( !$linestart ) {
2069 $output .= array_shift( $textLines );
2071 foreach ( $textLines as $oLine ) {
2072 $lastPrefixLength = strlen( $lastPrefix );
2073 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2074 $preOpenMatch = preg_match('/<pre/i', $oLine );
2075 if ( !$this->mInPre
) {
2076 # Multiple prefixes may abut each other for nested lists.
2077 $prefixLength = strspn( $oLine, '*#:;' );
2078 $pref = substr( $oLine, 0, $prefixLength );
2081 $pref2 = str_replace( ';', ':', $pref );
2082 $t = substr( $oLine, $prefixLength );
2083 $this->mInPre
= !empty($preOpenMatch);
2085 # Don't interpret any other prefixes in preformatted text
2087 $pref = $pref2 = '';
2092 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2093 # Same as the last item, so no need to deal with nesting or opening stuff
2094 $output .= $this->nextItem( substr( $pref, -1 ) );
2095 $paragraphStack = false;
2097 if ( substr( $pref, -1 ) == ';') {
2098 # The one nasty exception: definition lists work like this:
2099 # ; title : definition text
2100 # So we check for : in the remainder text to split up the
2101 # title and definition, without b0rking links.
2103 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2105 $output .= $term . $this->nextItem( ':' );
2108 } elseif( $prefixLength ||
$lastPrefixLength ) {
2109 # Either open or close a level...
2110 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2111 $paragraphStack = false;
2113 while( $commonPrefixLength < $lastPrefixLength ) {
2114 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2115 --$lastPrefixLength;
2117 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2118 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2120 while ( $prefixLength > $commonPrefixLength ) {
2121 $char = substr( $pref, $commonPrefixLength, 1 );
2122 $output .= $this->openList( $char );
2124 if ( ';' == $char ) {
2125 # FIXME: This is dupe of code above
2126 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2128 $output .= $term . $this->nextItem( ':' );
2131 ++
$commonPrefixLength;
2133 $lastPrefix = $pref2;
2135 if( 0 == $prefixLength ) {
2136 wfProfileIn( "$fname-paragraph" );
2137 # No prefix (not in list)--go to paragraph mode
2138 // XXX: use a stack for nestable elements like span, table and div
2139 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2140 $closematch = preg_match(
2141 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2142 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2143 if ( $openmatch or $closematch ) {
2144 $paragraphStack = false;
2145 #Â TODO bug 5718: paragraph closed
2146 $output .= $this->closeParagraph();
2147 if ( $preOpenMatch and !$preCloseMatch ) {
2148 $this->mInPre
= true;
2150 if ( $closematch ) {
2151 $inBlockElem = false;
2153 $inBlockElem = true;
2155 } else if ( !$inBlockElem && !$this->mInPre
) {
2156 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2158 if ($this->mLastSection
!= 'pre') {
2159 $paragraphStack = false;
2160 $output .= $this->closeParagraph().'<pre>';
2161 $this->mLastSection
= 'pre';
2163 $t = substr( $t, 1 );
2166 if ( '' == trim($t) ) {
2167 if ( $paragraphStack ) {
2168 $output .= $paragraphStack.'<br />';
2169 $paragraphStack = false;
2170 $this->mLastSection
= 'p';
2172 if ($this->mLastSection
!= 'p' ) {
2173 $output .= $this->closeParagraph();
2174 $this->mLastSection
= '';
2175 $paragraphStack = '<p>';
2177 $paragraphStack = '</p><p>';
2181 if ( $paragraphStack ) {
2182 $output .= $paragraphStack;
2183 $paragraphStack = false;
2184 $this->mLastSection
= 'p';
2185 } else if ($this->mLastSection
!= 'p') {
2186 $output .= $this->closeParagraph().'<p>';
2187 $this->mLastSection
= 'p';
2192 wfProfileOut( "$fname-paragraph" );
2194 // somewhere above we forget to get out of pre block (bug 785)
2195 if($preCloseMatch && $this->mInPre
) {
2196 $this->mInPre
= false;
2198 if ($paragraphStack === false) {
2202 while ( $prefixLength ) {
2203 $output .= $this->closeList( $pref2{$prefixLength-1} );
2206 if ( '' != $this->mLastSection
) {
2207 $output .= '</' . $this->mLastSection
. '>';
2208 $this->mLastSection
= '';
2211 wfProfileOut( $fname );
2216 * Split up a string on ':', ignoring any occurences inside tags
2217 * to prevent illegal overlapping.
2218 * @param string $str the string to split
2219 * @param string &$before set to everything before the ':'
2220 * @param string &$after set to everything after the ':'
2221 * return string the position of the ':', or false if none found
2223 function findColonNoLinks($str, &$before, &$after) {
2224 $fname = 'Parser::findColonNoLinks';
2225 wfProfileIn( $fname );
2227 $pos = strpos( $str, ':' );
2228 if( $pos === false ) {
2230 wfProfileOut( $fname );
2234 $lt = strpos( $str, '<' );
2235 if( $lt === false ||
$lt > $pos ) {
2236 // Easy; no tag nesting to worry about
2237 $before = substr( $str, 0, $pos );
2238 $after = substr( $str, $pos+
1 );
2239 wfProfileOut( $fname );
2243 // Ugly state machine to walk through avoiding tags.
2244 $state = MW_COLON_STATE_TEXT
;
2246 $len = strlen( $str );
2247 for( $i = 0; $i < $len; $i++
) {
2251 // (Using the number is a performance hack for common cases)
2252 case 0: // MW_COLON_STATE_TEXT:
2255 // Could be either a <start> tag or an </end> tag
2256 $state = MW_COLON_STATE_TAGSTART
;
2261 $before = substr( $str, 0, $i );
2262 $after = substr( $str, $i +
1 );
2263 wfProfileOut( $fname );
2266 // Embedded in a tag; don't break it.
2269 // Skip ahead looking for something interesting
2270 $colon = strpos( $str, ':', $i );
2271 if( $colon === false ) {
2272 // Nothing else interesting
2273 wfProfileOut( $fname );
2276 $lt = strpos( $str, '<', $i );
2277 if( $stack === 0 ) {
2278 if( $lt === false ||
$colon < $lt ) {
2280 $before = substr( $str, 0, $colon );
2281 $after = substr( $str, $colon +
1 );
2282 wfProfileOut( $fname );
2286 if( $lt === false ) {
2287 // Nothing else interesting to find; abort!
2288 // We're nested, but there's no close tags left. Abort!
2291 // Skip ahead to next tag start
2293 $state = MW_COLON_STATE_TAGSTART
;
2296 case 1: // MW_COLON_STATE_TAG:
2301 $state = MW_COLON_STATE_TEXT
;
2304 // Slash may be followed by >?
2305 $state = MW_COLON_STATE_TAGSLASH
;
2311 case 2: // MW_COLON_STATE_TAGSTART:
2314 $state = MW_COLON_STATE_CLOSETAG
;
2317 $state = MW_COLON_STATE_COMMENT
;
2320 // Illegal early close? This shouldn't happen D:
2321 $state = MW_COLON_STATE_TEXT
;
2324 $state = MW_COLON_STATE_TAG
;
2327 case 3: // MW_COLON_STATE_CLOSETAG:
2332 wfDebug( "Invalid input in $fname; too many close tags\n" );
2333 wfProfileOut( $fname );
2336 $state = MW_COLON_STATE_TEXT
;
2339 case MW_COLON_STATE_TAGSLASH
:
2341 // Yes, a self-closed tag <blah/>
2342 $state = MW_COLON_STATE_TEXT
;
2344 // Probably we're jumping the gun, and this is an attribute
2345 $state = MW_COLON_STATE_TAG
;
2348 case 5: // MW_COLON_STATE_COMMENT:
2350 $state = MW_COLON_STATE_COMMENTDASH
;
2353 case MW_COLON_STATE_COMMENTDASH
:
2355 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2357 $state = MW_COLON_STATE_COMMENT
;
2360 case MW_COLON_STATE_COMMENTDASHDASH
:
2362 $state = MW_COLON_STATE_TEXT
;
2364 $state = MW_COLON_STATE_COMMENT
;
2368 throw new MWException( "State machine error in $fname" );
2372 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2375 wfProfileOut( $fname );
2380 * Return value of a magic variable (like PAGENAME)
2384 function getVariableValue( $index ) {
2385 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2388 * Some of these require message or data lookups and can be
2389 * expensive to check many times.
2391 static $varCache = array();
2392 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2393 if ( isset( $varCache[$index] ) ) {
2394 return $varCache[$index];
2399 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2402 global $wgLocaltimezone;
2403 if ( isset( $wgLocaltimezone ) ) {
2404 $oldtz = getenv( 'TZ' );
2405 putenv( 'TZ='.$wgLocaltimezone );
2407 $localTimestamp = date( 'YmdHis', $ts );
2408 $localMonth = date( 'm', $ts );
2409 $localMonthName = date( 'n', $ts );
2410 $localDay = date( 'j', $ts );
2411 $localDay2 = date( 'd', $ts );
2412 $localDayOfWeek = date( 'w', $ts );
2413 $localWeek = date( 'W', $ts );
2414 $localYear = date( 'Y', $ts );
2415 $localHour = date( 'H', $ts );
2416 if ( isset( $wgLocaltimezone ) ) {
2417 putenv( 'TZ='.$oldtz );
2421 case 'currentmonth':
2422 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2423 case 'currentmonthname':
2424 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2425 case 'currentmonthnamegen':
2426 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2427 case 'currentmonthabbrev':
2428 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2430 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2432 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2434 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2435 case 'localmonthname':
2436 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2437 case 'localmonthnamegen':
2438 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2439 case 'localmonthabbrev':
2440 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2442 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2444 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2446 return $this->mTitle
->getText();
2448 return $this->mTitle
->getPartialURL();
2449 case 'fullpagename':
2450 return $this->mTitle
->getPrefixedText();
2451 case 'fullpagenamee':
2452 return $this->mTitle
->getPrefixedURL();
2454 return $this->mTitle
->getSubpageText();
2455 case 'subpagenamee':
2456 return $this->mTitle
->getSubpageUrlForm();
2457 case 'basepagename':
2458 return $this->mTitle
->getBaseText();
2459 case 'basepagenamee':
2460 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2461 case 'talkpagename':
2462 if( $this->mTitle
->canTalk() ) {
2463 $talkPage = $this->mTitle
->getTalkPage();
2464 return $talkPage->getPrefixedText();
2468 case 'talkpagenamee':
2469 if( $this->mTitle
->canTalk() ) {
2470 $talkPage = $this->mTitle
->getTalkPage();
2471 return $talkPage->getPrefixedUrl();
2475 case 'subjectpagename':
2476 $subjPage = $this->mTitle
->getSubjectPage();
2477 return $subjPage->getPrefixedText();
2478 case 'subjectpagenamee':
2479 $subjPage = $this->mTitle
->getSubjectPage();
2480 return $subjPage->getPrefixedUrl();
2482 return $this->mRevisionId
;
2484 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2485 case 'revisionday2':
2486 return substr( $this->getRevisionTimestamp(), 6, 2 );
2487 case 'revisionmonth':
2488 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2489 case 'revisionyear':
2490 return substr( $this->getRevisionTimestamp(), 0, 4 );
2491 case 'revisiontimestamp':
2492 return $this->getRevisionTimestamp();
2494 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2496 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2498 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2500 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2501 case 'subjectspace':
2502 return $this->mTitle
->getSubjectNsText();
2503 case 'subjectspacee':
2504 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2505 case 'currentdayname':
2506 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2508 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2510 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2512 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2514 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2515 // int to remove the padding
2516 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2518 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2519 case 'localdayname':
2520 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2522 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2524 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2526 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2528 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2529 // int to remove the padding
2530 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2532 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2533 case 'numberofarticles':
2534 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2535 case 'numberoffiles':
2536 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2537 case 'numberofusers':
2538 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2539 case 'numberofpages':
2540 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2541 case 'numberofadmins':
2542 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2543 case 'currenttimestamp':
2544 return $varCache[$index] = wfTimestampNow();
2545 case 'localtimestamp':
2546 return $varCache[$index] = $localTimestamp;
2547 case 'currentversion':
2548 return $varCache[$index] = SpecialVersion
::getVersion();
2554 return $wgServerName;
2556 return $wgScriptPath;
2557 case 'directionmark':
2558 return $wgContLang->getDirMark();
2559 case 'contentlanguage':
2560 global $wgContLanguageCode;
2561 return $wgContLanguageCode;
2564 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2572 * initialise the magic variables (like CURRENTMONTHNAME)
2576 function initialiseVariables() {
2577 $fname = 'Parser::initialiseVariables';
2578 wfProfileIn( $fname );
2579 $variableIDs = MagicWord
::getVariableIDs();
2581 $this->mVariables
= array();
2582 foreach ( $variableIDs as $id ) {
2583 $mw =& MagicWord
::get( $id );
2584 $mw->addToArray( $this->mVariables
, $id );
2586 wfProfileOut( $fname );
2590 * parse any parentheses in format ((title|part|part))
2591 * and call callbacks to get a replacement text for any found piece
2593 * @param string $text The text to parse
2594 * @param array $callbacks rules in form:
2595 * '{' => array( # opening parentheses
2596 * 'end' => '}', # closing parentheses
2597 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2598 * 3 => callback # replacement callback to call if {{{..}}} is found
2601 * 'min' => 2, # Minimum parenthesis count in cb
2602 * 'max' => 3, # Maximum parenthesis count in cb
2605 function replace_callback ($text, $callbacks) {
2606 wfProfileIn( __METHOD__
);
2607 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2608 $lastOpeningBrace = -1; # last not closed parentheses
2610 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2613 while ( $i < strlen( $text ) ) {
2614 # Find next opening brace, closing brace or pipe
2615 if ( $lastOpeningBrace == -1 ) {
2616 $currentClosing = '';
2617 $search = $validOpeningBraces;
2619 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2620 $search = $validOpeningBraces . '|' . $currentClosing;
2623 $i +
= strcspn( $text, $search, $i );
2624 if ( $i < strlen( $text ) ) {
2625 if ( $text[$i] == '|' ) {
2627 } elseif ( $text[$i] == $currentClosing ) {
2629 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2631 $rule = $callbacks[$text[$i]];
2633 # Some versions of PHP have a strcspn which stops on null characters
2634 # Ignore and continue
2643 if ( $found == 'open' ) {
2644 # found opening brace, let's add it to parentheses stack
2645 $piece = array('brace' => $text[$i],
2646 'braceEnd' => $rule['end'],
2650 # count opening brace characters
2651 $piece['count'] = strspn( $text, $piece['brace'], $i );
2652 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2653 $i +
= $piece['count'];
2655 # we need to add to stack only if opening brace count is enough for one of the rules
2656 if ( $piece['count'] >= $rule['min'] ) {
2657 $lastOpeningBrace ++
;
2658 $openingBraceStack[$lastOpeningBrace] = $piece;
2660 } elseif ( $found == 'close' ) {
2661 # lets check if it is enough characters for closing brace
2662 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2663 $count = strspn( $text, $text[$i], $i, $maxCount );
2665 # check for maximum matching characters (if there are 5 closing
2666 # characters, we will probably need only 3 - depending on the rules)
2668 $matchingCallback = null;
2669 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2670 if ( $count > $cbType['max'] ) {
2671 # The specified maximum exists in the callback array, unless the caller
2673 $matchingCount = $cbType['max'];
2675 # Count is less than the maximum
2676 # Skip any gaps in the callback array to find the true largest match
2677 # Need to use array_key_exists not isset because the callback can be null
2678 $matchingCount = $count;
2679 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2684 if ($matchingCount <= 0) {
2688 $matchingCallback = $cbType['cb'][$matchingCount];
2690 # let's set a title or last part (if '|' was found)
2691 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2692 $openingBraceStack[$lastOpeningBrace]['title'] =
2693 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2694 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2696 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2697 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2698 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2701 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2702 $pieceEnd = $i +
$matchingCount;
2704 if( is_callable( $matchingCallback ) ) {
2706 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2707 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2708 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2709 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2711 # finally we can call a user callback and replace piece of text
2712 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2713 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2714 $i = $pieceStart +
strlen($replaceWith);
2716 # null value for callback means that parentheses should be parsed, but not replaced
2717 $i +
= $matchingCount;
2720 # reset last opening parentheses, but keep it in case there are unused characters
2721 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2722 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2723 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2726 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2727 $openingBraceStack[$lastOpeningBrace--] = null;
2729 if ($matchingCount < $piece['count']) {
2730 $piece['count'] -= $matchingCount;
2731 $piece['startAt'] -= $matchingCount;
2732 $piece['partStart'] = $piece['startAt'];
2733 # do we still qualify for any callback with remaining count?
2734 $currentCbList = $callbacks[$piece['brace']]['cb'];
2735 while ( $piece['count'] ) {
2736 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2737 $lastOpeningBrace++
;
2738 $openingBraceStack[$lastOpeningBrace] = $piece;
2744 } elseif ( $found == 'pipe' ) {
2745 # lets set a title if it is a first separator, or next part otherwise
2746 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2747 $openingBraceStack[$lastOpeningBrace]['title'] =
2748 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2749 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2750 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2752 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2753 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2754 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2756 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2760 wfProfileOut( __METHOD__
);
2765 * Replace magic variables, templates, and template arguments
2766 * with the appropriate text. Templates are substituted recursively,
2767 * taking care to avoid infinite loops.
2769 * Note that the substitution depends on value of $mOutputType:
2770 * OT_WIKI: only {{subst:}} templates
2771 * OT_MSG: only magic variables
2772 * OT_HTML: all templates and magic variables
2774 * @param string $tex The text to transform
2775 * @param array $args Key-value pairs representing template parameters to substitute
2776 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2779 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2780 # Prevent too big inclusions
2781 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2785 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2786 wfProfileIn( $fname );
2788 # This function is called recursively. To keep track of arguments we need a stack:
2789 array_push( $this->mArgStack
, $args );
2791 $braceCallbacks = array();
2793 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2795 if ( $this->mOutputType
!= OT_MSG
) {
2796 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2798 if ( $braceCallbacks ) {
2802 'cb' => $braceCallbacks,
2803 'min' => $argsOnly ?
3 : 2,
2804 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2808 'cb' => array(2=>null),
2813 $text = $this->replace_callback ($text, $callbacks);
2815 array_pop( $this->mArgStack
);
2817 wfProfileOut( $fname );
2822 * Replace magic variables
2825 function variableSubstitution( $matches ) {
2827 $fname = 'Parser::variableSubstitution';
2828 $varname = $wgContLang->lc($matches[1]);
2829 wfProfileIn( $fname );
2831 if ( $this->mOutputType
== OT_WIKI
) {
2832 # Do only magic variables prefixed by SUBST
2833 $mwSubst =& MagicWord
::get( 'subst' );
2834 if (!$mwSubst->matchStartAndRemove( $varname ))
2836 # Note that if we don't substitute the variable below,
2837 # we don't remove the {{subst:}} magic word, in case
2838 # it is a template rather than a magic variable.
2840 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2841 $id = $this->mVariables
[$varname];
2842 # Now check if we did really match, case sensitive or not
2843 $mw =& MagicWord
::get( $id );
2844 if ($mw->match($matches[1])) {
2845 $text = $this->getVariableValue( $id );
2846 $this->mOutput
->mContainsOldMagic
= true;
2848 $text = $matches[0];
2851 $text = $matches[0];
2853 wfProfileOut( $fname );
2858 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2859 static function createAssocArgs( $args ) {
2860 $assocArgs = array();
2862 foreach( $args as $arg ) {
2863 $eqpos = strpos( $arg, '=' );
2864 if ( $eqpos === false ) {
2865 $assocArgs[$index++
] = $arg;
2867 $name = trim( substr( $arg, 0, $eqpos ) );
2868 $value = trim( substr( $arg, $eqpos+
1 ) );
2869 if ( $value === false ) {
2872 if ( $name !== false ) {
2873 $assocArgs[$name] = $value;
2882 * Return the text of a template, after recursively
2883 * replacing any variables or templates within the template.
2885 * @param array $piece The parts of the template
2886 * $piece['text']: matched text
2887 * $piece['title']: the title, i.e. the part before the |
2888 * $piece['parts']: the parameter array
2889 * @return string the text of the template
2892 function braceSubstitution( $piece ) {
2893 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2894 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2895 wfProfileIn( $fname );
2896 wfProfileIn( __METHOD__
.'-setup' );
2899 $found = false; # $text has been filled
2900 $nowiki = false; # wiki markup in $text should be escaped
2901 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2902 $noargs = false; # Don't replace triple-brace arguments in $text
2903 $replaceHeadings = false; # Make the edit section links go to the template not the article
2904 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2905 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2906 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2908 # Title object, where $text came from
2914 # $part1 is the bit before the first |, and must contain only title characters
2915 # $args is a list of arguments, starting from index 0, not including $part1
2917 $titleText = $part1 = $piece['title'];
2918 # If the third subpattern matched anything, it will start with |
2920 if (null == $piece['parts']) {
2921 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2922 if ($replaceWith != $piece['text']) {
2923 $text = $replaceWith;
2930 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2931 wfProfileOut( __METHOD__
.'-setup' );
2934 wfProfileIn( __METHOD__
.'-modifiers' );
2936 $mwSubst =& MagicWord
::get( 'subst' );
2937 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2938 # One of two possibilities is true:
2939 # 1) Found SUBST but not in the PST phase
2940 # 2) Didn't find SUBST and in the PST phase
2941 # In either case, return without further processing
2942 $text = $piece['text'];
2949 # MSG, MSGNW and RAW
2952 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2953 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2956 # Remove obsolete MSG:
2957 $mwMsg =& MagicWord
::get( 'msg' );
2958 $mwMsg->matchStartAndRemove( $part1 );
2962 $mwRaw =& MagicWord
::get( 'raw' );
2963 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2964 $forceRawInterwiki = true;
2967 wfProfileOut( __METHOD__
.'-modifiers' );
2969 //save path level before recursing into functions & templates.
2970 $lastPathLevel = $this->mTemplatePath
;
2974 wfProfileIn( __METHOD__
. '-pfunc' );
2976 $colonPos = strpos( $part1, ':' );
2977 if ( $colonPos !== false ) {
2978 # Case sensitive functions
2979 $function = substr( $part1, 0, $colonPos );
2980 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2981 $function = $this->mFunctionSynonyms
[1][$function];
2983 # Case insensitive functions
2984 $function = strtolower( $function );
2985 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2986 $function = $this->mFunctionSynonyms
[0][$function];
2992 $funcArgs = array_map( 'trim', $args );
2993 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2994 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2997 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3001 if ( is_array( $result ) ) {
3002 if ( isset( $result[0] ) ) {
3003 $text = $linestart . $result[0];
3004 unset( $result[0] );
3007 // Extract flags into the local scope
3008 // This allows callers to set flags such as nowiki, noparse, found, etc.
3011 $text = $linestart . $result;
3015 wfProfileOut( __METHOD__
. '-pfunc' );
3018 # Template table test
3020 # Did we encounter this template already? If yes, it is in the cache
3021 # and we need to check for loops.
3022 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
3025 # Infinite loop test
3026 if ( isset( $this->mTemplatePath
[$part1] ) ) {
3030 $text = $linestart .
3031 "[[$part1]]<!-- WARNING: template loop detected -->";
3032 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
3034 # set $text to cached message.
3035 $text = $linestart . $this->mTemplates
[$piece['title']];
3036 #treat title for cached page the same as others
3039 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3040 if ($subpage !== '') {
3041 $ns = $this->mTitle
->getNamespace();
3043 $title = Title
::newFromText( $part1, $ns );
3044 //used by include size checking
3045 $titleText = $title->getPrefixedText();
3046 //used by edit section links
3047 $replaceHeadings = true;
3052 # Load from database
3054 wfProfileIn( __METHOD__
. '-loadtpl' );
3056 # declaring $subpage directly in the function call
3057 # does not work correctly with references and breaks
3058 # {{/subpage}}-style inclusions
3060 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3061 if ($subpage !== '') {
3062 $ns = $this->mTitle
->getNamespace();
3064 $title = Title
::newFromText( $part1, $ns );
3067 if ( !is_null( $title ) ) {
3068 $titleText = $title->getPrefixedText();
3069 # Check for language variants if the template is not found
3070 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3071 $wgContLang->findVariantLink($part1, $title);
3074 if ( !$title->isExternal() ) {
3075 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3076 $text = SpecialPage
::capturePath( $title );
3077 if ( is_string( $text ) ) {
3082 $this->disableCache();
3084 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3085 $found = false; //access denied
3086 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3088 $articleContent = $this->fetchTemplate( $title );
3089 if ( $articleContent !== false ) {
3091 $text = $articleContent;
3092 $replaceHeadings = true;
3096 # If the title is valid but undisplayable, make a link to it
3097 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3098 $text = "[[:$titleText]]";
3101 } elseif ( $title->isTrans() ) {
3102 // Interwiki transclusion
3103 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3104 $text = $this->interwikiTransclude( $title, 'render' );
3108 $text = $this->interwikiTransclude( $title, 'raw' );
3109 $replaceHeadings = true;
3114 # Template cache array insertion
3115 # Use the original $piece['title'] not the mangled $part1, so that
3116 # modifiers such as RAW: produce separate cache entries
3119 // A special page; don't store it in the template cache.
3121 $this->mTemplates
[$piece['title']] = $text;
3123 $text = $linestart . $text;
3126 wfProfileOut( __METHOD__
. '-loadtpl' );
3129 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3130 # Error, oversize inclusion
3131 $text = $linestart .
3132 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3137 # Recursive parsing, escaping and link table handling
3138 # Only for HTML output
3139 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3140 $text = wfEscapeWikiText( $text );
3141 } elseif ( !$this->ot
['msg'] && $found ) {
3143 $assocArgs = array();
3145 # Clean up argument array
3146 $assocArgs = self
::createAssocArgs($args);
3147 # Add a new element to the templace recursion path
3148 $this->mTemplatePath
[$part1] = 1;
3152 # If there are any <onlyinclude> tags, only include them
3153 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3154 $replacer = new OnlyIncludeReplacer
;
3155 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3156 array( &$replacer, 'replace' ), $text );
3157 $text = $replacer->output
;
3159 # Remove <noinclude> sections and <includeonly> tags
3160 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3161 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3163 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3164 # Strip <nowiki>, <pre>, etc.
3165 $text = $this->strip( $text, $this->mStripState
);
3166 if ( $this->ot
['html'] ) {
3167 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3168 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3169 $text = Sanitizer
::removeHTMLcomments( $text );
3172 $text = $this->replaceVariables( $text, $assocArgs );
3174 # If the template begins with a table or block-level
3175 # element, it should be treated as beginning a new line.
3176 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3177 $text = "\n" . $text;
3179 } elseif ( !$noargs ) {
3180 # $noparse and !$noargs
3181 # Just replace the arguments, not any double-brace items
3182 # This is used for rendered interwiki transclusion
3183 $text = $this->replaceVariables( $text, $assocArgs, true );
3186 # Prune lower levels off the recursion check path
3187 $this->mTemplatePath
= $lastPathLevel;
3189 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3190 # Error, oversize inclusion
3191 $text = $linestart .
3192 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3198 wfProfileOut( $fname );
3199 return $piece['text'];
3201 wfProfileIn( __METHOD__
. '-placeholders' );
3203 # Replace raw HTML by a placeholder
3204 # Add a blank line preceding, to prevent it from mucking up
3205 # immediately preceding headings
3206 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3208 # replace ==section headers==
3209 # XXX this needs to go away once we have a better parser.
3210 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3211 if( !is_null( $title ) )
3212 $encodedname = base64_encode($title->getPrefixedDBkey());
3214 $encodedname = base64_encode("");
3215 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3216 PREG_SPLIT_DELIM_CAPTURE
);
3218 $nsec = $headingOffset;
3219 for( $i = 0; $i < count($m); $i +
= 2 ) {
3221 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3223 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3228 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3229 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3230 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3236 wfProfileOut( __METHOD__
. '-placeholders' );
3239 # Prune lower levels off the recursion check path
3240 $this->mTemplatePath
= $lastPathLevel;
3243 wfProfileOut( $fname );
3244 return $piece['text'];
3246 wfProfileOut( $fname );
3252 * Fetch the unparsed text of a template and register a reference to it.
3254 function fetchTemplate( $title ) {
3256 // Loop to fetch the article, with up to 1 redirect
3257 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3258 $rev = Revision
::newFromTitle( $title );
3259 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3261 $text = $rev->getText();
3262 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3264 $message = $wgLang->lcfirst( $title->getText() );
3265 $text = wfMsgForContentNoTrans( $message );
3266 if( wfEmptyMsg( $message, $text ) ) {
3273 if ( $text === false ) {
3277 $title = Title
::newFromRedirect( $text );
3283 * Transclude an interwiki link.
3285 function interwikiTransclude( $title, $action ) {
3286 global $wgEnableScaryTranscluding;
3288 if (!$wgEnableScaryTranscluding)
3289 return wfMsg('scarytranscludedisabled');
3291 $url = $title->getFullUrl( "action=$action" );
3293 if (strlen($url) > 255)
3294 return wfMsg('scarytranscludetoolong');
3295 return $this->fetchScaryTemplateMaybeFromCache($url);
3298 function fetchScaryTemplateMaybeFromCache($url) {
3299 global $wgTranscludeCacheExpiry;
3300 $dbr = wfGetDB(DB_SLAVE
);
3301 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3302 array('tc_url' => $url));
3304 $time = $obj->tc_time
;
3305 $text = $obj->tc_contents
;
3306 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3311 $text = Http
::get($url);
3313 return wfMsg('scarytranscludefailed', $url);
3315 $dbw = wfGetDB(DB_MASTER
);
3316 $dbw->replace('transcache', array('tc_url'), array(
3318 'tc_time' => time(),
3319 'tc_contents' => $text));
3325 * Triple brace replacement -- used for template arguments
3328 function argSubstitution( $matches ) {
3329 $arg = trim( $matches['title'] );
3330 $text = $matches['text'];
3331 $inputArgs = end( $this->mArgStack
);
3333 if ( array_key_exists( $arg, $inputArgs ) ) {
3334 $text = $inputArgs[$arg];
3335 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3336 null != $matches['parts'] && count($matches['parts']) > 0) {
3337 $text = $matches['parts'][0];
3339 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3340 $text = $matches['text'] .
3341 '<!-- WARNING: argument omitted, expansion size too large -->';
3348 * Increment an include size counter
3350 * @param string $type The type of expansion
3351 * @param integer $size The size of the text
3352 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3354 function incrementIncludeSize( $type, $size ) {
3355 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3358 $this->mIncludeSizes
[$type] +
= $size;
3364 * Detect __NOGALLERY__ magic word and set a placeholder
3366 function stripNoGallery( &$text ) {
3367 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3369 $mw = MagicWord
::get( 'nogallery' );
3370 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3374 * Detect __TOC__ magic word and set a placeholder
3376 function stripToc( $text ) {
3377 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3379 $mw = MagicWord
::get( 'notoc' );
3380 if( $mw->matchAndRemove( $text ) ) {
3381 $this->mShowToc
= false;
3384 $mw = MagicWord
::get( 'toc' );
3385 if( $mw->match( $text ) ) {
3386 $this->mShowToc
= true;
3387 $this->mForceTocPosition
= true;
3389 // Set a placeholder. At the end we'll fill it in with the TOC.
3390 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3392 // Only keep the first one.
3393 $text = $mw->replace( '', $text );
3399 * This function accomplishes several tasks:
3400 * 1) Auto-number headings if that option is enabled
3401 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3402 * 3) Add a Table of contents on the top for users who have enabled the option
3403 * 4) Auto-anchor headings
3405 * It loops through all headlines, collects the necessary data, then splits up the
3406 * string and re-inserts the newly formatted headlines.
3408 * @param string $text
3409 * @param boolean $isMain
3412 function formatHeadings( $text, $isMain=true ) {
3413 global $wgMaxTocLevel, $wgContLang;
3415 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3416 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3419 $showEditLink = $this->mOptions
->getEditSection();
3422 # Inhibit editsection links if requested in the page
3423 $esw =& MagicWord
::get( 'noeditsection' );
3424 if( $esw->matchAndRemove( $text ) ) {
3428 # Get all headlines for numbering them and adding funky stuff like [edit]
3429 # links - this is for later, but we need the number of headlines right now
3431 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3433 # if there are fewer than 4 headlines in the article, do not show TOC
3434 # unless it's been explicitly enabled.
3435 $enoughToc = $this->mShowToc
&&
3436 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3438 # Allow user to stipulate that a page should have a "new section"
3439 # link added via __NEWSECTIONLINK__
3440 $mw =& MagicWord
::get( 'newsectionlink' );
3441 if( $mw->matchAndRemove( $text ) )
3442 $this->mOutput
->setNewSection( true );
3444 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3445 # override above conditions and always show TOC above first header
3446 $mw =& MagicWord
::get( 'forcetoc' );
3447 if ($mw->matchAndRemove( $text ) ) {
3448 $this->mShowToc
= true;
3452 # Never ever show TOC if no headers
3453 if( $numMatches < 1 ) {
3457 # We need this to perform operations on the HTML
3458 $sk = $this->mOptions
->getSkin();
3462 $sectionCount = 0; # headlineCount excluding template sections
3464 # Ugh .. the TOC should have neat indentation levels which can be
3465 # passed to the skin functions. These are determined here
3469 $sublevelCount = array();
3470 $levelCount = array();
3477 foreach( $matches[3] as $headline ) {
3479 $templatetitle = '';
3480 $templatesection = 0;
3483 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3485 $templatetitle = base64_decode($mat[1]);
3486 $templatesection = 1 +
(int)base64_decode($mat[2]);
3487 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3491 $prevlevel = $level;
3492 $prevtoclevel = $toclevel;
3494 $level = $matches[1][$headlineCount];
3496 if( $doNumberHeadings ||
$enoughToc ) {
3498 if ( $level > $prevlevel ) {
3499 # Increase TOC level
3501 $sublevelCount[$toclevel] = 0;
3502 if( $toclevel<$wgMaxTocLevel ) {
3503 $toc .= $sk->tocIndent();
3506 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3507 # Decrease TOC level, find level to jump to
3509 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3510 # Can only go down to level 1
3513 for ($i = $toclevel; $i > 0; $i--) {
3514 if ( $levelCount[$i] == $level ) {
3515 # Found last matching level
3519 elseif ( $levelCount[$i] < $level ) {
3520 # Found first matching level below current level
3526 if( $toclevel<$wgMaxTocLevel ) {
3527 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3531 # No change in level, end TOC line
3532 if( $toclevel<$wgMaxTocLevel ) {
3533 $toc .= $sk->tocLineEnd();
3537 $levelCount[$toclevel] = $level;
3539 # count number of headlines for each level
3540 @$sublevelCount[$toclevel]++
;
3542 for( $i = 1; $i <= $toclevel; $i++
) {
3543 if( !empty( $sublevelCount[$i] ) ) {
3547 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3553 # The canonized header is a version of the header text safe to use for links
3554 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3555 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3557 # Remove link placeholders by the link text.
3558 # <!--LINK number-->
3560 # link text with suffix
3561 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3562 "\$this->mLinkHolders['texts'][\$1]",
3563 $canonized_headline );
3564 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3565 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3566 $canonized_headline );
3569 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3570 $tocline = trim( $canonized_headline );
3571 # Save headline for section edit hint before it's escaped
3572 $headline_hint = trim( $canonized_headline );
3573 $canonized_headline = Sanitizer
::escapeId( $tocline );
3574 $refers[$headlineCount] = $canonized_headline;
3576 # count how many in assoc. array so we can track dupes in anchors
3577 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3578 $refcount[$headlineCount]=$refers[$canonized_headline];
3580 # Don't number the heading if it is the only one (looks silly)
3581 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3582 # the two are different if the line contains a link
3583 $headline=$numbering . ' ' . $headline;
3586 # Create the anchor for linking from the TOC to the section
3587 $anchor = $canonized_headline;
3588 if($refcount[$headlineCount] > 1 ) {
3589 $anchor .= '_' . $refcount[$headlineCount];
3591 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3592 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3594 # give headline the correct <h#> tag
3595 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3597 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3599 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3603 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3611 if( $toclevel<$wgMaxTocLevel ) {
3612 $toc .= $sk->tocUnindent( $toclevel - 1 );
3614 $toc = $sk->tocList( $toc );
3617 # split up and insert constructed headlines
3619 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3622 foreach( $blocks as $block ) {
3623 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3624 # This is the [edit] link that appears for the top block of text when
3625 # section editing is enabled
3627 # Disabled because it broke block formatting
3628 # For example, a bullet point in the top line
3629 # $full .= $sk->editSectionLink(0);
3632 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3633 # Top anchor now in skin
3637 if( !empty( $head[$i] ) ) {
3642 if( $this->mForceTocPosition
) {
3643 return str_replace( '<!--MWTOC-->', $toc, $full );
3650 * Transform wiki markup when saving a page by doing \r\n -> \n
3651 * conversion, substitting signatures, {{subst:}} templates, etc.
3653 * @param string $text the text to transform
3654 * @param Title &$title the Title object for the current article
3655 * @param User &$user the User object describing the current user
3656 * @param ParserOptions $options parsing options
3657 * @param bool $clearState whether to clear the parser state first
3658 * @return string the altered wiki markup
3661 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3662 $this->mOptions
= $options;
3663 $this->mTitle
=& $title;
3664 $this->setOutputType( OT_WIKI
);
3666 if ( $clearState ) {
3667 $this->clearState();
3670 $stripState = new StripState
;
3674 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3675 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3676 $text = $this->pstPass2( $text, $stripState, $user );
3677 $text = $stripState->unstripBoth( $text );
3682 * Pre-save transform helper function
3685 function pstPass2( $text, &$stripState, $user ) {
3686 global $wgContLang, $wgLocaltimezone;
3688 /* Note: This is the timestamp saved as hardcoded wikitext to
3689 * the database, we use $wgContLang here in order to give
3690 * everyone the same signature and use the default one rather
3691 * than the one selected in each user's preferences.
3693 if ( isset( $wgLocaltimezone ) ) {
3694 $oldtz = getenv( 'TZ' );
3695 putenv( 'TZ='.$wgLocaltimezone );
3697 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3698 ' (' . date( 'T' ) . ')';
3699 if ( isset( $wgLocaltimezone ) ) {
3700 putenv( 'TZ='.$oldtz );
3703 # Variable replacement
3704 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3705 $text = $this->replaceVariables( $text );
3707 # Strip out <nowiki> etc. added via replaceVariables
3708 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3711 $sigText = $this->getUserSig( $user );
3712 $text = strtr( $text, array(
3714 '~~~~' => "$sigText $d",
3718 # Context links: [[|name]] and [[name (context)|]]
3720 global $wgLegalTitleChars;
3721 $tc = "[$wgLegalTitleChars]";
3722 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3724 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3725 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3726 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3728 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3729 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3730 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3732 $t = $this->mTitle
->getText();
3734 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3735 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3736 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3737 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3739 # if there's no context, don't bother duplicating the title
3740 $text = preg_replace( $p2, '[[\\1]]', $text );
3743 # Trim trailing whitespace
3744 $text = rtrim( $text );
3750 * Fetch the user's signature text, if any, and normalize to
3751 * validated, ready-to-insert wikitext.
3757 function getUserSig( &$user ) {
3758 $username = $user->getName();
3759 $nickname = $user->getOption( 'nickname' );
3760 $nickname = $nickname === '' ?
$username : $nickname;
3762 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3763 # Sig. might contain markup; validate this
3764 if( $this->validateSig( $nickname ) !== false ) {
3765 # Validated; clean up (if needed) and return it
3766 return $this->cleanSig( $nickname, true );
3768 # Failed to validate; fall back to the default
3769 $nickname = $username;
3770 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3774 // Make sure nickname doesnt get a sig in a sig
3775 $nickname = $this->cleanSigInSig( $nickname );
3777 # If we're still here, make it a link to the user page
3778 $userpage = $user->getUserPage();
3779 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3783 * Check that the user's signature contains no bad XML
3785 * @param string $text
3786 * @return mixed An expanded string, or false if invalid.
3788 function validateSig( $text ) {
3789 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3793 * Clean up signature text
3795 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3796 * 2) Substitute all transclusions
3798 * @param string $text
3799 * @param $parsing Whether we're cleaning (preferences save) or parsing
3800 * @return string Signature text
3802 function cleanSig( $text, $parsing = false ) {
3804 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3806 $substWord = MagicWord
::get( 'subst' );
3807 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3808 $substText = '{{' . $substWord->getSynonym( 0 );
3810 $text = preg_replace( $substRegex, $substText, $text );
3811 $text = $this->cleanSigInSig( $text );
3812 $text = $this->replaceVariables( $text );
3814 $this->clearState();
3819 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3820 * @param string $text
3821 * @return string Signature text with /~{3,5}/ removed
3823 function cleanSigInSig( $text ) {
3824 $text = preg_replace( '/~{3,5}/', '', $text );
3829 * Set up some variables which are usually set up in parse()
3830 * so that an external function can call some class members with confidence
3833 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3834 $this->mTitle
=& $title;
3835 $this->mOptions
= $options;
3836 $this->setOutputType( $outputType );
3837 if ( $clearState ) {
3838 $this->clearState();
3843 * Transform a MediaWiki message by replacing magic variables.
3845 * @param string $text the text to transform
3846 * @param ParserOptions $options options
3847 * @return string the text with variables substituted
3850 function transformMsg( $text, $options ) {
3852 static $executing = false;
3854 $fname = "Parser::transformMsg";
3856 # Guard against infinite recursion
3862 wfProfileIn($fname);
3864 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3865 $this->mTitle
= $wgTitle;
3867 $this->mTitle
= Title
::newFromText('msg');
3869 $this->mOptions
= $options;
3870 $this->setOutputType( OT_MSG
);
3871 $this->clearState();
3872 $text = $this->replaceVariables( $text );
3875 wfProfileOut($fname);
3880 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3881 * The callback should have the following form:
3882 * function myParserHook( $text, $params, &$parser ) { ... }
3884 * Transform and return $text. Use $parser for any required context, e.g. use
3885 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3889 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3890 * @param mixed $callback The callback function (and object) to use for the tag
3892 * @return The old value of the mTagHooks array associated with the hook
3894 function setHook( $tag, $callback ) {
3895 $tag = strtolower( $tag );
3896 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3897 $this->mTagHooks
[$tag] = $callback;
3903 * Create a function, e.g. {{sum:1|2|3}}
3904 * The callback function should have the form:
3905 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3907 * The callback may either return the text result of the function, or an array with the text
3908 * in element 0, and a number of flags in the other elements. The names of the flags are
3909 * specified in the keys. Valid flags are:
3910 * found The text returned is valid, stop processing the template. This
3912 * nowiki Wiki markup in the return value should be escaped
3913 * noparse Unsafe HTML tags should not be stripped, etc.
3914 * noargs Don't replace triple-brace arguments in the return value
3915 * isHTML The returned text is HTML, armour it against wikitext transformation
3919 * @param string $id The magic word ID
3920 * @param mixed $callback The callback function (and object) to use
3921 * @param integer $flags a combination of the following flags:
3922 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3924 * @return The old callback function for this name, if any
3926 function setFunctionHook( $id, $callback, $flags = 0 ) {
3927 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3928 $this->mFunctionHooks
[$id] = $callback;
3930 # Add to function cache
3931 $mw = MagicWord
::get( $id );
3933 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3935 $synonyms = $mw->getSynonyms();
3936 $sensitive = intval( $mw->isCaseSensitive() );
3938 foreach ( $synonyms as $syn ) {
3940 if ( !$sensitive ) {
3941 $syn = strtolower( $syn );
3944 if ( !( $flags & SFH_NO_HASH
) ) {
3947 # Remove trailing colon
3948 if ( substr( $syn, -1, 1 ) == ':' ) {
3949 $syn = substr( $syn, 0, -1 );
3951 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3957 * Get all registered function hook identifiers
3961 function getFunctionHooks() {
3962 return array_keys( $this->mFunctionHooks
);
3966 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3967 * Placeholders created in Skin::makeLinkObj()
3968 * Returns an array of links found, indexed by PDBK:
3972 * $options is a bit field, RLH_FOR_UPDATE to select for update
3974 function replaceLinkHolders( &$text, $options = 0 ) {
3978 $fname = 'Parser::replaceLinkHolders';
3979 wfProfileIn( $fname );
3983 $sk = $this->mOptions
->getSkin();
3984 $linkCache =& LinkCache
::singleton();
3986 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3987 wfProfileIn( $fname.'-check' );
3988 $dbr = wfGetDB( DB_SLAVE
);
3989 $page = $dbr->tableName( 'page' );
3990 $threshold = $wgUser->getOption('stubthreshold');
3993 asort( $this->mLinkHolders
['namespaces'] );
3998 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4000 $title = $this->mLinkHolders
['titles'][$key];
4002 # Skip invalid entries.
4003 # Result will be ugly, but prevents crash.
4004 if ( is_null( $title ) ) {
4007 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4009 # Check if it's a static known link, e.g. interwiki
4010 if ( $title->isAlwaysKnown() ) {
4011 $colours[$pdbk] = 1;
4012 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4013 $colours[$pdbk] = 1;
4014 $this->mOutput
->addLink( $title, $id );
4015 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4016 $colours[$pdbk] = 0;
4018 # Not in the link cache, add it to the query
4019 if ( !isset( $current ) ) {
4021 $query = "SELECT page_id, page_namespace, page_title";
4022 if ( $threshold > 0 ) {
4023 $query .= ', page_len, page_is_redirect';
4025 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4026 } elseif ( $current != $ns ) {
4028 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4033 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4038 if ( $options & RLH_FOR_UPDATE
) {
4039 $query .= ' FOR UPDATE';
4042 $res = $dbr->query( $query, $fname );
4044 # Fetch data and form into an associative array
4045 # non-existent = broken
4048 while ( $s = $dbr->fetchObject($res) ) {
4049 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4050 $pdbk = $title->getPrefixedDBkey();
4051 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4052 $this->mOutput
->addLink( $title, $s->page_id
);
4054 if ( $threshold > 0 ) {
4055 $size = $s->page_len
;
4056 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4057 $colours[$pdbk] = 1;
4059 $colours[$pdbk] = 2;
4062 $colours[$pdbk] = 1;
4066 wfProfileOut( $fname.'-check' );
4068 # Do a second query for different language variants of links and categories
4069 if($wgContLang->hasVariants()){
4070 $linkBatch = new LinkBatch();
4071 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4072 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4073 $varCategories = array(); // category replacements oldDBkey => newDBkey
4075 $categories = $this->mOutput
->getCategoryLinks();
4077 // Add variants of links to link batch
4078 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4079 $title = $this->mLinkHolders
['titles'][$key];
4080 if ( is_null( $title ) )
4083 $pdbk = $title->getPrefixedDBkey();
4084 $titleText = $title->getText();
4086 // generate all variants of the link title text
4087 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4089 // if link was not found (in first query), add all variants to query
4090 if ( !isset($colours[$pdbk]) ){
4091 foreach($allTextVariants as $textVariant){
4092 if($textVariant != $titleText){
4093 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4094 if(is_null($variantTitle)) continue;
4095 $linkBatch->addObj( $variantTitle );
4096 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4102 // process categories, check if a category exists in some variant
4103 foreach( $categories as $category){
4104 $variants = $wgContLang->convertLinkToAllVariants($category);
4105 foreach($variants as $variant){
4106 if($variant != $category){
4107 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4108 if(is_null($variantTitle)) continue;
4109 $linkBatch->addObj( $variantTitle );
4110 $categoryMap[$variant] = $category;
4116 if(!$linkBatch->isEmpty()){
4118 $titleClause = $linkBatch->constructSet('page', $dbr);
4120 $variantQuery = "SELECT page_id, page_namespace, page_title";
4121 if ( $threshold > 0 ) {
4122 $variantQuery .= ', page_len, page_is_redirect';
4125 $variantQuery .= " FROM $page WHERE $titleClause";
4126 if ( $options & RLH_FOR_UPDATE
) {
4127 $variantQuery .= ' FOR UPDATE';
4130 $varRes = $dbr->query( $variantQuery, $fname );
4132 // for each found variants, figure out link holders and replace
4133 while ( $s = $dbr->fetchObject($varRes) ) {
4135 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4136 $varPdbk = $variantTitle->getPrefixedDBkey();
4137 $vardbk = $variantTitle->getDBkey();
4139 $holderKeys = array();
4140 if(isset($variantMap[$varPdbk])){
4141 $holderKeys = $variantMap[$varPdbk];
4142 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4143 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4146 // loop over link holders
4147 foreach($holderKeys as $key){
4148 $title = $this->mLinkHolders
['titles'][$key];
4149 if ( is_null( $title ) ) continue;
4151 $pdbk = $title->getPrefixedDBkey();
4153 if(!isset($colours[$pdbk])){
4154 // found link in some of the variants, replace the link holder data
4155 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4156 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4158 // set pdbk and colour
4159 $pdbks[$key] = $varPdbk;
4160 if ( $threshold > 0 ) {
4161 $size = $s->page_len
;
4162 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4163 $colours[$varPdbk] = 1;
4165 $colours[$varPdbk] = 2;
4169 $colours[$varPdbk] = 1;
4174 // check if the object is a variant of a category
4175 if(isset($categoryMap[$vardbk])){
4176 $oldkey = $categoryMap[$vardbk];
4177 if($oldkey != $vardbk)
4178 $varCategories[$oldkey]=$vardbk;
4182 // rebuild the categories in original order (if there are replacements)
4183 if(count($varCategories)>0){
4185 $originalCats = $this->mOutput
->getCategories();
4186 foreach($originalCats as $cat => $sortkey){
4187 // make the replacement
4188 if( array_key_exists($cat,$varCategories) )
4189 $newCats[$varCategories[$cat]] = $sortkey;
4190 else $newCats[$cat] = $sortkey;
4192 $this->mOutput
->setCategoryLinks($newCats);
4197 # Construct search and replace arrays
4198 wfProfileIn( $fname.'-construct' );
4199 $replacePairs = array();
4200 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4201 $pdbk = $pdbks[$key];
4202 $searchkey = "<!--LINK $key-->";
4203 $title = $this->mLinkHolders
['titles'][$key];
4204 if ( empty( $colours[$pdbk] ) ) {
4205 $linkCache->addBadLinkObj( $title );
4206 $colours[$pdbk] = 0;
4207 $this->mOutput
->addLink( $title, 0 );
4208 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4209 $this->mLinkHolders
['texts'][$key],
4210 $this->mLinkHolders
['queries'][$key] );
4211 } elseif ( $colours[$pdbk] == 1 ) {
4212 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4213 $this->mLinkHolders
['texts'][$key],
4214 $this->mLinkHolders
['queries'][$key] );
4215 } elseif ( $colours[$pdbk] == 2 ) {
4216 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4217 $this->mLinkHolders
['texts'][$key],
4218 $this->mLinkHolders
['queries'][$key] );
4221 $replacer = new HashtableReplacer( $replacePairs, 1 );
4222 wfProfileOut( $fname.'-construct' );
4225 wfProfileIn( $fname.'-replace' );
4226 $text = preg_replace_callback(
4227 '/(<!--LINK .*?-->)/',
4231 wfProfileOut( $fname.'-replace' );
4234 # Now process interwiki link holders
4235 # This is quite a bit simpler than internal links
4236 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4237 wfProfileIn( $fname.'-interwiki' );
4238 # Make interwiki link HTML
4239 $replacePairs = array();
4240 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4241 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4242 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4244 $replacer = new HashtableReplacer( $replacePairs, 1 );
4246 $text = preg_replace_callback(
4247 '/<!--IWLINK (.*?)-->/',
4250 wfProfileOut( $fname.'-interwiki' );
4253 wfProfileOut( $fname );
4258 * Replace <!--LINK--> link placeholders with plain text of links
4259 * (not HTML-formatted).
4260 * @param string $text
4263 function replaceLinkHoldersText( $text ) {
4264 $fname = 'Parser::replaceLinkHoldersText';
4265 wfProfileIn( $fname );
4267 $text = preg_replace_callback(
4268 '/<!--(LINK|IWLINK) (.*?)-->/',
4269 array( &$this, 'replaceLinkHoldersTextCallback' ),
4272 wfProfileOut( $fname );
4277 * @param array $matches
4281 function replaceLinkHoldersTextCallback( $matches ) {
4282 $type = $matches[1];
4284 if( $type == 'LINK' ) {
4285 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4286 return $this->mLinkHolders
['texts'][$key];
4288 } elseif( $type == 'IWLINK' ) {
4289 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4290 return $this->mInterwikiLinkHolders
['texts'][$key];
4297 * Tag hook handler for 'pre'.
4299 function renderPreTag( $text, $attribs ) {
4300 // Backwards-compatibility hack
4301 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4303 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4304 return wfOpenElement( 'pre', $attribs ) .
4305 Xml
::escapeTagsOnly( $content ) .
4310 * Renders an image gallery from a text with one line per image.
4311 * text labels may be given by using |-style alternative text. E.g.
4312 * Image:one.jpg|The number "1"
4313 * Image:tree.jpg|A tree
4314 * given as text will return the HTML of a gallery with two images,
4315 * labeled 'The number "1"' and
4318 function renderImageGallery( $text, $params ) {
4319 $ig = new ImageGallery();
4320 $ig->setContextTitle( $this->mTitle
);
4321 $ig->setShowBytes( false );
4322 $ig->setShowFilename( false );
4324 $ig->useSkin( $this->mOptions
->getSkin() );
4326 if( isset( $params['caption'] ) ) {
4327 $caption = $params['caption'];
4328 $caption = htmlspecialchars( $caption );
4329 $caption = $this->replaceInternalLinks( $caption );
4330 $ig->setCaptionHtml( $caption );
4332 if( isset( $params['perrow'] ) ) {
4333 $ig->setPerRow( $params['perrow'] );
4335 if( isset( $params['widths'] ) ) {
4336 $ig->setWidths( $params['widths'] );
4338 if( isset( $params['heights'] ) ) {
4339 $ig->setHeights( $params['heights'] );
4342 $lines = explode( "\n", $text );
4343 foreach ( $lines as $line ) {
4344 # match lines like these:
4345 # Image:someimage.jpg|This is some image
4347 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4349 if ( count( $matches ) == 0 ) {
4352 $tp = Title
::newFromText( $matches[1] );
4354 if( is_null( $nt ) ) {
4355 # Bogus title. Ignore these so we don't bomb out later.
4358 if ( isset( $matches[3] ) ) {
4359 $label = $matches[3];
4364 $pout = $this->parse( $label,
4367 false, // Strip whitespace...?
4368 false // Don't clear state!
4370 $html = $pout->getText();
4372 $ig->add( new Image( $nt ), $html );
4374 # Only add real images (bug #5586)
4375 if ( $nt->getNamespace() == NS_IMAGE
) {
4376 $this->mOutput
->addImage( $nt->getDBkey() );
4379 return $ig->toHTML();
4383 * Parse image options text and use it to make an image
4385 function makeImage( $nt, $options ) {
4386 global $wgUseImageResize, $wgDjvuRenderer;
4388 # Check if the options text is of the form "options|alt text"
4390 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4391 # * left no resizing, just left align. label is used for alt= only
4392 # * right same, but right aligned
4393 # * none same, but not aligned
4394 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4395 # * center center the image
4396 # * framed Keep original image size, no magnify-button.
4397 # vertical-align values (no % or length right now):
4407 $part = array_map( 'trim', explode( '|', $options) );
4410 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4411 foreach ( $alignments as $alignment ) {
4412 $mwAlign[$alignment] =& MagicWord
::get( 'img_'.$alignment );
4414 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4415 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4416 $mwWidth =& MagicWord
::get( 'img_width' );
4417 $mwFramed =& MagicWord
::get( 'img_framed' );
4418 $mwPage =& MagicWord
::get( 'img_page' );
4421 $width = $height = $framed = $thumb = false;
4423 $manual_thumb = '' ;
4424 $align = $valign = '';
4426 foreach( $part as $val ) {
4427 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4429 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4430 # use manually specified thumbnail
4432 $manual_thumb = $match;
4434 foreach( $alignments as $alignment ) {
4435 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4436 switch ( $alignment ) {
4437 case 'left': case 'right': case 'center': case 'none':
4438 $align = $alignment; break;
4440 $valign = $alignment;
4445 if ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4446 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4447 # Select a page in a multipage document
4449 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4450 wfDebug( "img_width match: $match\n" );
4451 # $match is the image width in pixels
4453 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4454 $width = intval( $m[1] );
4455 $height = intval( $m[2] );
4457 $width = intval($match);
4459 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4466 # Strip bad stuff out of the alt text
4467 $alt = $this->replaceLinkHoldersText( $caption );
4469 # make sure there are no placeholders in thumbnail attributes
4470 # that are later expanded to html- so expand them now and
4472 $alt = $this->mStripState
->unstripBoth( $alt );
4473 $alt = Sanitizer
::stripAllTags( $alt );
4475 # Linker does the rest
4476 $sk = $this->mOptions
->getSkin();
4477 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page, $valign );
4481 * Set a flag in the output object indicating that the content is dynamic and
4482 * shouldn't be cached.
4484 function disableCache() {
4485 wfDebug( "Parser output marked as uncacheable.\n" );
4486 $this->mOutput
->mCacheTime
= -1;
4490 * Callback from the Sanitizer for expanding items found in HTML attribute
4491 * values, so they can be safely tested and escaped.
4492 * @param string $text
4493 * @param array $args
4497 function attributeStripCallback( &$text, $args ) {
4498 $text = $this->replaceVariables( $text, $args );
4499 $text = $this->mStripState
->unstripBoth( $text );
4508 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4509 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4510 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4516 function getTags() { return array_keys( $this->mTagHooks
); }
4521 * Break wikitext input into sections, and either pull or replace
4522 * some particular section's text.
4524 * External callers should use the getSection and replaceSection methods.
4526 * @param $text Page wikitext
4527 * @param $section Numbered section. 0 pulls the text before the first
4528 * heading; other numbers will pull the given section
4529 * along with its lower-level subsections.
4530 * @param $mode One of "get" or "replace"
4531 * @param $newtext Replacement text for section data.
4532 * @return string for "get", the extracted section text.
4533 * for "replace", the whole page with the section replaced.
4535 private function extractSections( $text, $section, $mode, $newtext='' ) {
4536 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4537 # comments to be stripped as well)
4538 $stripState = new StripState
;
4540 $oldOutputType = $this->mOutputType
;
4541 $oldOptions = $this->mOptions
;
4542 $this->mOptions
= new ParserOptions();
4543 $this->setOutputType( OT_WIKI
);
4545 $striptext = $this->strip( $text, $stripState, true );
4547 $this->setOutputType( $oldOutputType );
4548 $this->mOptions
= $oldOptions;
4550 # now that we can be sure that no pseudo-sections are in the source,
4551 # split it up by section
4552 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4553 $comment = "(?:$uniq-!--.*?QINU)";
4558 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4559 (=+) # Should this be limited to 6?
4560 .+? # Section title...
4561 \\2 # Ending = count must match start
4562 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4571 PREG_SPLIT_DELIM_CAPTURE
);
4573 if( $mode == "get" ) {
4574 if( $section == 0 ) {
4575 // "Section 0" returns the content before any other section.
4578 //track missing section, will replace if found.
4581 } elseif( $mode == "replace" ) {
4582 if( $section == 0 ) {
4583 $rv = $newtext . "\n\n";
4592 for( $index = 1; $index < count( $secs ); ) {
4593 $headerLine = $secs[$index++
];
4594 if( $secs[$index] ) {
4596 $headerLevel = strlen( $secs[$index++
] );
4600 $headerLevel = intval( $secs[$index++
] );
4602 $content = $secs[$index++
];
4605 if( $mode == "get" ) {
4606 if( $count == $section ) {
4607 $rv = $headerLine . $content;
4608 $sectionLevel = $headerLevel;
4609 } elseif( $count > $section ) {
4610 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4611 $rv .= $headerLine . $content;
4613 // Broke out to a higher-level section
4617 } elseif( $mode == "replace" ) {
4618 if( $count < $section ) {
4619 $rv .= $headerLine . $content;
4620 } elseif( $count == $section ) {
4621 $rv .= $newtext . "\n\n";
4622 $sectionLevel = $headerLevel;
4623 } elseif( $count > $section ) {
4624 if( $headerLevel <= $sectionLevel ) {
4625 // Passed the section's sub-parts.
4629 $rv .= $headerLine . $content;
4635 # reinsert stripped tags
4636 $rv = trim( $stripState->unstripBoth( $rv ) );
4642 * This function returns the text of a section, specified by a number ($section).
4643 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4644 * the first section before any such heading (section 0).
4646 * If a section contains subsections, these are also returned.
4648 * @param $text String: text to look in
4649 * @param $section Integer: section number
4650 * @param $deftext: default to return if section is not found
4651 * @return string text of the requested section
4653 public function getSection( $text, $section, $deftext='' ) {
4654 return $this->extractSections( $text, $section, "get", $deftext );
4657 public function replaceSection( $oldtext, $section, $text ) {
4658 return $this->extractSections( $oldtext, $section, "replace", $text );
4662 * Get the timestamp associated with the current revision, adjusted for
4663 * the default server-local timestamp
4665 function getRevisionTimestamp() {
4666 if ( is_null( $this->mRevisionTimestamp
) ) {
4667 wfProfileIn( __METHOD__
);
4669 $dbr = wfGetDB( DB_SLAVE
);
4670 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4671 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4673 // Normalize timestamp to internal MW format for timezone processing.
4674 // This has the added side-effect of replacing a null value with
4675 // the current time, which gives us more sensible behavior for
4677 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4679 // The cryptic '' timezone parameter tells to use the site-default
4680 // timezone offset instead of the user settings.
4682 // Since this value will be saved into the parser cache, served
4683 // to other users, and potentially even used inside links and such,
4684 // it needs to be consistent for all visitors.
4685 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4687 wfProfileOut( __METHOD__
);
4689 return $this->mRevisionTimestamp
;
4693 * Mutator for $mDefaultSort
4695 * @param $sort New value
4697 public function setDefaultSort( $sort ) {
4698 $this->mDefaultSort
= $sort;
4702 * Accessor for $mDefaultSort
4703 * Will use the title/prefixed title if none is set
4707 public function getDefaultSort() {
4708 if( $this->mDefaultSort
!== false ) {
4709 return $this->mDefaultSort
;
4711 return $this->mTitle
->getNamespace() == NS_CATEGORY
4712 ?
$this->mTitle
->getText()
4713 : $this->mTitle
->getPrefixedText();
4720 * @todo document, briefly.
4722 class OnlyIncludeReplacer
{
4725 function replace( $matches ) {
4726 if ( substr( $matches[1], -1 ) == "\n" ) {
4727 $this->output
.= substr( $matches[1], 0, -1 );
4729 $this->output
.= $matches[1];
4735 * @todo document, briefly.
4738 var $general, $nowiki;
4740 function __construct() {
4741 $this->general
= new ReplacementArray
;
4742 $this->nowiki
= new ReplacementArray
;
4745 function unstripGeneral( $text ) {
4746 wfProfileIn( __METHOD__
);
4747 $text = $this->general
->replace( $text );
4748 wfProfileOut( __METHOD__
);
4752 function unstripNoWiki( $text ) {
4753 wfProfileIn( __METHOD__
);
4754 $text = $this->nowiki
->replace( $text );
4755 wfProfileOut( __METHOD__
);
4759 function unstripBoth( $text ) {
4760 wfProfileIn( __METHOD__
);
4761 $text = $this->general
->replace( $text );
4762 $text = $this->nowiki
->replace( $text );
4763 wfProfileOut( __METHOD__
);