3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
131 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
132 $this->mUrlProtocols
= wfUrlProtocols();
133 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
134 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
135 $this->mVarCache
= array();
136 if ( isset( $conf['preprocessorClass'] ) ) {
137 $this->mPreprocessorClass
= $conf['preprocessorClass'];
138 } elseif ( extension_loaded( 'domxml' ) ) {
139 // PECL extension that conflicts with the core DOM extension (bug 13770)
140 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
141 $this->mPreprocessorClass
= 'Preprocessor_Hash';
142 } elseif ( extension_loaded( 'dom' ) ) {
143 $this->mPreprocessorClass
= 'Preprocessor_DOM';
145 $this->mPreprocessorClass
= 'Preprocessor_Hash';
147 $this->mMarkerIndex
= 0;
148 $this->mFirstCall
= true;
152 * Reduce memory usage to reduce the impact of circular references
154 function __destruct() {
155 if ( isset( $this->mLinkHolders
) ) {
156 $this->mLinkHolders
->__destruct();
158 foreach ( $this as $name => $value ) {
159 unset( $this->$name );
164 * Do various kinds of initialisation on the first call of the parser
166 function firstCallInit() {
167 if ( !$this->mFirstCall
) {
170 $this->mFirstCall
= false;
172 wfProfileIn( __METHOD__
);
174 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
175 CoreParserFunctions
::register( $this );
176 $this->initialiseVariables();
178 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
179 wfProfileOut( __METHOD__
);
187 function clearState() {
188 wfProfileIn( __METHOD__
);
189 if ( $this->mFirstCall
) {
190 $this->firstCallInit();
192 $this->mOutput
= new ParserOutput
;
193 $this->mAutonumber
= 0;
194 $this->mLastSection
= '';
195 $this->mDTopen
= false;
196 $this->mIncludeCount
= array();
197 $this->mStripState
= new StripState
;
198 $this->mArgStack
= false;
199 $this->mInPre
= false;
200 $this->mLinkHolders
= new LinkHolderArray( $this );
202 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
205 * Prefix for temporary replacement strings for the multipass parser.
206 * \x07 should never appear in input as it's disallowed in XML.
207 * Using it at the front also gives us a little extra robustness
208 * since it shouldn't match when butted up against identifier-like
211 * Must not consist of all title characters, or else it will change
212 * the behaviour of <nowiki> in a link.
214 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
215 # Changed to \x7f to allow XML double-parsing -- TS
216 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
219 # Clear these on every parse, bug 4549
220 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
222 $this->mShowToc
= true;
223 $this->mForceTocPosition
= false;
224 $this->mIncludeSizes
= array(
228 $this->mPPNodeCount
= 0;
229 $this->mDefaultSort
= false;
230 $this->mHeadings
= array();
231 $this->mDoubleUnderscores
= array();
232 $this->mExpensiveFunctionCount
= 0;
233 $this->mFileCache
= array();
236 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
237 $this->mPreprocessor
= null;
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__
);
244 function setOutputType( $ot ) {
245 $this->mOutputType
= $ot;
248 'html' => $ot == self
::OT_HTML
,
249 'wiki' => $ot == self
::OT_WIKI
,
250 'pre' => $ot == self
::OT_PREPROCESS
,
255 * Set the context title
257 function setTitle( $t ) {
258 if ( !$t ||
$t instanceof FakeTitle
) {
259 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if( !isset( $this->mUniqPrefix
) ) {
277 // @fixme this is probably *horribly wrong*
278 // LanguageConverter seems to want $wgParser's uniqPrefix, however
279 // if this is called for a parser cache hit, the parser may not
280 // have ever been initialized in the first place.
281 // Not really sure what the heck is supposed to be going on here.
283 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title );
317 $oldRevisionId = $this->mRevisionId
;
318 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
319 if( $revid !== null ) {
320 $this->mRevisionId
= $revid;
321 $this->mRevisionTimestamp
= null;
323 $this->setOutputType( self
::OT_HTML
);
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
327 $text = $this->internalParse( $text );
328 $text = $this->mStripState
->unstripGeneral( $text );
330 # Clean up special characters, only run once, next-to-last before doBlockLevels
332 # french spaces, last one Guillemet-left
333 # only if there is something before the space
334 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
335 # french spaces, Guillemet-right
336 '/(\\302\\253) /' => '\\1 ',
337 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
339 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
341 $text = $this->doBlockLevels( $text, $linestart );
343 $this->replaceLinkHolders( $text );
345 # the position of the parserConvert() call should not be changed. it
346 # assumes that the links are all replaced and the only thing left
347 # is the <nowiki> mark.
348 # Side-effects: this calls $this->mOutput->setTitleText()
349 $text = $wgContLang->parserConvert( $text, $this );
351 $text = $this->mStripState
->unstripNoWiki( $text );
353 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
355 //!JF Move to its own function
357 $uniq_prefix = $this->mUniqPrefix
;
359 $elements = array_keys( $this->mTransparentTagHooks
);
360 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
362 foreach( $matches as $marker => $data ) {
363 list( $element, $content, $params, $tag ) = $data;
364 $tagName = strtolower( $element );
365 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
366 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
367 array( $content, $params, $this ) );
371 $this->mStripState
->general
->setPair( $marker, $output );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 $text = Sanitizer
::normalizeCharReferences( $text );
377 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
378 $text = self
::tidy($text);
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3<div\\5>\\6</div>\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 global $wgExpensiveParserFunctionLimit;
416 $max = $this->mOptions
->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
427 $this->mOutput
->setText( $text );
428 $this->mRevisionId
= $oldRevisionId;
429 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__
);
433 return $this->mOutput
;
437 * Recursive parser entry point that can be called from an extension tag
440 function recursiveTagParse( $text ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Get a random string
476 function getRandomString() {
477 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
480 function &getTitle() { return $this->mTitle
; }
481 function getOptions() { return $this->mOptions
; }
482 function getRevisionId() { return $this->mRevisionId
; }
483 function getOutput() { return $this->mOutput
; }
484 function nextLinkID() { return $this->mLinkID++
; }
486 function getFunctionLang() {
487 global $wgLang, $wgContLang;
489 $target = $this->mOptions
->getTargetLanguage();
490 if ( $target !== null ) {
493 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
498 * Get a preprocessor object
500 function getPreprocessor() {
501 if ( !isset( $this->mPreprocessor
) ) {
502 $class = $this->mPreprocessorClass
;
503 $this->mPreprocessor
= new $class( $this );
505 return $this->mPreprocessor
;
509 * Replaces all occurrences of HTML-style comments and the given tags
510 * in the text with a random marker and returns the next text. The output
511 * parameter $matches will be an associative array filled with data in
513 * 'UNIQ-xxxxx' => array(
516 * array( 'param' => 'x' ),
517 * '<element param="x">tag content</element>' ) )
519 * @param $elements list of element names. Comments are always extracted.
520 * @param $text Source text string.
521 * @param $uniq_prefix
526 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
531 $taglist = implode( '|', $elements );
532 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
534 while ( '' != $text ) {
535 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
537 if( count( $p ) < 5 ) {
540 if( count( $p ) > 5 ) {
554 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
555 $stripped .= $marker;
557 if ( $close === '/>' ) {
558 // Empty element tag, <tag />
563 if( $element === '!--' ) {
566 $end = "/(<\\/$element\\s*>)/i";
568 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
570 if( count( $q ) < 3 ) {
571 # No end tag -- let it run out to the end of the text.
580 $matches[$marker] = array( $element,
582 Sanitizer
::decodeTagAttributes( $attributes ),
583 "<$element$attributes$close$content$tail" );
589 * Get a list of strippable XML-like elements
591 function getStripList() {
593 $elements = $this->mStripList
;
595 $elements[] = 'html';
597 if( $this->mOptions
->getUseTeX() ) {
598 $elements[] = 'math';
604 * @deprecated use replaceVariables
606 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
611 * Restores pre, math, and other extensions removed by strip()
613 * always call unstripNoWiki() after this one
615 * @deprecated use $this->mStripState->unstrip()
617 function unstrip( $text, $state ) {
618 return $state->unstripGeneral( $text );
622 * Always call this after unstrip() to preserve the order
625 * @deprecated use $this->mStripState->unstrip()
627 function unstripNoWiki( $text, $state ) {
628 return $state->unstripNoWiki( $text );
632 * @deprecated use $this->mStripState->unstripBoth()
634 function unstripForHTML( $text ) {
635 return $this->mStripState
->unstripBoth( $text );
639 * Add an item to the strip state
640 * Returns the unique tag which must be inserted into the stripped text
641 * The tag will be replaced with the original text in unstrip()
645 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
647 $this->mMarkerIndex++
;
648 $this->mStripState
->general
->setPair( $rnd, $text );
653 * Interface with html tidy, used if $wgUseTidy = true.
654 * If tidy isn't able to correct the markup, the original will be
655 * returned in all its glory with a warning comment appended.
657 * Either the external tidy program or the in-process tidy extension
658 * will be used depending on availability. Override the default
659 * $wgTidyInternal setting to disable the internal if it's not working.
661 * @param string $text Hideous HTML input
662 * @return string Corrected HTML output
666 function tidy( $text ) {
667 global $wgTidyInternal;
669 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
670 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
671 '<head><title>test</title></head><body>'.$text.'</body></html>';
673 # Tidy is known to clobber tabs; convert 'em to entities
674 $wrappedtext = str_replace("\t", '	', $wrappedtext);
676 if( $wgTidyInternal ) {
677 $correctedtext = self
::internalTidy( $wrappedtext );
679 $correctedtext = self
::externalTidy( $wrappedtext );
681 if( is_null( $correctedtext ) ) {
682 wfDebug( "Tidy error detected!\n" );
683 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
686 # Convert the tabs back from entities
687 $correctedtext = str_replace('	', "\t", $correctedtext);
689 return $correctedtext;
693 * Spawn an external HTML tidy process and get corrected markup back from it.
698 function externalTidy( $text ) {
699 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
700 wfProfileIn( __METHOD__
);
705 $descriptorspec = array(
706 0 => array('pipe', 'r'),
707 1 => array('pipe', 'w'),
708 2 => array('file', wfGetNull(), 'a')
711 if( function_exists('proc_open') ) {
712 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
713 if (is_resource($process)) {
714 // Theoretically, this style of communication could cause a deadlock
715 // here. If the stdout buffer fills up, then writes to stdin could
716 // block. This doesn't appear to happen with tidy, because tidy only
717 // writes to stdout after it's finished reading from stdin. Search
718 // for tidyParseStdin and tidySaveStdout in console/tidy.c
719 fwrite($pipes[0], $text);
721 while (!feof($pipes[1])) {
722 $cleansource .= fgets($pipes[1], 1024);
725 proc_close($process);
729 wfProfileOut( __METHOD__
);
731 if( $cleansource == '' && $text != '') {
732 // Some kind of error happened, so we couldn't get the corrected text.
733 // Just give up; we'll use the source text and append a warning.
741 * Use the HTML tidy PECL extension to use the tidy library in-process,
742 * saving the overhead of spawning a new process.
744 * 'pear install tidy' should be able to compile the extension module.
749 function internalTidy( $text ) {
750 global $wgTidyConf, $IP, $wgDebugTidy;
751 wfProfileIn( __METHOD__
);
754 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
755 $tidy->cleanRepair();
756 if( $tidy->getStatus() == 2 ) {
757 // 2 is magic number for fatal error
758 // http://www.php.net/manual/en/function.tidy-get-status.php
761 $cleansource = tidy_get_output( $tidy );
763 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
764 $cleansource .= "<!--\nTidy reports:\n" .
765 str_replace( '-->', '-->', $tidy->errorBuffer
) .
769 wfProfileOut( __METHOD__
);
774 * parse the wiki syntax used to render tables
778 function doTableStuff ( $text ) {
779 wfProfileIn( __METHOD__
);
781 $lines = StringUtils
::explode( "\n", $text );
783 $td_history = array (); // Is currently a td tag open?
784 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
785 $tr_history = array (); // Is currently a tr tag open?
786 $tr_attributes = array (); // history of tr attributes
787 $has_opened_tr = array(); // Did this table open a <tr> element?
788 $indent_level = 0; // indent level of the table
790 foreach ( $lines as $outLine ) {
791 $line = trim( $outLine );
793 if( $line == '' ) { // empty line, go to next line
794 $out .= $outLine."\n";
797 $first_character = $line[0];
800 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
801 // First check if we are starting a new table
802 $indent_level = strlen( $matches[1] );
804 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
805 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
807 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
808 array_push ( $td_history , false );
809 array_push ( $last_tag_history , '' );
810 array_push ( $tr_history , false );
811 array_push ( $tr_attributes , '' );
812 array_push ( $has_opened_tr , false );
813 } else if ( count ( $td_history ) == 0 ) {
814 // Don't do any of the following
815 $out .= $outLine."\n";
817 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
818 // We are ending a table
819 $line = '</table>' . substr ( $line , 2 );
820 $last_tag = array_pop ( $last_tag_history );
822 if ( !array_pop ( $has_opened_tr ) ) {
823 $line = "<tr><td></td></tr>{$line}";
826 if ( array_pop ( $tr_history ) ) {
827 $line = "</tr>{$line}";
830 if ( array_pop ( $td_history ) ) {
831 $line = "</{$last_tag}>{$line}";
833 array_pop ( $tr_attributes );
834 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
835 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
836 // Now we have a table row
837 $line = preg_replace( '#^\|-+#', '', $line );
839 // Whats after the tag is now only attributes
840 $attributes = $this->mStripState
->unstripBoth( $line );
841 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
842 array_pop ( $tr_attributes );
843 array_push ( $tr_attributes , $attributes );
846 $last_tag = array_pop ( $last_tag_history );
847 array_pop ( $has_opened_tr );
848 array_push ( $has_opened_tr , true );
850 if ( array_pop ( $tr_history ) ) {
854 if ( array_pop ( $td_history ) ) {
855 $line = "</{$last_tag}>{$line}";
859 array_push ( $tr_history , false );
860 array_push ( $td_history , false );
861 array_push ( $last_tag_history , '' );
863 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
864 // This might be cell elements, td, th or captions
865 if ( substr ( $line , 0 , 2 ) === '|+' ) {
866 $first_character = '+';
867 $line = substr ( $line , 1 );
870 $line = substr ( $line , 1 );
872 if ( $first_character === '!' ) {
873 $line = str_replace ( '!!' , '||' , $line );
876 // Split up multiple cells on the same line.
877 // FIXME : This can result in improper nesting of tags processed
878 // by earlier parser steps, but should avoid splitting up eg
879 // attribute values containing literal "||".
880 $cells = StringUtils
::explodeMarkup( '||' , $line );
884 // Loop through each table cell
885 foreach ( $cells as $cell )
888 if ( $first_character !== '+' )
890 $tr_after = array_pop ( $tr_attributes );
891 if ( !array_pop ( $tr_history ) ) {
892 $previous = "<tr{$tr_after}>\n";
894 array_push ( $tr_history , true );
895 array_push ( $tr_attributes , '' );
896 array_pop ( $has_opened_tr );
897 array_push ( $has_opened_tr , true );
900 $last_tag = array_pop ( $last_tag_history );
902 if ( array_pop ( $td_history ) ) {
903 $previous = "</{$last_tag}>{$previous}";
906 if ( $first_character === '|' ) {
908 } else if ( $first_character === '!' ) {
910 } else if ( $first_character === '+' ) {
911 $last_tag = 'caption';
916 array_push ( $last_tag_history , $last_tag );
918 // A cell could contain both parameters and data
919 $cell_data = explode ( '|' , $cell , 2 );
921 // Bug 553: Note that a '|' inside an invalid link should not
922 // be mistaken as delimiting cell parameters
923 if ( strpos( $cell_data[0], '[[' ) !== false ) {
924 $cell = "{$previous}<{$last_tag}>{$cell}";
925 } else if ( count ( $cell_data ) == 1 )
926 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
928 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
929 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
930 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
934 array_push ( $td_history , true );
937 $out .= $outLine . "\n";
940 // Closing open td, tr && table
941 while ( count ( $td_history ) > 0 )
943 if ( array_pop ( $td_history ) ) {
946 if ( array_pop ( $tr_history ) ) {
949 if ( !array_pop ( $has_opened_tr ) ) {
950 $out .= "<tr><td></td></tr>\n" ;
953 $out .= "</table>\n";
956 // Remove trailing line-ending (b/c)
957 if ( substr( $out, -1 ) === "\n" ) {
958 $out = substr( $out, 0, -1 );
961 // special case: don't return empty table
962 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
966 wfProfileOut( __METHOD__
);
972 * Helper function for parse() that transforms wiki markup into
973 * HTML. Only called for $mOutputType == self::OT_HTML.
977 function internalParse( $text ) {
979 wfProfileIn( __METHOD__
);
981 # Hook to suspend the parser in this state
982 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
983 wfProfileOut( __METHOD__
);
987 $text = $this->replaceVariables( $text );
988 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
989 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
991 // Tables need to come after variable replacement for things to work
992 // properly; putting them before other transformations should keep
993 // exciting things like link expansions from showing up in surprising
995 $text = $this->doTableStuff( $text );
997 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
999 $text = $this->doDoubleUnderscore( $text );
1000 $text = $this->doHeadings( $text );
1001 if($this->mOptions
->getUseDynamicDates()) {
1002 $df = DateFormatter
::getInstance();
1003 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1005 $text = $this->doAllQuotes( $text );
1006 $text = $this->replaceInternalLinks( $text );
1007 $text = $this->replaceExternalLinks( $text );
1009 # replaceInternalLinks may sometimes leave behind
1010 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1011 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1013 $text = $this->doMagicLinks( $text );
1014 $text = $this->formatHeadings( $text, $isMain );
1016 wfProfileOut( __METHOD__
);
1021 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1022 * magic external links.
1027 function doMagicLinks( $text ) {
1028 wfProfileIn( __METHOD__
);
1029 $prots = $this->mUrlProtocols
;
1030 $urlChar = self
::EXT_LINK_URL_CLASS
;
1031 $text = preg_replace_callback(
1033 (<a.*?</a>) | # m[1]: Skip link text
1034 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1035 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1036 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1037 ISBN\s+(\b # m[5]: ISBN, capture number
1038 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1039 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1040 [0-9Xx] # check digit
1042 )!x', array( &$this, 'magicLinkCallback' ), $text );
1043 wfProfileOut( __METHOD__
);
1047 function magicLinkCallback( $m ) {
1048 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1051 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1054 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1055 # Free external link
1056 return $this->makeFreeExternalLink( $m[0] );
1057 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1059 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1063 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1065 $urlmsg = 'pubmedurl';
1068 throw new MWException( __METHOD__
.': unrecognised match type "' .
1069 substr($m[0], 0, 20 ) . '"' );
1071 $url = wfMsg( $urlmsg, $id);
1072 $sk = $this->mOptions
->getSkin();
1073 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1074 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1075 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1078 $num = strtr( $isbn, array(
1083 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1085 $titleObj->escapeLocalUrl() .
1086 "\" class=\"internal\">ISBN $isbn</a>";
1093 * Make a free external link, given a user-supplied URL
1097 function makeFreeExternalLink( $url ) {
1099 wfProfileIn( __METHOD__
);
1101 $sk = $this->mOptions
->getSkin();
1104 # The characters '<' and '>' (which were escaped by
1105 # removeHTMLtags()) should not be included in
1106 # URLs, per RFC 2396.
1108 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1109 $trail = substr($url, $m2[0][1]) . $trail;
1110 $url = substr($url, 0, $m2[0][1]);
1113 # Move trailing punctuation to $trail
1115 # If there is no left bracket, then consider right brackets fair game too
1116 if ( strpos( $url, '(' ) === false ) {
1120 $numSepChars = strspn( strrev( $url ), $sep );
1121 if ( $numSepChars ) {
1122 $trail = substr( $url, -$numSepChars ) . $trail;
1123 $url = substr( $url, 0, -$numSepChars );
1126 $url = Sanitizer
::cleanUrl( $url );
1128 # Is this an external image?
1129 $text = $this->maybeMakeExternalImage( $url );
1130 if ( $text === false ) {
1131 # Not an image, make a link
1132 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1133 $this->getExternalLinkAttribs() );
1134 # Register it in the output object...
1135 # Replace unnecessary URL escape codes with their equivalent characters
1136 $pasteurized = self
::replaceUnusualEscapes( $url );
1137 $this->mOutput
->addExternalLink( $pasteurized );
1139 wfProfileOut( __METHOD__
);
1140 return $text . $trail;
1145 * Parse headers and return html
1149 function doHeadings( $text ) {
1150 wfProfileIn( __METHOD__
);
1151 for ( $i = 6; $i >= 1; --$i ) {
1152 $h = str_repeat( '=', $i );
1153 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1154 "<h$i>\\1</h$i>", $text );
1156 wfProfileOut( __METHOD__
);
1161 * Replace single quotes with HTML markup
1163 * @return string the altered text
1165 function doAllQuotes( $text ) {
1166 wfProfileIn( __METHOD__
);
1168 $lines = StringUtils
::explode( "\n", $text );
1169 foreach ( $lines as $line ) {
1170 $outtext .= $this->doQuotes( $line ) . "\n";
1172 $outtext = substr($outtext, 0,-1);
1173 wfProfileOut( __METHOD__
);
1178 * Helper function for doAllQuotes()
1180 public function doQuotes( $text ) {
1181 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1182 if ( count( $arr ) == 1 )
1186 # First, do some preliminary work. This may shift some apostrophes from
1187 # being mark-up to being text. It also counts the number of occurrences
1188 # of bold and italics mark-ups.
1192 foreach ( $arr as $r )
1194 if ( ( $i %
2 ) == 1 )
1196 # If there are ever four apostrophes, assume the first is supposed to
1197 # be text, and the remaining three constitute mark-up for bold text.
1198 if ( strlen( $arr[$i] ) == 4 )
1203 # If there are more than 5 apostrophes in a row, assume they're all
1204 # text except for the last 5.
1205 else if ( strlen( $arr[$i] ) > 5 )
1207 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1210 # Count the number of occurrences of bold and italics mark-ups.
1211 # We are not counting sequences of five apostrophes.
1212 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1213 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1214 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1219 # If there is an odd number of both bold and italics, it is likely
1220 # that one of the bold ones was meant to be an apostrophe followed
1221 # by italics. Which one we cannot know for certain, but it is more
1222 # likely to be one that has a single-letter word before it.
1223 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1226 $firstsingleletterword = -1;
1227 $firstmultiletterword = -1;
1229 foreach ( $arr as $r )
1231 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1233 $x1 = substr ($arr[$i-1], -1);
1234 $x2 = substr ($arr[$i-1], -2, 1);
1236 if ($firstspace == -1) $firstspace = $i;
1237 } else if ($x2 === ' ') {
1238 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1240 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1246 # If there is a single-letter word, use it!
1247 if ($firstsingleletterword > -1)
1249 $arr [ $firstsingleletterword ] = "''";
1250 $arr [ $firstsingleletterword-1 ] .= "'";
1252 # If not, but there's a multi-letter word, use that one.
1253 else if ($firstmultiletterword > -1)
1255 $arr [ $firstmultiletterword ] = "''";
1256 $arr [ $firstmultiletterword-1 ] .= "'";
1258 # ... otherwise use the first one that has neither.
1259 # (notice that it is possible for all three to be -1 if, for example,
1260 # there is only one pentuple-apostrophe in the line)
1261 else if ($firstspace > -1)
1263 $arr [ $firstspace ] = "''";
1264 $arr [ $firstspace-1 ] .= "'";
1268 # Now let's actually convert our apostrophic mush to HTML!
1273 foreach ($arr as $r)
1277 if ($state === 'both')
1284 if (strlen ($r) == 2)
1287 { $output .= '</i>'; $state = ''; }
1288 else if ($state === 'bi')
1289 { $output .= '</i>'; $state = 'b'; }
1290 else if ($state === 'ib')
1291 { $output .= '</b></i><b>'; $state = 'b'; }
1292 else if ($state === 'both')
1293 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1294 else # $state can be 'b' or ''
1295 { $output .= '<i>'; $state .= 'i'; }
1297 else if (strlen ($r) == 3)
1300 { $output .= '</b>'; $state = ''; }
1301 else if ($state === 'bi')
1302 { $output .= '</i></b><i>'; $state = 'i'; }
1303 else if ($state === 'ib')
1304 { $output .= '</b>'; $state = 'i'; }
1305 else if ($state === 'both')
1306 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1307 else # $state can be 'i' or ''
1308 { $output .= '<b>'; $state .= 'b'; }
1310 else if (strlen ($r) == 5)
1313 { $output .= '</b><i>'; $state = 'i'; }
1314 else if ($state === 'i')
1315 { $output .= '</i><b>'; $state = 'b'; }
1316 else if ($state === 'bi')
1317 { $output .= '</i></b>'; $state = ''; }
1318 else if ($state === 'ib')
1319 { $output .= '</b></i>'; $state = ''; }
1320 else if ($state === 'both')
1321 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1322 else # ($state == '')
1323 { $buffer = ''; $state = 'both'; }
1328 # Now close all remaining tags. Notice that the order is important.
1329 if ($state === 'b' ||
$state === 'ib')
1331 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1333 if ($state === 'bi')
1335 # There might be lonely ''''', so make sure we have a buffer
1336 if ($state === 'both' && $buffer)
1337 $output .= '<b><i>'.$buffer.'</i></b>';
1343 * Replace external links (REL)
1345 * Note: this is all very hackish and the order of execution matters a lot.
1346 * Make sure to run maintenance/parserTests.php if you change this code.
1350 function replaceExternalLinks( $text ) {
1352 wfProfileIn( __METHOD__
);
1354 $sk = $this->mOptions
->getSkin();
1356 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1357 $s = array_shift( $bits );
1360 while ( $i<count( $bits ) ) {
1362 $protocol = $bits[$i++
];
1363 $text = $bits[$i++
];
1364 $trail = $bits[$i++
];
1366 # The characters '<' and '>' (which were escaped by
1367 # removeHTMLtags()) should not be included in
1368 # URLs, per RFC 2396.
1370 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1371 $text = substr($url, $m2[0][1]) . ' ' . $text;
1372 $url = substr($url, 0, $m2[0][1]);
1375 # If the link text is an image URL, replace it with an <img> tag
1376 # This happened by accident in the original parser, but some people used it extensively
1377 $img = $this->maybeMakeExternalImage( $text );
1378 if ( $img !== false ) {
1384 # Set linktype for CSS - if URL==text, link is essentially free
1385 $linktype = ($text === $url) ?
'free' : 'text';
1387 # No link text, e.g. [http://domain.tld/some.link]
1388 if ( $text == '' ) {
1389 # Autonumber if allowed. See bug #5918
1390 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1391 $langObj = $this->getFunctionLang();
1392 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1393 $linktype = 'autonumber';
1395 # Otherwise just use the URL
1396 $text = htmlspecialchars( $url );
1400 # Have link text, e.g. [http://domain.tld/some.link text]s
1402 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1405 $text = $wgContLang->markNoConversion($text);
1407 $url = Sanitizer
::cleanUrl( $url );
1409 if ( $this->mOptions
->mExternalLinkTarget
) {
1410 $attribs = array( 'target' => $this->mOptions
->mExternalLinkTarget
);
1415 # Use the encoded URL
1416 # This means that users can paste URLs directly into the text
1417 # Funny characters like ö aren't valid in URLs anyway
1418 # This was changed in August 2004
1419 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->getExternalLinkAttribs() )
1422 # Register link in the output object.
1423 # Replace unnecessary URL escape codes with the referenced character
1424 # This prevents spammers from hiding links from the filters
1425 $pasteurized = self
::replaceUnusualEscapes( $url );
1426 $this->mOutput
->addExternalLink( $pasteurized );
1429 wfProfileOut( __METHOD__
);
1433 function getExternalLinkAttribs() {
1435 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1436 $ns = $this->mTitle
->getNamespace();
1437 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1438 $attribs['rel'] = 'nofollow';
1440 if ( $this->mOptions
->getExternalLinkTarget() ) {
1441 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1448 * Replace unusual URL escape codes with their equivalent characters
1452 * @todo This can merge genuinely required bits in the path or query string,
1453 * breaking legit URLs. A proper fix would treat the various parts of
1454 * the URL differently; as a workaround, just use the output for
1455 * statistical records, not for actual linking/output.
1457 static function replaceUnusualEscapes( $url ) {
1458 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1459 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1463 * Callback function used in replaceUnusualEscapes().
1464 * Replaces unusual URL escape codes with their equivalent character
1468 private static function replaceUnusualEscapesCallback( $matches ) {
1469 $char = urldecode( $matches[0] );
1470 $ord = ord( $char );
1471 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1472 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1473 // No, shouldn't be escaped
1476 // Yes, leave it escaped
1482 * make an image if it's allowed, either through the global
1483 * option, through the exception, or through the on-wiki whitelist
1486 function maybeMakeExternalImage( $url ) {
1487 $sk = $this->mOptions
->getSkin();
1488 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1489 $imagesexception = !empty($imagesfrom);
1491 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1492 if( $imagesexception && is_array( $imagesfrom ) ) {
1493 $imagematch = false;
1494 foreach( $imagesfrom as $match ) {
1495 if( strpos( $url, $match ) === 0 ) {
1500 } elseif( $imagesexception ) {
1501 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1503 $imagematch = false;
1505 if ( $this->mOptions
->getAllowExternalImages()
1506 ||
( $imagesexception && $imagematch ) ) {
1507 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1509 $text = $sk->makeExternalImage( $url );
1512 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1513 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1514 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1515 foreach( $whitelist as $entry ) {
1516 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1517 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1519 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1520 # Image matches a whitelist entry
1521 $text = $sk->makeExternalImage( $url );
1530 * Process [[ ]] wikilinks
1531 * @return processed text
1535 function replaceInternalLinks( $s ) {
1536 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1541 * Process [[ ]] wikilinks (RIL)
1542 * @return LinkHolderArray
1546 function replaceInternalLinks2( &$s ) {
1549 wfProfileIn( __METHOD__
);
1551 wfProfileIn( __METHOD__
.'-setup' );
1552 static $tc = FALSE, $e1, $e1_img;
1553 # the % is needed to support urlencoded titles as well
1555 $tc = Title
::legalChars() . '#%';
1556 # Match a link having the form [[namespace:link|alternate]]trail
1557 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1558 # Match cases where there is no "]]", which might still be images
1559 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1562 $sk = $this->mOptions
->getSkin();
1563 $holders = new LinkHolderArray( $this );
1565 #split the entire text string on occurences of [[
1566 $a = StringUtils
::explode( '[[', ' ' . $s );
1567 #get the first element (all text up to first [[), and remove the space we added
1570 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1571 $s = substr( $s, 1 );
1573 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1575 if ( $useLinkPrefixExtension ) {
1576 # Match the end of a line for a word that's not followed by whitespace,
1577 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1578 $e2 = wfMsgForContent( 'linkprefix' );
1581 if( is_null( $this->mTitle
) ) {
1582 wfProfileOut( __METHOD__
.'-setup' );
1583 wfProfileOut( __METHOD__
);
1584 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1586 $nottalk = !$this->mTitle
->isTalkPage();
1588 if ( $useLinkPrefixExtension ) {
1590 if ( preg_match( $e2, $s, $m ) ) {
1591 $first_prefix = $m[2];
1593 $first_prefix = false;
1599 if($wgContLang->hasVariants()) {
1600 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1602 $selflink = array($this->mTitle
->getPrefixedText());
1604 $useSubpages = $this->areSubpagesAllowed();
1605 wfProfileOut( __METHOD__
.'-setup' );
1607 # Loop for each link
1608 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1609 # Check for excessive memory usage
1610 if ( $holders->isBig() ) {
1612 # Do the existence check, replace the link holders and clear the array
1613 $holders->replace( $s );
1617 if ( $useLinkPrefixExtension ) {
1618 wfProfileIn( __METHOD__
.'-prefixhandling' );
1619 if ( preg_match( $e2, $s, $m ) ) {
1627 $prefix = $first_prefix;
1628 $first_prefix = false;
1630 wfProfileOut( __METHOD__
.'-prefixhandling' );
1633 $might_be_img = false;
1635 wfProfileIn( __METHOD__
."-e1" );
1636 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1638 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1639 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1640 # the real problem is with the $e1 regex
1643 # Still some problems for cases where the ] is meant to be outside punctuation,
1644 # and no image is in sight. See bug 2095.
1647 substr( $m[3], 0, 1 ) === ']' &&
1648 strpos($text, '[') !== false
1651 $text .= ']'; # so that replaceExternalLinks($text) works later
1652 $m[3] = substr( $m[3], 1 );
1654 # fix up urlencoded title texts
1655 if( strpos( $m[1], '%' ) !== false ) {
1656 # Should anchors '#' also be rejected?
1657 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1660 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1661 $might_be_img = true;
1663 if ( strpos( $m[1], '%' ) !== false ) {
1664 $m[1] = urldecode($m[1]);
1667 } else { # Invalid form; output directly
1668 $s .= $prefix . '[[' . $line ;
1669 wfProfileOut( __METHOD__
."-e1" );
1672 wfProfileOut( __METHOD__
."-e1" );
1673 wfProfileIn( __METHOD__
."-misc" );
1675 # Don't allow internal links to pages containing
1676 # PROTO: where PROTO is a valid URL protocol; these
1677 # should be external links.
1678 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1679 $s .= $prefix . '[[' . $line ;
1680 wfProfileOut( __METHOD__
."-misc" );
1684 # Make subpage if necessary
1685 if( $useSubpages ) {
1686 $link = $this->maybeDoSubpageLink( $m[1], $text );
1691 $noforce = (substr($m[1], 0, 1) !== ':');
1693 # Strip off leading ':'
1694 $link = substr($link, 1);
1697 wfProfileOut( __METHOD__
."-misc" );
1698 wfProfileIn( __METHOD__
."-title" );
1699 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1701 $s .= $prefix . '[[' . $line;
1702 wfProfileOut( __METHOD__
."-title" );
1706 $ns = $nt->getNamespace();
1707 $iw = $nt->getInterWiki();
1708 wfProfileOut( __METHOD__
."-title" );
1710 if ($might_be_img) { # if this is actually an invalid link
1711 wfProfileIn( __METHOD__
."-might_be_img" );
1712 if ($ns == NS_FILE
&& $noforce) { #but might be an image
1715 #look at the next 'line' to see if we can close it there
1717 $next_line = $a->current();
1718 if ( $next_line === false ||
$next_line === null ) {
1721 $m = explode( ']]', $next_line, 3 );
1722 if ( count( $m ) == 3 ) {
1723 # the first ]] closes the inner link, the second the image
1725 $text .= "[[{$m[0]}]]{$m[1]}";
1728 } elseif ( count( $m ) == 2 ) {
1729 #if there's exactly one ]] that's fine, we'll keep looking
1730 $text .= "[[{$m[0]}]]{$m[1]}";
1732 #if $next_line is invalid too, we need look no further
1733 $text .= '[[' . $next_line;
1738 # we couldn't find the end of this imageLink, so output it raw
1739 #but don't ignore what might be perfectly normal links in the text we've examined
1740 $holders->merge( $this->replaceInternalLinks2( $text ) );
1741 $s .= "{$prefix}[[$link|$text";
1742 # note: no $trail, because without an end, there *is* no trail
1743 wfProfileOut( __METHOD__
."-might_be_img" );
1746 } else { #it's not an image, so output it raw
1747 $s .= "{$prefix}[[$link|$text";
1748 # note: no $trail, because without an end, there *is* no trail
1749 wfProfileOut( __METHOD__
."-might_be_img" );
1752 wfProfileOut( __METHOD__
."-might_be_img" );
1755 $wasblank = ( '' == $text );
1756 if( $wasblank ) $text = $link;
1758 # Link not escaped by : , create the various objects
1762 wfProfileIn( __METHOD__
."-interwiki" );
1763 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1764 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1765 $s = rtrim($s . $prefix);
1766 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1767 wfProfileOut( __METHOD__
."-interwiki" );
1770 wfProfileOut( __METHOD__
."-interwiki" );
1772 if ( $ns == NS_FILE
) {
1773 wfProfileIn( __METHOD__
."-image" );
1774 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1775 # recursively parse links inside the image caption
1776 # actually, this will parse them in any other parameters, too,
1777 # but it might be hard to fix that, and it doesn't matter ATM
1778 $text = $this->replaceExternalLinks($text);
1779 $holders->merge( $this->replaceInternalLinks2( $text ) );
1781 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1782 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1784 $this->mOutput
->addImage( $nt->getDBkey() );
1785 wfProfileOut( __METHOD__
."-image" );
1790 if ( $ns == NS_CATEGORY
) {
1791 wfProfileIn( __METHOD__
."-category" );
1792 $s = rtrim($s . "\n"); # bug 87
1795 $sortkey = $this->getDefaultSort();
1799 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1800 $sortkey = str_replace( "\n", '', $sortkey );
1801 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1802 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1805 * Strip the whitespace Category links produce, see bug 87
1806 * @todo We might want to use trim($tmp, "\n") here.
1808 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1810 wfProfileOut( __METHOD__
."-category" );
1815 # Self-link checking
1816 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1817 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1818 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1823 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1824 # FIXME: Should do batch file existence checks, see comment below
1825 if( $ns == NS_MEDIA
) {
1826 # Give extensions a chance to select the file revision for us
1827 $skip = $time = false;
1828 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1830 $link = $sk->link( $nt );
1832 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1834 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1835 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1836 $this->mOutput
->addImage( $nt->getDBkey() );
1840 # Some titles, such as valid special pages or files in foreign repos, should
1841 # be shown as bluelinks even though they're not included in the page table
1843 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1844 # batch file existence checks for NS_FILE and NS_MEDIA
1845 if( $iw == '' && $nt->isAlwaysKnown() ) {
1846 $this->mOutput
->addLink( $nt );
1847 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1849 # Links will be added to the output link list after checking
1850 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1853 wfProfileOut( __METHOD__
);
1858 * Make a link placeholder. The text returned can be later resolved to a real link with
1859 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1860 * parsing of interwiki links, and secondly to allow all existence checks and
1861 * article length checks (for stub links) to be bundled into a single query.
1865 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1866 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1870 * Render a forced-blue link inline; protect against double expansion of
1871 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1872 * Since this little disaster has to split off the trail text to avoid
1873 * breaking URLs in the following text without breaking trails on the
1874 * wiki links, it's been made into a horrible function.
1877 * @param string $text
1878 * @param string $query
1879 * @param string $trail
1880 * @param string $prefix
1881 * @return string HTML-wikitext mix oh yuck
1883 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1884 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1885 $sk = $this->mOptions
->getSkin();
1886 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1887 return $this->armorLinks( $link ) . $trail;
1891 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1892 * going to go through further parsing steps before inline URL expansion.
1894 * Not needed quite as much as it used to be since free links are a bit
1895 * more sensible these days. But bracketed links are still an issue.
1897 * @param string more-or-less HTML
1898 * @return string less-or-more HTML with NOPARSE bits
1900 function armorLinks( $text ) {
1901 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1902 "{$this->mUniqPrefix}NOPARSE$1", $text );
1906 * Return true if subpage links should be expanded on this page.
1909 function areSubpagesAllowed() {
1910 # Some namespaces don't allow subpages
1911 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1915 * Handle link to subpage if necessary
1916 * @param string $target the source of the link
1917 * @param string &$text the link text, modified as necessary
1918 * @return string the full name of the link
1921 function maybeDoSubpageLink($target, &$text) {
1924 # :Foobar -- override special treatment of prefix (images, language links)
1925 # /Foobar -- convert to CurrentPage/Foobar
1926 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1927 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1928 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1930 wfProfileIn( __METHOD__
);
1931 $ret = $target; # default return value is no change
1933 # Some namespaces don't allow subpages,
1934 # so only perform processing if subpages are allowed
1935 if( $this->areSubpagesAllowed() ) {
1936 $hash = strpos( $target, '#' );
1937 if( $hash !== false ) {
1938 $suffix = substr( $target, $hash );
1939 $target = substr( $target, 0, $hash );
1944 $target = trim( $target );
1945 # Look at the first character
1946 if( $target != '' && $target{0} === '/' ) {
1947 # / at end means we don't want the slash to be shown
1949 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1950 if( $trailingSlashes ) {
1951 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1953 $noslash = substr( $target, 1 );
1956 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1957 if( '' === $text ) {
1958 $text = $target . $suffix;
1959 } # this might be changed for ugliness reasons
1961 # check for .. subpage backlinks
1963 $nodotdot = $target;
1964 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1966 $nodotdot = substr( $nodotdot, 3 );
1968 if($dotdotcount > 0) {
1969 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1970 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1971 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1972 # / at the end means don't show full path
1973 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1974 $nodotdot = substr( $nodotdot, 0, -1 );
1975 if( '' === $text ) {
1976 $text = $nodotdot . $suffix;
1979 $nodotdot = trim( $nodotdot );
1980 if( $nodotdot != '' ) {
1981 $ret .= '/' . $nodotdot;
1989 wfProfileOut( __METHOD__
);
1994 * Used by doBlockLevels()
1997 /* private */ function closeParagraph() {
1999 if ( '' != $this->mLastSection
) {
2000 $result = '</' . $this->mLastSection
. ">\n";
2002 $this->mInPre
= false;
2003 $this->mLastSection
= '';
2006 # getCommon() returns the length of the longest common substring
2007 # of both arguments, starting at the beginning of both.
2009 /* private */ function getCommon( $st1, $st2 ) {
2010 $fl = strlen( $st1 );
2011 $shorter = strlen( $st2 );
2012 if ( $fl < $shorter ) { $shorter = $fl; }
2014 for ( $i = 0; $i < $shorter; ++
$i ) {
2015 if ( $st1{$i} != $st2{$i} ) { break; }
2019 # These next three functions open, continue, and close the list
2020 # element appropriate to the prefix character passed into them.
2022 /* private */ function openList( $char ) {
2023 $result = $this->closeParagraph();
2025 if ( '*' === $char ) { $result .= '<ul><li>'; }
2026 else if ( '#' === $char ) { $result .= '<ol><li>'; }
2027 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
2028 else if ( ';' === $char ) {
2029 $result .= '<dl><dt>';
2030 $this->mDTopen
= true;
2032 else { $result = '<!-- ERR 1 -->'; }
2037 /* private */ function nextItem( $char ) {
2038 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2039 else if ( ':' === $char ||
';' === $char ) {
2041 if ( $this->mDTopen
) { $close = '</dt>'; }
2042 if ( ';' === $char ) {
2043 $this->mDTopen
= true;
2044 return $close . '<dt>';
2046 $this->mDTopen
= false;
2047 return $close . '<dd>';
2050 return '<!-- ERR 2 -->';
2053 /* private */ function closeList( $char ) {
2054 if ( '*' === $char ) { $text = '</li></ul>'; }
2055 else if ( '#' === $char ) { $text = '</li></ol>'; }
2056 else if ( ':' === $char ) {
2057 if ( $this->mDTopen
) {
2058 $this->mDTopen
= false;
2059 $text = '</dt></dl>';
2061 $text = '</dd></dl>';
2064 else { return '<!-- ERR 3 -->'; }
2070 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2073 * @return string the lists rendered as HTML
2075 function doBlockLevels( $text, $linestart ) {
2076 wfProfileIn( __METHOD__
);
2078 # Parsing through the text line by line. The main thing
2079 # happening here is handling of block-level elements p, pre,
2080 # and making lists from lines starting with * # : etc.
2082 $textLines = StringUtils
::explode( "\n", $text );
2084 $lastPrefix = $output = '';
2085 $this->mDTopen
= $inBlockElem = false;
2087 $paragraphStack = false;
2089 foreach ( $textLines as $oLine ) {
2091 if ( !$linestart ) {
2097 $lastPrefixLength = strlen( $lastPrefix );
2098 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2099 $preOpenMatch = preg_match('/<pre/i', $oLine );
2100 if ( !$this->mInPre
) {
2101 # Multiple prefixes may abut each other for nested lists.
2102 $prefixLength = strspn( $oLine, '*#:;' );
2103 $prefix = substr( $oLine, 0, $prefixLength );
2106 $prefix2 = str_replace( ';', ':', $prefix );
2107 $t = substr( $oLine, $prefixLength );
2108 $this->mInPre
= (bool)$preOpenMatch;
2110 # Don't interpret any other prefixes in preformatted text
2112 $prefix = $prefix2 = '';
2117 if( $prefixLength && $lastPrefix === $prefix2 ) {
2118 # Same as the last item, so no need to deal with nesting or opening stuff
2119 $output .= $this->nextItem( substr( $prefix, -1 ) );
2120 $paragraphStack = false;
2122 if ( substr( $prefix, -1 ) === ';') {
2123 # The one nasty exception: definition lists work like this:
2124 # ; title : definition text
2125 # So we check for : in the remainder text to split up the
2126 # title and definition, without b0rking links.
2128 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2130 $output .= $term . $this->nextItem( ':' );
2133 } elseif( $prefixLength ||
$lastPrefixLength ) {
2134 # Either open or close a level...
2135 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2136 $paragraphStack = false;
2138 while( $commonPrefixLength < $lastPrefixLength ) {
2139 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2140 --$lastPrefixLength;
2142 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2143 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2145 while ( $prefixLength > $commonPrefixLength ) {
2146 $char = substr( $prefix, $commonPrefixLength, 1 );
2147 $output .= $this->openList( $char );
2149 if ( ';' === $char ) {
2150 # FIXME: This is dupe of code above
2151 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2153 $output .= $term . $this->nextItem( ':' );
2156 ++
$commonPrefixLength;
2158 $lastPrefix = $prefix2;
2160 if( 0 == $prefixLength ) {
2161 wfProfileIn( __METHOD__
."-paragraph" );
2162 # No prefix (not in list)--go to paragraph mode
2163 // XXX: use a stack for nestable elements like span, table and div
2164 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2165 $closematch = preg_match(
2166 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2167 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2168 if ( $openmatch or $closematch ) {
2169 $paragraphStack = false;
2170 #Â TODO bug 5718: paragraph closed
2171 $output .= $this->closeParagraph();
2172 if ( $preOpenMatch and !$preCloseMatch ) {
2173 $this->mInPre
= true;
2175 if ( $closematch ) {
2176 $inBlockElem = false;
2178 $inBlockElem = true;
2180 } else if ( !$inBlockElem && !$this->mInPre
) {
2181 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2183 if ($this->mLastSection
!== 'pre') {
2184 $paragraphStack = false;
2185 $output .= $this->closeParagraph().'<pre>';
2186 $this->mLastSection
= 'pre';
2188 $t = substr( $t, 1 );
2191 if ( '' == trim($t) ) {
2192 if ( $paragraphStack ) {
2193 $output .= $paragraphStack.'<br />';
2194 $paragraphStack = false;
2195 $this->mLastSection
= 'p';
2197 if ($this->mLastSection
!== 'p' ) {
2198 $output .= $this->closeParagraph();
2199 $this->mLastSection
= '';
2200 $paragraphStack = '<p>';
2202 $paragraphStack = '</p><p>';
2206 if ( $paragraphStack ) {
2207 $output .= $paragraphStack;
2208 $paragraphStack = false;
2209 $this->mLastSection
= 'p';
2210 } else if ($this->mLastSection
!== 'p') {
2211 $output .= $this->closeParagraph().'<p>';
2212 $this->mLastSection
= 'p';
2217 wfProfileOut( __METHOD__
."-paragraph" );
2219 // somewhere above we forget to get out of pre block (bug 785)
2220 if($preCloseMatch && $this->mInPre
) {
2221 $this->mInPre
= false;
2223 if ($paragraphStack === false) {
2227 while ( $prefixLength ) {
2228 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2231 if ( '' != $this->mLastSection
) {
2232 $output .= '</' . $this->mLastSection
. '>';
2233 $this->mLastSection
= '';
2236 wfProfileOut( __METHOD__
);
2241 * Split up a string on ':', ignoring any occurences inside tags
2242 * to prevent illegal overlapping.
2243 * @param string $str the string to split
2244 * @param string &$before set to everything before the ':'
2245 * @param string &$after set to everything after the ':'
2246 * return string the position of the ':', or false if none found
2248 function findColonNoLinks($str, &$before, &$after) {
2249 wfProfileIn( __METHOD__
);
2251 $pos = strpos( $str, ':' );
2252 if( $pos === false ) {
2254 wfProfileOut( __METHOD__
);
2258 $lt = strpos( $str, '<' );
2259 if( $lt === false ||
$lt > $pos ) {
2260 // Easy; no tag nesting to worry about
2261 $before = substr( $str, 0, $pos );
2262 $after = substr( $str, $pos+
1 );
2263 wfProfileOut( __METHOD__
);
2267 // Ugly state machine to walk through avoiding tags.
2268 $state = self
::COLON_STATE_TEXT
;
2270 $len = strlen( $str );
2271 for( $i = 0; $i < $len; $i++
) {
2275 // (Using the number is a performance hack for common cases)
2276 case 0: // self::COLON_STATE_TEXT:
2279 // Could be either a <start> tag or an </end> tag
2280 $state = self
::COLON_STATE_TAGSTART
;
2285 $before = substr( $str, 0, $i );
2286 $after = substr( $str, $i +
1 );
2287 wfProfileOut( __METHOD__
);
2290 // Embedded in a tag; don't break it.
2293 // Skip ahead looking for something interesting
2294 $colon = strpos( $str, ':', $i );
2295 if( $colon === false ) {
2296 // Nothing else interesting
2297 wfProfileOut( __METHOD__
);
2300 $lt = strpos( $str, '<', $i );
2301 if( $stack === 0 ) {
2302 if( $lt === false ||
$colon < $lt ) {
2304 $before = substr( $str, 0, $colon );
2305 $after = substr( $str, $colon +
1 );
2306 wfProfileOut( __METHOD__
);
2310 if( $lt === false ) {
2311 // Nothing else interesting to find; abort!
2312 // We're nested, but there's no close tags left. Abort!
2315 // Skip ahead to next tag start
2317 $state = self
::COLON_STATE_TAGSTART
;
2320 case 1: // self::COLON_STATE_TAG:
2325 $state = self
::COLON_STATE_TEXT
;
2328 // Slash may be followed by >?
2329 $state = self
::COLON_STATE_TAGSLASH
;
2335 case 2: // self::COLON_STATE_TAGSTART:
2338 $state = self
::COLON_STATE_CLOSETAG
;
2341 $state = self
::COLON_STATE_COMMENT
;
2344 // Illegal early close? This shouldn't happen D:
2345 $state = self
::COLON_STATE_TEXT
;
2348 $state = self
::COLON_STATE_TAG
;
2351 case 3: // self::COLON_STATE_CLOSETAG:
2356 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2357 wfProfileOut( __METHOD__
);
2360 $state = self
::COLON_STATE_TEXT
;
2363 case self
::COLON_STATE_TAGSLASH
:
2365 // Yes, a self-closed tag <blah/>
2366 $state = self
::COLON_STATE_TEXT
;
2368 // Probably we're jumping the gun, and this is an attribute
2369 $state = self
::COLON_STATE_TAG
;
2372 case 5: // self::COLON_STATE_COMMENT:
2374 $state = self
::COLON_STATE_COMMENTDASH
;
2377 case self
::COLON_STATE_COMMENTDASH
:
2379 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2381 $state = self
::COLON_STATE_COMMENT
;
2384 case self
::COLON_STATE_COMMENTDASHDASH
:
2386 $state = self
::COLON_STATE_TEXT
;
2388 $state = self
::COLON_STATE_COMMENT
;
2392 throw new MWException( "State machine error in " . __METHOD__
);
2396 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2399 wfProfileOut( __METHOD__
);
2404 * Return value of a magic variable (like PAGENAME)
2408 function getVariableValue( $index ) {
2409 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2412 * Some of these require message or data lookups and can be
2413 * expensive to check many times.
2415 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2416 if ( isset( $this->mVarCache
[$index] ) ) {
2417 return $this->mVarCache
[$index];
2421 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2422 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2425 global $wgLocaltimezone;
2426 if ( isset( $wgLocaltimezone ) ) {
2427 $oldtz = getenv( 'TZ' );
2428 putenv( 'TZ='.$wgLocaltimezone );
2431 wfSuppressWarnings(); // E_STRICT system time bitching
2432 $localTimestamp = date( 'YmdHis', $ts );
2433 $localMonth = date( 'm', $ts );
2434 $localMonthName = date( 'n', $ts );
2435 $localDay = date( 'j', $ts );
2436 $localDay2 = date( 'd', $ts );
2437 $localDayOfWeek = date( 'w', $ts );
2438 $localWeek = date( 'W', $ts );
2439 $localYear = date( 'Y', $ts );
2440 $localHour = date( 'H', $ts );
2441 if ( isset( $wgLocaltimezone ) ) {
2442 putenv( 'TZ='.$oldtz );
2444 wfRestoreWarnings();
2447 case 'currentmonth':
2448 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2449 case 'currentmonthname':
2450 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2451 case 'currentmonthnamegen':
2452 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2453 case 'currentmonthabbrev':
2454 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2456 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2458 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2460 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2461 case 'localmonthname':
2462 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2463 case 'localmonthnamegen':
2464 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2465 case 'localmonthabbrev':
2466 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2468 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2470 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2472 return wfEscapeWikiText( $this->mTitle
->getText() );
2474 return $this->mTitle
->getPartialURL();
2475 case 'fullpagename':
2476 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2477 case 'fullpagenamee':
2478 return $this->mTitle
->getPrefixedURL();
2480 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2481 case 'subpagenamee':
2482 return $this->mTitle
->getSubpageUrlForm();
2483 case 'basepagename':
2484 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2485 case 'basepagenamee':
2486 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2487 case 'talkpagename':
2488 if( $this->mTitle
->canTalk() ) {
2489 $talkPage = $this->mTitle
->getTalkPage();
2490 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2494 case 'talkpagenamee':
2495 if( $this->mTitle
->canTalk() ) {
2496 $talkPage = $this->mTitle
->getTalkPage();
2497 return $talkPage->getPrefixedUrl();
2501 case 'subjectpagename':
2502 $subjPage = $this->mTitle
->getSubjectPage();
2503 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2504 case 'subjectpagenamee':
2505 $subjPage = $this->mTitle
->getSubjectPage();
2506 return $subjPage->getPrefixedUrl();
2508 // Let the edit saving system know we should parse the page
2509 // *after* a revision ID has been assigned.
2510 $this->mOutput
->setFlag( 'vary-revision' );
2511 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2512 return $this->mRevisionId
;
2514 // Let the edit saving system know we should parse the page
2515 // *after* a revision ID has been assigned. This is for null edits.
2516 $this->mOutput
->setFlag( 'vary-revision' );
2517 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2518 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2519 case 'revisionday2':
2520 // Let the edit saving system know we should parse the page
2521 // *after* a revision ID has been assigned. This is for null edits.
2522 $this->mOutput
->setFlag( 'vary-revision' );
2523 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2524 return substr( $this->getRevisionTimestamp(), 6, 2 );
2525 case 'revisionmonth':
2526 // Let the edit saving system know we should parse the page
2527 // *after* a revision ID has been assigned. This is for null edits.
2528 $this->mOutput
->setFlag( 'vary-revision' );
2529 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2530 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2531 case 'revisionyear':
2532 // Let the edit saving system know we should parse the page
2533 // *after* a revision ID has been assigned. This is for null edits.
2534 $this->mOutput
->setFlag( 'vary-revision' );
2535 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2536 return substr( $this->getRevisionTimestamp(), 0, 4 );
2537 case 'revisiontimestamp':
2538 // Let the edit saving system know we should parse the page
2539 // *after* a revision ID has been assigned. This is for null edits.
2540 $this->mOutput
->setFlag( 'vary-revision' );
2541 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2542 return $this->getRevisionTimestamp();
2544 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2546 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2548 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2550 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2551 case 'subjectspace':
2552 return $this->mTitle
->getSubjectNsText();
2553 case 'subjectspacee':
2554 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2555 case 'currentdayname':
2556 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2560 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2562 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2564 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2565 // int to remove the padding
2566 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2568 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2569 case 'localdayname':
2570 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2572 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2574 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2576 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2578 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2579 // int to remove the padding
2580 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2582 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2583 case 'numberofarticles':
2584 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2585 case 'numberoffiles':
2586 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2587 case 'numberofusers':
2588 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2589 case 'numberofpages':
2590 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2591 case 'numberofadmins':
2592 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2593 case 'numberofedits':
2594 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2595 case 'numberofviews':
2596 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2597 case 'currenttimestamp':
2598 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2599 case 'localtimestamp':
2600 return $this->mVarCache
[$index] = $localTimestamp;
2601 case 'currentversion':
2602 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2608 return $wgServerName;
2610 return $wgScriptPath;
2611 case 'directionmark':
2612 return $wgContLang->getDirMark();
2613 case 'contentlanguage':
2614 global $wgContLanguageCode;
2615 return $wgContLanguageCode;
2618 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2626 * initialise the magic variables (like CURRENTMONTHNAME)
2630 function initialiseVariables() {
2631 wfProfileIn( __METHOD__
);
2632 $variableIDs = MagicWord
::getVariableIDs();
2634 $this->mVariables
= new MagicWordArray( $variableIDs );
2635 wfProfileOut( __METHOD__
);
2639 * Preprocess some wikitext and return the document tree.
2640 * This is the ghost of replace_variables().
2642 * @param string $text The text to parse
2643 * @param integer flags Bitwise combination of:
2644 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2645 * included. Default is to assume a direct page view.
2647 * The generated DOM tree must depend only on the input text and the flags.
2648 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2650 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2651 * change in the DOM tree for a given text, must be passed through the section identifier
2652 * in the section edit link and thus back to extractSections().
2654 * The output of this function is currently only cached in process memory, but a persistent
2655 * cache may be implemented at a later date which takes further advantage of these strict
2656 * dependency requirements.
2660 function preprocessToDom ( $text, $flags = 0 ) {
2661 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2666 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2668 public static function splitWhitespace( $s ) {
2669 $ltrimmed = ltrim( $s );
2670 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2671 $trimmed = rtrim( $ltrimmed );
2672 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2674 $w2 = substr( $ltrimmed, -$diff );
2678 return array( $w1, $trimmed, $w2 );
2682 * Replace magic variables, templates, and template arguments
2683 * with the appropriate text. Templates are substituted recursively,
2684 * taking care to avoid infinite loops.
2686 * Note that the substitution depends on value of $mOutputType:
2687 * self::OT_WIKI: only {{subst:}} templates
2688 * self::OT_PREPROCESS: templates but not extension tags
2689 * self::OT_HTML: all templates and extension tags
2691 * @param string $tex The text to transform
2692 * @param PPFrame $frame Object describing the arguments passed to the template.
2693 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2694 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2695 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2698 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2699 # Prevent too big inclusions
2700 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2704 wfProfileIn( __METHOD__
);
2706 if ( $frame === false ) {
2707 $frame = $this->getPreprocessor()->newFrame();
2708 } elseif ( !( $frame instanceof PPFrame
) ) {
2709 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2710 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2713 $dom = $this->preprocessToDom( $text );
2714 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2715 $text = $frame->expand( $dom, $flags );
2717 wfProfileOut( __METHOD__
);
2721 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2722 static function createAssocArgs( $args ) {
2723 $assocArgs = array();
2725 foreach( $args as $arg ) {
2726 $eqpos = strpos( $arg, '=' );
2727 if ( $eqpos === false ) {
2728 $assocArgs[$index++
] = $arg;
2730 $name = trim( substr( $arg, 0, $eqpos ) );
2731 $value = trim( substr( $arg, $eqpos+
1 ) );
2732 if ( $value === false ) {
2735 if ( $name !== false ) {
2736 $assocArgs[$name] = $value;
2745 * Warn the user when a parser limitation is reached
2746 * Will warn at most once the user per limitation type
2748 * @param string $limitationType, should be one of:
2749 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2750 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2751 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2752 * @params int $current, $max When an explicit limit has been
2753 * exceeded, provide the values (optional)
2755 function limitationWarn( $limitationType, $current=null, $max=null) {
2756 $msgName = $limitationType . '-warning';
2757 //does no harm if $current and $max are present but are unnecessary for the message
2758 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2759 $this->mOutput
->addWarning( $warning );
2760 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2762 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2767 * Return the text of a template, after recursively
2768 * replacing any variables or templates within the template.
2770 * @param array $piece The parts of the template
2771 * $piece['title']: the title, i.e. the part before the |
2772 * $piece['parts']: the parameter array
2773 * $piece['lineStart']: whether the brace was at the start of a line
2774 * @param PPFrame The current frame, contains template arguments
2775 * @return string the text of the template
2778 function braceSubstitution( $piece, $frame ) {
2779 global $wgContLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2780 wfProfileIn( __METHOD__
);
2781 wfProfileIn( __METHOD__
.'-setup' );
2784 $found = false; # $text has been filled
2785 $nowiki = false; # wiki markup in $text should be escaped
2786 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2787 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2788 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2789 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2791 # Title object, where $text came from
2794 # $part1 is the bit before the first |, and must contain only title characters.
2795 # Various prefixes will be stripped from it later.
2796 $titleWithSpaces = $frame->expand( $piece['title'] );
2797 $part1 = trim( $titleWithSpaces );
2800 # Original title text preserved for various purposes
2801 $originalTitle = $part1;
2803 # $args is a list of argument nodes, starting from index 0, not including $part1
2804 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2805 wfProfileOut( __METHOD__
.'-setup' );
2808 wfProfileIn( __METHOD__
.'-modifiers' );
2810 $mwSubst = MagicWord
::get( 'subst' );
2811 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2812 # One of two possibilities is true:
2813 # 1) Found SUBST but not in the PST phase
2814 # 2) Didn't find SUBST and in the PST phase
2815 # In either case, return without further processing
2816 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2823 if ( !$found && $args->getLength() == 0 ) {
2824 $id = $this->mVariables
->matchStartToEnd( $part1 );
2825 if ( $id !== false ) {
2826 $text = $this->getVariableValue( $id );
2827 if (MagicWord
::getCacheTTL($id)>-1)
2828 $this->mOutput
->mContainsOldMagic
= true;
2833 # MSG, MSGNW and RAW
2836 $mwMsgnw = MagicWord
::get( 'msgnw' );
2837 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2840 # Remove obsolete MSG:
2841 $mwMsg = MagicWord
::get( 'msg' );
2842 $mwMsg->matchStartAndRemove( $part1 );
2846 $mwRaw = MagicWord
::get( 'raw' );
2847 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2848 $forceRawInterwiki = true;
2851 wfProfileOut( __METHOD__
.'-modifiers' );
2855 wfProfileIn( __METHOD__
. '-pfunc' );
2857 $colonPos = strpos( $part1, ':' );
2858 if ( $colonPos !== false ) {
2859 # Case sensitive functions
2860 $function = substr( $part1, 0, $colonPos );
2861 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2862 $function = $this->mFunctionSynonyms
[1][$function];
2864 # Case insensitive functions
2865 $function = strtolower( $function );
2866 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2867 $function = $this->mFunctionSynonyms
[0][$function];
2873 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2874 $initialArgs = array( &$this );
2875 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2876 if ( $flags & SFH_OBJECT_ARGS
) {
2877 # Add a frame parameter, and pass the arguments as an array
2878 $allArgs = $initialArgs;
2879 $allArgs[] = $frame;
2880 for ( $i = 0; $i < $args->getLength(); $i++
) {
2881 $funcArgs[] = $args->item( $i );
2883 $allArgs[] = $funcArgs;
2885 # Convert arguments to plain text
2886 for ( $i = 0; $i < $args->getLength(); $i++
) {
2887 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2889 $allArgs = array_merge( $initialArgs, $funcArgs );
2892 # Workaround for PHP bug 35229 and similar
2893 if ( !is_callable( $callback ) ) {
2894 throw new MWException( "Tag hook for $function is not callable\n" );
2896 $result = call_user_func_array( $callback, $allArgs );
2899 $preprocessFlags = 0;
2901 if ( is_array( $result ) ) {
2902 if ( isset( $result[0] ) ) {
2904 unset( $result[0] );
2907 // Extract flags into the local scope
2908 // This allows callers to set flags such as nowiki, found, etc.
2914 $text = $this->preprocessToDom( $text, $preprocessFlags );
2919 wfProfileOut( __METHOD__
. '-pfunc' );
2922 # Finish mangling title and then check for loops.
2923 # Set $title to a Title object and $titleText to the PDBK
2926 # Split the title into page and subpage
2928 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2929 if ($subpage !== '') {
2930 $ns = $this->mTitle
->getNamespace();
2932 $title = Title
::newFromText( $part1, $ns );
2934 $titleText = $title->getPrefixedText();
2935 # Check for language variants if the template is not found
2936 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2937 $wgContLang->findVariantLink( $part1, $title, true );
2939 # Do infinite loop check
2940 if ( !$frame->loopCheck( $title ) ) {
2942 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2943 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2945 # Do recursion depth check
2946 $limit = $this->mOptions
->getMaxTemplateDepth();
2947 if ( $frame->depth
>= $limit ) {
2949 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2954 # Load from database
2955 if ( !$found && $title ) {
2956 wfProfileIn( __METHOD__
. '-loadtpl' );
2957 if ( !$title->isExternal() ) {
2958 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2959 $text = SpecialPage
::capturePath( $title );
2960 if ( is_string( $text ) ) {
2963 $this->disableCache();
2965 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2966 $found = false; //access denied
2967 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2969 list( $text, $title ) = $this->getTemplateDom( $title );
2970 if ( $text !== false ) {
2976 # If the title is valid but undisplayable, make a link to it
2977 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2978 $text = "[[:$titleText]]";
2981 } elseif ( $title->isTrans() ) {
2982 // Interwiki transclusion
2983 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2984 $text = $this->interwikiTransclude( $title, 'render' );
2987 $text = $this->interwikiTransclude( $title, 'raw' );
2988 // Preprocess it like a template
2989 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2994 wfProfileOut( __METHOD__
. '-loadtpl' );
2997 # If we haven't found text to substitute by now, we're done
2998 # Recover the source wikitext and return it
3000 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3001 wfProfileOut( __METHOD__
);
3002 return array( 'object' => $text );
3005 # Expand DOM-style return values in a child frame
3006 if ( $isChildObj ) {
3007 # Clean up argument array
3008 $newFrame = $frame->newChild( $args, $title );
3011 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3012 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3013 # Expansion is eligible for the empty-frame cache
3014 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3015 $text = $this->mTplExpandCache
[$titleText];
3017 $text = $newFrame->expand( $text );
3018 $this->mTplExpandCache
[$titleText] = $text;
3021 # Uncached expansion
3022 $text = $newFrame->expand( $text );
3025 if ( $isLocalObj && $nowiki ) {
3026 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3027 $isLocalObj = false;
3030 # Replace raw HTML by a placeholder
3031 # Add a blank line preceding, to prevent it from mucking up
3032 # immediately preceding headings
3034 $text = "\n\n" . $this->insertStripItem( $text );
3036 # Escape nowiki-style return values
3037 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3038 $text = wfEscapeWikiText( $text );
3040 # Bug 529: if the template begins with a table or block-level
3041 # element, it should be treated as beginning a new line.
3042 # This behaviour is somewhat controversial.
3043 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3044 $text = "\n" . $text;
3047 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3048 # Error, oversize inclusion
3049 $text = "[[$originalTitle]]" .
3050 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3051 $this->limitationWarn( 'post-expand-template-inclusion' );
3054 if ( $isLocalObj ) {
3055 $ret = array( 'object' => $text );
3057 $ret = array( 'text' => $text );
3060 wfProfileOut( __METHOD__
);
3065 * Get the semi-parsed DOM representation of a template with a given title,
3066 * and its redirect destination title. Cached.
3068 function getTemplateDom( $title ) {
3069 $cacheTitle = $title;
3070 $titleText = $title->getPrefixedDBkey();
3072 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3073 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3074 $title = Title
::makeTitle( $ns, $dbk );
3075 $titleText = $title->getPrefixedDBkey();
3077 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3078 return array( $this->mTplDomCache
[$titleText], $title );
3081 // Cache miss, go to the database
3082 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3084 if ( $text === false ) {
3085 $this->mTplDomCache
[$titleText] = false;
3086 return array( false, $title );
3089 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3090 $this->mTplDomCache
[ $titleText ] = $dom;
3092 if (! $title->equals($cacheTitle)) {
3093 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3094 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3097 return array( $dom, $title );
3101 * Fetch the unparsed text of a template and register a reference to it.
3103 function fetchTemplateAndTitle( $title ) {
3104 $templateCb = $this->mOptions
->getTemplateCallback();
3105 $stuff = call_user_func( $templateCb, $title, $this );
3106 $text = $stuff['text'];
3107 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3108 if ( isset( $stuff['deps'] ) ) {
3109 foreach ( $stuff['deps'] as $dep ) {
3110 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3113 return array($text,$finalTitle);
3116 function fetchTemplate( $title ) {
3117 $rv = $this->fetchTemplateAndTitle($title);
3122 * Static function to get a template
3123 * Can be overridden via ParserOptions::setTemplateCallback().
3125 static function statelessFetchTemplate( $title, $parser=false ) {
3126 $text = $skip = false;
3127 $finalTitle = $title;
3130 // Loop to fetch the article, with up to 1 redirect
3131 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3132 # Give extensions a chance to select the revision instead
3133 $id = false; // Assume current
3134 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3140 'page_id' => $title->getArticleID(),
3144 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3145 $rev_id = $rev ?
$rev->getId() : 0;
3146 // If there is no current revision, there is no page
3147 if( $id === false && !$rev ) {
3148 $linkCache = LinkCache
::singleton();
3149 $linkCache->addBadLinkObj( $title );
3154 'page_id' => $title->getArticleID(),
3155 'rev_id' => $rev_id );
3158 $text = $rev->getText();
3159 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3161 $message = $wgContLang->lcfirst( $title->getText() );
3162 $text = wfMsgForContentNoTrans( $message );
3163 if( wfEmptyMsg( $message, $text ) ) {
3170 if ( $text === false ) {
3174 $finalTitle = $title;
3175 $title = Title
::newFromRedirect( $text );
3179 'finalTitle' => $finalTitle,
3184 * Transclude an interwiki link.
3186 function interwikiTransclude( $title, $action ) {
3187 global $wgEnableScaryTranscluding;
3189 if (!$wgEnableScaryTranscluding)
3190 return wfMsg('scarytranscludedisabled');
3192 $url = $title->getFullUrl( "action=$action" );
3194 if (strlen($url) > 255)
3195 return wfMsg('scarytranscludetoolong');
3196 return $this->fetchScaryTemplateMaybeFromCache($url);
3199 function fetchScaryTemplateMaybeFromCache($url) {
3200 global $wgTranscludeCacheExpiry;
3201 $dbr = wfGetDB(DB_SLAVE
);
3202 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3203 array('tc_url' => $url));
3205 $time = $obj->tc_time
;
3206 $text = $obj->tc_contents
;
3207 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3212 $text = Http
::get($url);
3214 return wfMsg('scarytranscludefailed', $url);
3216 $dbw = wfGetDB(DB_MASTER
);
3217 $dbw->replace('transcache', array('tc_url'), array(
3219 'tc_time' => time(),
3220 'tc_contents' => $text));
3226 * Triple brace replacement -- used for template arguments
3229 function argSubstitution( $piece, $frame ) {
3230 wfProfileIn( __METHOD__
);
3233 $parts = $piece['parts'];
3234 $nameWithSpaces = $frame->expand( $piece['title'] );
3235 $argName = trim( $nameWithSpaces );
3237 $text = $frame->getArgument( $argName );
3238 if ( $text === false && $parts->getLength() > 0
3242 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3245 # No match in frame, use the supplied default
3246 $object = $parts->item( 0 )->getChildren();
3248 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3249 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3250 $this->limitationWarn( 'post-expand-template-argument' );
3253 if ( $text === false && $object === false ) {
3255 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3257 if ( $error !== false ) {
3260 if ( $object !== false ) {
3261 $ret = array( 'object' => $object );
3263 $ret = array( 'text' => $text );
3266 wfProfileOut( __METHOD__
);
3271 * Return the text to be used for a given extension tag.
3272 * This is the ghost of strip().
3274 * @param array $params Associative array of parameters:
3275 * name PPNode for the tag name
3276 * attr PPNode for unparsed text where tag attributes are thought to be
3277 * attributes Optional associative array of parsed attributes
3278 * inner Contents of extension element
3279 * noClose Original text did not have a close tag
3280 * @param PPFrame $frame
3282 function extensionSubstitution( $params, $frame ) {
3283 global $wgRawHtml, $wgContLang;
3285 $name = $frame->expand( $params['name'] );
3286 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3287 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3289 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3291 if ( $this->ot
['html'] ) {
3292 $name = strtolower( $name );
3294 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3295 if ( isset( $params['attributes'] ) ) {
3296 $attributes = $attributes +
$params['attributes'];
3304 throw new MWException( '<html> extension tag encountered unexpectedly' );
3307 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3308 $output = Xml
::escapeTagsOnly( $content );
3311 $output = $wgContLang->armourMath(
3312 MathRenderer
::renderMath( $content, $attributes ) );
3315 $output = $this->renderImageGallery( $content, $attributes );
3318 if( isset( $this->mTagHooks
[$name] ) ) {
3319 # Workaround for PHP bug 35229 and similar
3320 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3321 throw new MWException( "Tag hook for $name is not callable\n" );
3323 $output = call_user_func_array( $this->mTagHooks
[$name],
3324 array( $content, $attributes, $this ) );
3326 $output = '<span class="error">Invalid tag extension name: ' .
3327 htmlspecialchars( $name ) . '</span>';
3331 if ( is_null( $attrText ) ) {
3334 if ( isset( $params['attributes'] ) ) {
3335 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3336 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3337 htmlspecialchars( $attrValue ) . '"';
3340 if ( $content === null ) {
3341 $output = "<$name$attrText/>";
3343 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3344 $output = "<$name$attrText>$content$close";
3348 if ( $name === 'html' ||
$name === 'nowiki' ) {
3349 $this->mStripState
->nowiki
->setPair( $marker, $output );
3351 $this->mStripState
->general
->setPair( $marker, $output );
3357 * Increment an include size counter
3359 * @param string $type The type of expansion
3360 * @param integer $size The size of the text
3361 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3363 function incrementIncludeSize( $type, $size ) {
3364 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3367 $this->mIncludeSizes
[$type] +
= $size;
3373 * Increment the expensive function count
3375 * @return boolean False if the limit has been exceeded
3377 function incrementExpensiveFunctionCount() {
3378 global $wgExpensiveParserFunctionLimit;
3379 $this->mExpensiveFunctionCount++
;
3380 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3387 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3388 * Fills $this->mDoubleUnderscores, returns the modified text
3390 function doDoubleUnderscore( $text ) {
3391 // The position of __TOC__ needs to be recorded
3392 $mw = MagicWord
::get( 'toc' );
3393 if( $mw->match( $text ) ) {
3394 $this->mShowToc
= true;
3395 $this->mForceTocPosition
= true;
3397 // Set a placeholder. At the end we'll fill it in with the TOC.
3398 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3400 // Only keep the first one.
3401 $text = $mw->replace( '', $text );
3404 // Now match and remove the rest of them
3405 $mwa = MagicWord
::getDoubleUnderscoreArray();
3406 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3408 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3409 $this->mOutput
->mNoGallery
= true;
3411 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3412 $this->mShowToc
= false;
3414 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3415 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3417 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3418 if ( $containerCategory ) {
3419 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3421 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3424 # (bug 8068) Allow control over whether robots index a page.
3426 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3427 # is not desirable, the last one on the page should win.
3428 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3429 $this->mOutput
->setIndexPolicy( 'noindex' );
3430 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3431 $this->mOutput
->setIndexPolicy( 'index' );
3438 * This function accomplishes several tasks:
3439 * 1) Auto-number headings if that option is enabled
3440 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3441 * 3) Add a Table of contents on the top for users who have enabled the option
3442 * 4) Auto-anchor headings
3444 * It loops through all headlines, collects the necessary data, then splits up the
3445 * string and re-inserts the newly formatted headlines.
3447 * @param string $text
3448 * @param boolean $isMain
3451 function formatHeadings( $text, $isMain=true ) {
3452 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3454 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3455 $showEditLink = $this->mOptions
->getEditSection();
3457 // Do not call quickUserCan unless necessary
3458 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3462 # Inhibit editsection links if requested in the page
3463 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3467 # Get all headlines for numbering them and adding funky stuff like [edit]
3468 # links - this is for later, but we need the number of headlines right now
3470 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3472 # if there are fewer than 4 headlines in the article, do not show TOC
3473 # unless it's been explicitly enabled.
3474 $enoughToc = $this->mShowToc
&&
3475 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3477 # Allow user to stipulate that a page should have a "new section"
3478 # link added via __NEWSECTIONLINK__
3479 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3480 $this->mOutput
->setNewSection( true );
3483 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3484 # override above conditions and always show TOC above first header
3485 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3486 $this->mShowToc
= true;
3490 # We need this to perform operations on the HTML
3491 $sk = $this->mOptions
->getSkin();
3497 # Ugh .. the TOC should have neat indentation levels which can be
3498 # passed to the skin functions. These are determined here
3502 $sublevelCount = array();
3503 $levelCount = array();
3509 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3510 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3513 foreach( $matches[3] as $headline ) {
3514 $isTemplate = false;
3516 $sectionIndex = false;
3518 $markerMatches = array();
3519 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3520 $serial = $markerMatches[1];
3521 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3522 $isTemplate = ($titleText != $baseTitleText);
3523 $headline = preg_replace("/^$markerRegex/", "", $headline);
3527 $prevlevel = $level;
3528 $prevtoclevel = $toclevel;
3530 $level = $matches[1][$headlineCount];
3532 if( $doNumberHeadings ||
$enoughToc ) {
3534 if ( $level > $prevlevel ) {
3535 # Increase TOC level
3537 $sublevelCount[$toclevel] = 0;
3538 if( $toclevel<$wgMaxTocLevel ) {
3539 $prevtoclevel = $toclevel;
3540 $toc .= $sk->tocIndent();
3544 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3545 # Decrease TOC level, find level to jump to
3547 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3548 # Can only go down to level 1
3551 for ($i = $toclevel; $i > 0; $i--) {
3552 if ( $levelCount[$i] == $level ) {
3553 # Found last matching level
3557 elseif ( $levelCount[$i] < $level ) {
3558 # Found first matching level below current level
3564 if( $toclevel<$wgMaxTocLevel ) {
3565 if($prevtoclevel < $wgMaxTocLevel) {
3566 # Unindent only if the previous toc level was shown :p
3567 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3568 $prevtoclevel = $toclevel;
3570 $toc .= $sk->tocLineEnd();
3575 # No change in level, end TOC line
3576 if( $toclevel<$wgMaxTocLevel ) {
3577 $toc .= $sk->tocLineEnd();
3581 $levelCount[$toclevel] = $level;
3583 # count number of headlines for each level
3584 @$sublevelCount[$toclevel]++
;
3586 for( $i = 1; $i <= $toclevel; $i++
) {
3587 if( !empty( $sublevelCount[$i] ) ) {
3591 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3597 # The safe header is a version of the header text safe to use for links
3598 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3599 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3601 # Remove link placeholders by the link text.
3602 # <!--LINK number-->
3604 # link text with suffix
3605 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3607 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3608 $tocline = preg_replace(
3609 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3613 $tocline = trim( $tocline );
3615 # For the anchor, strip out HTML-y stuff period
3616 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3617 $safeHeadline = trim( $safeHeadline );
3619 # Save headline for section edit hint before it's escaped
3620 $headlineHint = $safeHeadline;
3622 if ( $wgEnforceHtmlIds ) {
3623 $legacyHeadline = false;
3624 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3627 # For reverse compatibility, provide an id that's
3628 # HTML4-compatible, like we used to.
3630 # It may be worth noting, academically, that it's possible for
3631 # the legacy anchor to conflict with a non-legacy headline
3632 # anchor on the page. In this case likely the "correct" thing
3633 # would be to either drop the legacy anchors or make sure
3634 # they're numbered first. However, this would require people
3635 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3636 # manually, so let's not bother worrying about it.
3637 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3639 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3641 if ( $legacyHeadline == $safeHeadline ) {
3642 # No reason to have both (in fact, we can't)
3643 $legacyHeadline = false;
3644 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3645 $legacyHeadline, 'xml' ) ) {
3646 # The legacy id is invalid XML. We used to allow this, but
3647 # there's no reason to do so anymore. Backward
3648 # compatibility will fail slightly in this case, but it's
3650 $legacyHeadline = false;
3654 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3655 # Does this apply to Unicode characters? Because we aren't
3656 # handling those here.
3657 $arrayKey = strtolower( $safeHeadline );
3658 if ( $legacyHeadline === false ) {
3659 $legacyArrayKey = false;
3661 $legacyArrayKey = strtolower( $legacyHeadline );
3664 # count how many in assoc. array so we can track dupes in anchors
3665 if ( isset( $refers[$arrayKey] ) ) {
3666 $refers[$arrayKey]++
;
3668 $refers[$arrayKey] = 1;
3670 if ( isset( $refers[$legacyArrayKey] ) ) {
3671 $refers[$legacyArrayKey]++
;
3673 $refers[$legacyArrayKey] = 1;
3676 # Don't number the heading if it is the only one (looks silly)
3677 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3678 # the two are different if the line contains a link
3679 $headline=$numbering . ' ' . $headline;
3682 # Create the anchor for linking from the TOC to the section
3683 $anchor = $safeHeadline;
3684 $legacyAnchor = $legacyHeadline;
3685 if ( $refers[$arrayKey] > 1 ) {
3686 $anchor .= '_' . $refers[$arrayKey];
3688 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3689 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3691 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3692 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3693 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3695 # give headline the correct <h#> tag
3696 if( $showEditLink && $sectionIndex !== false ) {
3698 # Put a T flag in the section identifier, to indicate to extractSections()
3699 # that sections inside <includeonly> should be counted.
3700 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3702 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3707 $head[$headlineCount] = $sk->makeHeadline( $level,
3708 $matches['attrib'][$headlineCount], $anchor, $headline,
3709 $editlink, $legacyAnchor );
3714 $this->mOutput
->setSections( $tocraw );
3716 # Never ever show TOC if no headers
3717 if( $numVisible < 1 ) {
3722 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3723 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3725 $toc = $sk->tocList( $toc );
3728 # split up and insert constructed headlines
3730 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3733 foreach( $blocks as $block ) {
3734 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3735 # This is the [edit] link that appears for the top block of text when
3736 # section editing is enabled
3738 # Disabled because it broke block formatting
3739 # For example, a bullet point in the top line
3740 # $full .= $sk->editSectionLink(0);
3743 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3744 # Top anchor now in skin
3748 if( !empty( $head[$i] ) ) {
3753 if( $this->mForceTocPosition
) {
3754 return str_replace( '<!--MWTOC-->', $toc, $full );
3761 * Transform wiki markup when saving a page by doing \r\n -> \n
3762 * conversion, substitting signatures, {{subst:}} templates, etc.
3764 * @param string $text the text to transform
3765 * @param Title &$title the Title object for the current article
3766 * @param User &$user the User object describing the current user
3767 * @param ParserOptions $options parsing options
3768 * @param bool $clearState whether to clear the parser state first
3769 * @return string the altered wiki markup
3772 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3773 $this->mOptions
= $options;
3774 $this->setTitle( $title );
3775 $this->setOutputType( self
::OT_WIKI
);
3777 if ( $clearState ) {
3778 $this->clearState();
3784 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3785 $text = $this->pstPass2( $text, $user );
3786 $text = $this->mStripState
->unstripBoth( $text );
3791 * Pre-save transform helper function
3794 function pstPass2( $text, $user ) {
3795 global $wgContLang, $wgLocaltimezone;
3797 /* Note: This is the timestamp saved as hardcoded wikitext to
3798 * the database, we use $wgContLang here in order to give
3799 * everyone the same signature and use the default one rather
3800 * than the one selected in each user's preferences.
3802 * (see also bug 12815)
3804 $ts = $this->mOptions
->getTimestamp();
3805 $tz = wfMsgForContent( 'timezone-utc' );
3806 if ( isset( $wgLocaltimezone ) ) {
3807 $unixts = wfTimestamp( TS_UNIX
, $ts );
3808 $oldtz = getenv( 'TZ' );
3809 putenv( 'TZ='.$wgLocaltimezone );
3810 $ts = date( 'YmdHis', $unixts );
3811 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3812 putenv( 'TZ='.$oldtz );
3815 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3817 # Variable replacement
3818 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3819 $text = $this->replaceVariables( $text );
3822 $sigText = $this->getUserSig( $user );
3823 $text = strtr( $text, array(
3825 '~~~~' => "$sigText $d",
3829 # Context links: [[|name]] and [[name (context)|]]
3831 global $wgLegalTitleChars;
3832 $tc = "[$wgLegalTitleChars]";
3833 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3835 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3836 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3837 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3838 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3840 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3841 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3842 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3843 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3845 $t = $this->mTitle
->getText();
3847 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3848 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3849 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3850 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3852 # if there's no context, don't bother duplicating the title
3853 $text = preg_replace( $p2, '[[\\1]]', $text );
3856 # Trim trailing whitespace
3857 $text = rtrim( $text );
3863 * Fetch the user's signature text, if any, and normalize to
3864 * validated, ready-to-insert wikitext.
3870 function getUserSig( &$user ) {
3871 global $wgMaxSigChars;
3873 $username = $user->getName();
3874 $nickname = $user->getOption( 'nickname' );
3875 $nickname = $nickname === '' ?
$username : $nickname;
3877 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3878 $nickname = $username;
3879 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3880 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3881 # Sig. might contain markup; validate this
3882 if( $this->validateSig( $nickname ) !== false ) {
3883 # Validated; clean up (if needed) and return it
3884 return $this->cleanSig( $nickname, true );
3886 # Failed to validate; fall back to the default
3887 $nickname = $username;
3888 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3892 // Make sure nickname doesnt get a sig in a sig
3893 $nickname = $this->cleanSigInSig( $nickname );
3895 # If we're still here, make it a link to the user page
3896 $userText = wfEscapeWikiText( $username );
3897 $nickText = wfEscapeWikiText( $nickname );
3898 if ( $user->isAnon() ) {
3899 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3901 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3906 * Check that the user's signature contains no bad XML
3908 * @param string $text
3909 * @return mixed An expanded string, or false if invalid.
3911 function validateSig( $text ) {
3912 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3916 * Clean up signature text
3918 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3919 * 2) Substitute all transclusions
3921 * @param string $text
3922 * @param $parsing Whether we're cleaning (preferences save) or parsing
3923 * @return string Signature text
3925 function cleanSig( $text, $parsing = false ) {
3928 $this->clearState();
3929 $this->setTitle( $wgTitle );
3930 $this->mOptions
= new ParserOptions
;
3931 $this->setOutputType
= self
::OT_PREPROCESS
;
3934 # Option to disable this feature
3935 if ( !$this->mOptions
->getCleanSignatures() ) {
3939 # FIXME: regex doesn't respect extension tags or nowiki
3940 # => Move this logic to braceSubstitution()
3941 $substWord = MagicWord
::get( 'subst' );
3942 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3943 $substText = '{{' . $substWord->getSynonym( 0 );
3945 $text = preg_replace( $substRegex, $substText, $text );
3946 $text = $this->cleanSigInSig( $text );
3947 $dom = $this->preprocessToDom( $text );
3948 $frame = $this->getPreprocessor()->newFrame();
3949 $text = $frame->expand( $dom );
3952 $text = $this->mStripState
->unstripBoth( $text );
3959 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3960 * @param string $text
3961 * @return string Signature text with /~{3,5}/ removed
3963 function cleanSigInSig( $text ) {
3964 $text = preg_replace( '/~{3,5}/', '', $text );
3969 * Set up some variables which are usually set up in parse()
3970 * so that an external function can call some class members with confidence
3973 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3974 $this->setTitle( $title );
3975 $this->mOptions
= $options;
3976 $this->setOutputType( $outputType );
3977 if ( $clearState ) {
3978 $this->clearState();
3983 * Wrapper for preprocess()
3985 * @param string $text the text to preprocess
3986 * @param ParserOptions $options options
3990 function transformMsg( $text, $options ) {
3992 static $executing = false;
3994 # Guard against infinite recursion
4000 wfProfileIn(__METHOD__
);
4001 $text = $this->preprocess( $text, $wgTitle, $options );
4004 wfProfileOut(__METHOD__
);
4009 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4010 * The callback should have the following form:
4011 * function myParserHook( $text, $params, &$parser ) { ... }
4013 * Transform and return $text. Use $parser for any required context, e.g. use
4014 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4018 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4019 * @param mixed $callback The callback function (and object) to use for the tag
4021 * @return The old value of the mTagHooks array associated with the hook
4023 function setHook( $tag, $callback ) {
4024 $tag = strtolower( $tag );
4025 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4026 $this->mTagHooks
[$tag] = $callback;
4027 if( !in_array( $tag, $this->mStripList
) ) {
4028 $this->mStripList
[] = $tag;
4034 function setTransparentTagHook( $tag, $callback ) {
4035 $tag = strtolower( $tag );
4036 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4037 $this->mTransparentTagHooks
[$tag] = $callback;
4043 * Remove all tag hooks
4045 function clearTagHooks() {
4046 $this->mTagHooks
= array();
4047 $this->mStripList
= $this->mDefaultStripList
;
4051 * Create a function, e.g. {{sum:1|2|3}}
4052 * The callback function should have the form:
4053 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4055 * Or with SFH_OBJECT_ARGS:
4056 * function myParserFunction( $parser, $frame, $args ) { ... }
4058 * The callback may either return the text result of the function, or an array with the text
4059 * in element 0, and a number of flags in the other elements. The names of the flags are
4060 * specified in the keys. Valid flags are:
4061 * found The text returned is valid, stop processing the template. This
4063 * nowiki Wiki markup in the return value should be escaped
4064 * isHTML The returned text is HTML, armour it against wikitext transformation
4068 * @param string $id The magic word ID
4069 * @param mixed $callback The callback function (and object) to use
4070 * @param integer $flags a combination of the following flags:
4071 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4073 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4074 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4075 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4076 * the arguments, and to control the way they are expanded.
4078 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4079 * arguments, for instance:
4080 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4082 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4083 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4084 * working if/when this is changed.
4086 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4089 * Please read the documentation in includes/parser/Preprocessor.php for more information
4090 * about the methods available in PPFrame and PPNode.
4092 * @return The old callback function for this name, if any
4094 function setFunctionHook( $id, $callback, $flags = 0 ) {
4095 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4096 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4098 # Add to function cache
4099 $mw = MagicWord
::get( $id );
4101 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4103 $synonyms = $mw->getSynonyms();
4104 $sensitive = intval( $mw->isCaseSensitive() );
4106 foreach ( $synonyms as $syn ) {
4108 if ( !$sensitive ) {
4109 $syn = strtolower( $syn );
4112 if ( !( $flags & SFH_NO_HASH
) ) {
4115 # Remove trailing colon
4116 if ( substr( $syn, -1, 1 ) === ':' ) {
4117 $syn = substr( $syn, 0, -1 );
4119 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4125 * Get all registered function hook identifiers
4129 function getFunctionHooks() {
4130 return array_keys( $this->mFunctionHooks
);
4134 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4135 * Placeholders created in Skin::makeLinkObj()
4136 * Returns an array of link CSS classes, indexed by PDBK.
4138 function replaceLinkHolders( &$text, $options = 0 ) {
4139 return $this->mLinkHolders
->replace( $text );
4143 * Replace <!--LINK--> link placeholders with plain text of links
4144 * (not HTML-formatted).
4145 * @param string $text
4148 function replaceLinkHoldersText( $text ) {
4149 return $this->mLinkHolders
->replaceText( $text );
4153 * Tag hook handler for 'pre'.
4155 function renderPreTag( $text, $attribs ) {
4156 // Backwards-compatibility hack
4157 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4159 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4160 return Xml
::openElement( 'pre', $attribs ) .
4161 Xml
::escapeTagsOnly( $content ) .
4166 * Renders an image gallery from a text with one line per image.
4167 * text labels may be given by using |-style alternative text. E.g.
4168 * Image:one.jpg|The number "1"
4169 * Image:tree.jpg|A tree
4170 * given as text will return the HTML of a gallery with two images,
4171 * labeled 'The number "1"' and
4174 function renderImageGallery( $text, $params ) {
4175 $ig = new ImageGallery();
4176 $ig->setContextTitle( $this->mTitle
);
4177 $ig->setShowBytes( false );
4178 $ig->setShowFilename( false );
4179 $ig->setParser( $this );
4180 $ig->setHideBadImages();
4181 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4182 $ig->useSkin( $this->mOptions
->getSkin() );
4183 $ig->mRevisionId
= $this->mRevisionId
;
4185 if( isset( $params['caption'] ) ) {
4186 $caption = $params['caption'];
4187 $caption = htmlspecialchars( $caption );
4188 $caption = $this->replaceInternalLinks( $caption );
4189 $ig->setCaptionHtml( $caption );
4191 if( isset( $params['perrow'] ) ) {
4192 $ig->setPerRow( $params['perrow'] );
4194 if( isset( $params['widths'] ) ) {
4195 $ig->setWidths( $params['widths'] );
4197 if( isset( $params['heights'] ) ) {
4198 $ig->setHeights( $params['heights'] );
4201 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4203 $lines = StringUtils
::explode( "\n", $text );
4204 foreach ( $lines as $line ) {
4205 # match lines like these:
4206 # Image:someimage.jpg|This is some image
4208 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4210 if ( count( $matches ) == 0 ) {
4214 if ( strpos( $matches[0], '%' ) !== false )
4215 $matches[1] = urldecode( $matches[1] );
4216 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4218 if( is_null( $nt ) ) {
4219 # Bogus title. Ignore these so we don't bomb out later.
4222 if ( isset( $matches[3] ) ) {
4223 $label = $matches[3];
4228 $html = $this->recursiveTagParse( trim( $label ) );
4230 $ig->add( $nt, $html );
4232 # Only add real images (bug #5586)
4233 if ( $nt->getNamespace() == NS_FILE
) {
4234 $this->mOutput
->addImage( $nt->getDBkey() );
4237 return $ig->toHTML();
4240 function getImageParams( $handler ) {
4242 $handlerClass = get_class( $handler );
4246 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4247 // Initialise static lists
4248 static $internalParamNames = array(
4249 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4250 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4251 'bottom', 'text-bottom' ),
4252 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4253 'upright', 'border', 'link', 'alt' ),
4255 static $internalParamMap;
4256 if ( !$internalParamMap ) {
4257 $internalParamMap = array();
4258 foreach ( $internalParamNames as $type => $names ) {
4259 foreach ( $names as $name ) {
4260 $magicName = str_replace( '-', '_', "img_$name" );
4261 $internalParamMap[$magicName] = array( $type, $name );
4266 // Add handler params
4267 $paramMap = $internalParamMap;
4269 $handlerParamMap = $handler->getParamMap();
4270 foreach ( $handlerParamMap as $magic => $paramName ) {
4271 $paramMap[$magic] = array( 'handler', $paramName );
4274 $this->mImageParams
[$handlerClass] = $paramMap;
4275 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4277 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4281 * Parse image options text and use it to make an image
4282 * @param Title $title
4283 * @param string $options
4284 * @param LinkHolderArray $holders
4286 function makeImage( $title, $options, $holders = false ) {
4287 # Check if the options text is of the form "options|alt text"
4289 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4290 # * left no resizing, just left align. label is used for alt= only
4291 # * right same, but right aligned
4292 # * none same, but not aligned
4293 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4294 # * center center the image
4295 # * framed Keep original image size, no magnify-button.
4296 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4297 # * upright reduce width for upright images, rounded to full __0 px
4298 # * border draw a 1px border around the image
4299 # * alt Text for HTML alt attribute (defaults to empty)
4300 # vertical-align values (no % or length right now):
4310 $parts = StringUtils
::explode( "|", $options );
4311 $sk = $this->mOptions
->getSkin();
4313 # Give extensions a chance to select the file revision for us
4314 $skip = $time = $descQuery = false;
4315 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4318 return $sk->link( $title );
4322 $imagename = $title->getDBkey();
4323 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4324 $file = $this->mFileCache
[$imagename][$time];
4326 $file = wfFindFile( $title, $time );
4327 if ( count( $this->mFileCache
) > 1000 ) {
4328 $this->mFileCache
= array();
4330 $this->mFileCache
[$imagename][$time] = $file;
4333 $handler = $file ?
$file->getHandler() : false;
4335 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4337 # Process the input parameters
4339 $params = array( 'frame' => array(), 'handler' => array(),
4340 'horizAlign' => array(), 'vertAlign' => array() );
4341 foreach( $parts as $part ) {
4342 $part = trim( $part );
4343 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4345 if( isset( $paramMap[$magicName] ) ) {
4346 list( $type, $paramName ) = $paramMap[$magicName];
4348 // Special case; width and height come in one variable together
4349 if( $type === 'handler' && $paramName === 'width' ) {
4351 # (bug 13500) In both cases (width/height and width only),
4352 # permit trailing "px" for backward compatibility.
4353 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4354 $width = intval( $m[1] );
4355 $height = intval( $m[2] );
4356 if ( $handler->validateParam( 'width', $width ) ) {
4357 $params[$type]['width'] = $width;
4360 if ( $handler->validateParam( 'height', $height ) ) {
4361 $params[$type]['height'] = $height;
4364 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4365 $width = intval( $value );
4366 if ( $handler->validateParam( 'width', $width ) ) {
4367 $params[$type]['width'] = $width;
4370 } // else no validation -- bug 13436
4372 if ( $type === 'handler' ) {
4373 # Validate handler parameter
4374 $validated = $handler->validateParam( $paramName, $value );
4376 # Validate internal parameters
4377 switch( $paramName ) {
4380 // @fixme - possibly check validity here for
4381 // manualthumb? downstream behavior seems odd with
4382 // missing manual thumbs.
4384 $value = $this->stripAltText( $value, $holders );
4387 $chars = self
::EXT_LINK_URL_CLASS
;
4388 $prots = $this->mUrlProtocols
;
4389 if ( $value === '' ) {
4390 $paramName = 'no-link';
4393 } elseif ( preg_match( "/^$prots/", $value ) ) {
4394 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4395 $paramName = 'link-url';
4396 $this->mOutput
->addExternalLink( $value );
4400 $linkTitle = Title
::newFromText( $value );
4402 $paramName = 'link-title';
4403 $value = $linkTitle;
4404 $this->mOutput
->addLink( $linkTitle );
4410 // Most other things appear to be empty or numeric...
4411 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4416 $params[$type][$paramName] = $value;
4420 if ( !$validated ) {
4425 # Process alignment parameters
4426 if ( $params['horizAlign'] ) {
4427 $params['frame']['align'] = key( $params['horizAlign'] );
4429 if ( $params['vertAlign'] ) {
4430 $params['frame']['valign'] = key( $params['vertAlign'] );
4433 $params['frame']['caption'] = $caption;
4435 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4437 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4438 # came to also set the caption, ordinary text after the image -- which
4439 # makes no sense, because that just repeats the text multiple times in
4440 # screen readers. It *also* came to set the title attribute.
4442 # Now that we have an alt attribute, we should not set the alt text to
4443 # equal the caption: that's worse than useless, it just repeats the
4444 # text. This is the framed/thumbnail case. If there's no caption, we
4445 # use the unnamed parameter for alt text as well, just for the time be-
4446 # ing, if the unnamed param is set and the alt param is not.
4448 # For the future, we need to figure out if we want to tweak this more,
4449 # e.g., introducing a title= parameter for the title; ignoring the un-
4450 # named parameter entirely for images without a caption; adding an ex-
4451 # plicit caption= parameter and preserving the old magic unnamed para-
4453 if( $caption !== '' && !isset( $params['frame']['alt'] )
4454 && !isset( $params['frame']['framed'] )
4455 && !isset( $params['frame']['thumbnail'] )
4456 && !isset( $params['frame']['manualthumb'] ) ) {
4457 $params['frame']['alt'] = $params['frame']['title'];
4460 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4462 # Linker does the rest
4463 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4465 # Give the handler a chance to modify the parser object
4467 $handler->parserTransformHook( $this, $file );
4473 protected function stripAltText( $caption, $holders ) {
4474 # Strip bad stuff out of the title (tooltip). We can't just use
4475 # replaceLinkHoldersText() here, because if this function is called
4476 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4478 $tooltip = $holders->replaceText( $caption );
4480 $tooltip = $this->replaceLinkHoldersText( $caption );
4483 # make sure there are no placeholders in thumbnail attributes
4484 # that are later expanded to html- so expand them now and
4486 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4487 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4493 * Set a flag in the output object indicating that the content is dynamic and
4494 * shouldn't be cached.
4496 function disableCache() {
4497 wfDebug( "Parser output marked as uncacheable.\n" );
4498 $this->mOutput
->mCacheTime
= -1;
4502 * Callback from the Sanitizer for expanding items found in HTML attribute
4503 * values, so they can be safely tested and escaped.
4504 * @param string $text
4505 * @param PPFrame $frame
4509 function attributeStripCallback( &$text, $frame = false ) {
4510 $text = $this->replaceVariables( $text, $frame );
4511 $text = $this->mStripState
->unstripBoth( $text );
4520 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4521 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4522 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4528 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4533 * Break wikitext input into sections, and either pull or replace
4534 * some particular section's text.
4536 * External callers should use the getSection and replaceSection methods.
4538 * @param string $text Page wikitext
4539 * @param string $section A section identifier string of the form:
4540 * <flag1> - <flag2> - ... - <section number>
4542 * Currently the only recognised flag is "T", which means the target section number
4543 * was derived during a template inclusion parse, in other words this is a template
4544 * section edit link. If no flags are given, it was an ordinary section edit link.
4545 * This flag is required to avoid a section numbering mismatch when a section is
4546 * enclosed by <includeonly> (bug 6563).
4548 * The section number 0 pulls the text before the first heading; other numbers will
4549 * pull the given section along with its lower-level subsections. If the section is
4550 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4552 * @param string $mode One of "get" or "replace"
4553 * @param string $newText Replacement text for section data.
4554 * @return string for "get", the extracted section text.
4555 * for "replace", the whole page with the section replaced.
4557 private function extractSections( $text, $section, $mode, $newText='' ) {
4559 $this->clearState();
4560 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4561 $this->mOptions
= new ParserOptions
;
4562 $this->setOutputType( self
::OT_WIKI
);
4564 $frame = $this->getPreprocessor()->newFrame();
4566 // Process section extraction flags
4568 $sectionParts = explode( '-', $section );
4569 $sectionIndex = array_pop( $sectionParts );
4570 foreach ( $sectionParts as $part ) {
4571 if ( $part === 'T' ) {
4572 $flags |
= self
::PTD_FOR_INCLUSION
;
4575 // Preprocess the text
4576 $root = $this->preprocessToDom( $text, $flags );
4578 // <h> nodes indicate section breaks
4579 // They can only occur at the top level, so we can find them by iterating the root's children
4580 $node = $root->getFirstChild();
4582 // Find the target section
4583 if ( $sectionIndex == 0 ) {
4584 // Section zero doesn't nest, level=big
4585 $targetLevel = 1000;
4588 if ( $node->getName() === 'h' ) {
4589 $bits = $node->splitHeading();
4590 if ( $bits['i'] == $sectionIndex ) {
4591 $targetLevel = $bits['level'];
4595 if ( $mode === 'replace' ) {
4596 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4598 $node = $node->getNextSibling();
4604 if ( $mode === 'get' ) {
4611 // Find the end of the section, including nested sections
4613 if ( $node->getName() === 'h' ) {
4614 $bits = $node->splitHeading();
4615 $curLevel = $bits['level'];
4616 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4620 if ( $mode === 'get' ) {
4621 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4623 $node = $node->getNextSibling();
4626 // Write out the remainder (in replace mode only)
4627 if ( $mode === 'replace' ) {
4628 // Output the replacement text
4629 // Add two newlines on -- trailing whitespace in $newText is conventionally
4630 // stripped by the editor, so we need both newlines to restore the paragraph gap
4631 $outText .= $newText . "\n\n";
4633 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4634 $node = $node->getNextSibling();
4638 if ( is_string( $outText ) ) {
4639 // Re-insert stripped tags
4640 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4647 * This function returns the text of a section, specified by a number ($section).
4648 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4649 * the first section before any such heading (section 0).
4651 * If a section contains subsections, these are also returned.
4653 * @param string $text text to look in
4654 * @param string $section section identifier
4655 * @param string $deftext default to return if section is not found
4656 * @return string text of the requested section
4658 public function getSection( $text, $section, $deftext='' ) {
4659 return $this->extractSections( $text, $section, "get", $deftext );
4662 public function replaceSection( $oldtext, $section, $text ) {
4663 return $this->extractSections( $oldtext, $section, "replace", $text );
4667 * Get the timestamp associated with the current revision, adjusted for
4668 * the default server-local timestamp
4670 function getRevisionTimestamp() {
4671 if ( is_null( $this->mRevisionTimestamp
) ) {
4672 wfProfileIn( __METHOD__
);
4674 $dbr = wfGetDB( DB_SLAVE
);
4675 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4676 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4678 // Normalize timestamp to internal MW format for timezone processing.
4679 // This has the added side-effect of replacing a null value with
4680 // the current time, which gives us more sensible behavior for
4682 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4684 // The cryptic '' timezone parameter tells to use the site-default
4685 // timezone offset instead of the user settings.
4687 // Since this value will be saved into the parser cache, served
4688 // to other users, and potentially even used inside links and such,
4689 // it needs to be consistent for all visitors.
4690 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4692 wfProfileOut( __METHOD__
);
4694 return $this->mRevisionTimestamp
;
4698 * Mutator for $mDefaultSort
4700 * @param $sort New value
4702 public function setDefaultSort( $sort ) {
4703 $this->mDefaultSort
= $sort;
4707 * Accessor for $mDefaultSort
4708 * Will use the title/prefixed title if none is set
4712 public function getDefaultSort() {
4713 global $wgCategoryPrefixedDefaultSortkey;
4714 if( $this->mDefaultSort
!== false ) {
4715 return $this->mDefaultSort
;
4716 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4717 !$wgCategoryPrefixedDefaultSortkey) {
4718 return $this->mTitle
->getText();
4720 return $this->mTitle
->getPrefixedText();
4725 * Accessor for $mDefaultSort
4726 * Unlike getDefaultSort(), will return false if none is set
4728 * @return string or false
4730 public function getCustomDefaultSort() {
4731 return $this->mDefaultSort
;
4735 * Try to guess the section anchor name based on a wikitext fragment
4736 * presumably extracted from a heading, for example "Header" from
4739 public function guessSectionNameFromWikiText( $text ) {
4740 # Strip out wikitext links(they break the anchor)
4741 $text = $this->stripSectionName( $text );
4742 $headline = Sanitizer
::decodeCharReferences( $text );
4744 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4745 $headline = trim( $headline );
4746 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4747 $replacearray = array(
4752 array_keys( $replacearray ),
4753 array_values( $replacearray ),
4758 * Strips a text string of wikitext for use in a section anchor
4760 * Accepts a text string and then removes all wikitext from the
4761 * string and leaves only the resultant text (i.e. the result of
4762 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4763 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4764 * to create valid section anchors by mimicing the output of the
4765 * parser when headings are parsed.
4767 * @param $text string Text string to be stripped of wikitext
4768 * for use in a Section anchor
4769 * @return Filtered text string
4771 public function stripSectionName( $text ) {
4772 # Strip internal link markup
4773 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4774 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4776 # Strip external link markup (FIXME: Not Tolerant to blank link text
4777 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4778 # on how many empty links there are on the page - need to figure that out.
4779 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4781 # Parse wikitext quotes (italics & bold)
4782 $text = $this->doQuotes($text);
4785 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4789 function srvus( $text ) {
4790 return $this->testSrvus( $text, $this->mOutputType
);
4794 * strip/replaceVariables/unstrip for preprocessor regression testing
4796 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4797 $this->clearState();
4798 if ( ! ( $title instanceof Title
) ) {
4799 $title = Title
::newFromText( $title );
4801 $this->mTitle
= $title;
4802 $this->mOptions
= $options;
4803 $this->setOutputType( $outputType );
4804 $text = $this->replaceVariables( $text );
4805 $text = $this->mStripState
->unstripBoth( $text );
4806 $text = Sanitizer
::removeHTMLtags( $text );
4810 function testPst( $text, $title, $options ) {
4812 if ( ! ( $title instanceof Title
) ) {
4813 $title = Title
::newFromText( $title );
4815 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4818 function testPreprocess( $text, $title, $options ) {
4819 if ( ! ( $title instanceof Title
) ) {
4820 $title = Title
::newFromText( $title );
4822 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4825 function markerSkipCallback( $s, $callback ) {
4828 while ( $i < strlen( $s ) ) {
4829 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4830 if ( $markerStart === false ) {
4831 $out .= call_user_func( $callback, substr( $s, $i ) );
4834 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4835 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4836 if ( $markerEnd === false ) {
4837 $out .= substr( $s, $markerStart );
4840 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4841 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4851 * @todo document, briefly.
4855 var $general, $nowiki;
4857 function __construct() {
4858 $this->general
= new ReplacementArray
;
4859 $this->nowiki
= new ReplacementArray
;
4862 function unstripGeneral( $text ) {
4863 wfProfileIn( __METHOD__
);
4866 $text = $this->general
->replace( $text );
4867 } while ( $text !== $oldText );
4868 wfProfileOut( __METHOD__
);
4872 function unstripNoWiki( $text ) {
4873 wfProfileIn( __METHOD__
);
4876 $text = $this->nowiki
->replace( $text );
4877 } while ( $text !== $oldText );
4878 wfProfileOut( __METHOD__
);
4882 function unstripBoth( $text ) {
4883 wfProfileIn( __METHOD__
);
4886 $text = $this->general
->replace( $text );
4887 $text = $this->nowiki
->replace( $text );
4888 } while ( $text !== $oldText );
4889 wfProfileOut( __METHOD__
);
4895 * @todo document, briefly.
4898 class OnlyIncludeReplacer
{
4901 function replace( $matches ) {
4902 if ( substr( $matches[1], -1 ) === "\n" ) {
4903 $this->output
.= substr( $matches[1], 0, -1 );
4905 $this->output
.= $matches[1];