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
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
124 function __construct( $conf = array() ) {
125 $this->mConf
= $conf;
126 $this->mTagHooks
= array();
127 $this->mTransparentTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
131 $this->mUrlProtocols
= wfUrlProtocols();
132 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
133 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
134 $this->mVarCache
= array();
135 if ( isset( $conf['preprocessorClass'] ) ) {
136 $this->mPreprocessorClass
= $conf['preprocessorClass'];
137 } elseif ( extension_loaded( 'domxml' ) ) {
138 // PECL extension that conflicts with the core DOM extension (bug 13770)
139 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
140 $this->mPreprocessorClass
= 'Preprocessor_Hash';
141 } elseif ( extension_loaded( 'dom' ) ) {
142 $this->mPreprocessorClass
= 'Preprocessor_DOM';
144 $this->mPreprocessorClass
= 'Preprocessor_Hash';
146 $this->mMarkerIndex
= 0;
147 $this->mFirstCall
= true;
151 * Reduce memory usage to reduce the impact of circular references
153 function __destruct() {
154 if ( isset( $this->mLinkHolders
) ) {
155 $this->mLinkHolders
->__destruct();
157 foreach ( $this as $name => $value ) {
158 unset( $this->$name );
163 * Do various kinds of initialisation on the first call of the parser
165 function firstCallInit() {
166 if ( !$this->mFirstCall
) {
169 $this->mFirstCall
= false;
171 wfProfileIn( __METHOD__
);
173 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
174 CoreParserFunctions
::register( $this );
175 $this->initialiseVariables();
177 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
178 wfProfileOut( __METHOD__
);
186 function clearState() {
187 wfProfileIn( __METHOD__
);
188 if ( $this->mFirstCall
) {
189 $this->firstCallInit();
191 $this->mOutput
= new ParserOutput
;
192 $this->mAutonumber
= 0;
193 $this->mLastSection
= '';
194 $this->mDTopen
= false;
195 $this->mIncludeCount
= array();
196 $this->mStripState
= new StripState
;
197 $this->mArgStack
= false;
198 $this->mInPre
= false;
199 $this->mLinkHolders
= new LinkHolderArray( $this );
201 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
204 * Prefix for temporary replacement strings for the multipass parser.
205 * \x07 should never appear in input as it's disallowed in XML.
206 * Using it at the front also gives us a little extra robustness
207 * since it shouldn't match when butted up against identifier-like
210 * Must not consist of all title characters, or else it will change
211 * the behaviour of <nowiki> in a link.
213 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
214 # Changed to \x7f to allow XML double-parsing -- TS
215 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
221 $this->mShowToc
= true;
222 $this->mForceTocPosition
= false;
223 $this->mIncludeSizes
= array(
227 $this->mPPNodeCount
= 0;
228 $this->mDefaultSort
= false;
229 $this->mHeadings
= array();
230 $this->mDoubleUnderscores
= array();
231 $this->mExpensiveFunctionCount
= 0;
234 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
235 $this->mPreprocessor
= null;
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
242 function setOutputType( $ot ) {
243 $this->mOutputType
= $ot;
246 'html' => $ot == self
::OT_HTML
,
247 'wiki' => $ot == self
::OT_WIKI
,
248 'pre' => $ot == self
::OT_PREPROCESS
,
253 * Set the context title
255 function setTitle( $t ) {
256 if ( !$t ||
$t instanceof FakeTitle
) {
257 $t = Title
::newFromText( 'NO TITLE' );
259 if ( strval( $t->getFragment() ) !== '' ) {
260 # Strip the fragment to avoid various odd effects
261 $this->mTitle
= clone $t;
262 $this->mTitle
->setFragment( '' );
269 * Accessor for mUniqPrefix.
273 function uniqPrefix() {
274 if( !isset( $this->mUniqPrefix
) ) {
275 // @fixme this is probably *horribly wrong*
276 // LanguageConverter seems to want $wgParser's uniqPrefix, however
277 // if this is called for a parser cache hit, the parser may not
278 // have ever been initialized in the first place.
279 // Not really sure what the heck is supposed to be going on here.
281 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
283 return $this->mUniqPrefix
;
287 * Convert wikitext to HTML
288 * Do not call this function recursively.
290 * @param $text String: text we want to parse
291 * @param $title A title object
292 * @param $options ParserOptions
293 * @param $linestart boolean
294 * @param $clearState boolean
295 * @param $revid Int: number to pass in {{REVISIONID}}
296 * @return ParserOutput a ParserOutput
298 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
300 * First pass--just handle <nowiki> sections, pass the rest off
301 * to internalParse() which does all the real work.
304 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
305 $fname = __METHOD__
.'-' . wfGetCaller();
306 wfProfileIn( __METHOD__
);
307 wfProfileIn( $fname );
313 $this->mOptions
= $options;
314 $this->setTitle( $title );
315 $oldRevisionId = $this->mRevisionId
;
316 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
317 if( $revid !== null ) {
318 $this->mRevisionId
= $revid;
319 $this->mRevisionTimestamp
= null;
321 $this->setOutputType( self
::OT_HTML
);
322 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
324 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
325 $text = $this->internalParse( $text );
326 $text = $this->mStripState
->unstripGeneral( $text );
328 # Clean up special characters, only run once, next-to-last before doBlockLevels
330 # french spaces, last one Guillemet-left
331 # only if there is something before the space
332 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
333 # french spaces, Guillemet-right
334 '/(\\302\\253) /' => '\\1 ',
335 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
337 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
339 $text = $this->doBlockLevels( $text, $linestart );
341 $this->replaceLinkHolders( $text );
343 # the position of the parserConvert() call should not be changed. it
344 # assumes that the links are all replaced and the only thing left
345 # is the <nowiki> mark.
346 # Side-effects: this calls $this->mOutput->setTitleText()
347 $text = $wgContLang->parserConvert( $text, $this );
349 $text = $this->mStripState
->unstripNoWiki( $text );
351 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
353 //!JF Move to its own function
355 $uniq_prefix = $this->mUniqPrefix
;
357 $elements = array_keys( $this->mTransparentTagHooks
);
358 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
360 foreach( $matches as $marker => $data ) {
361 list( $element, $content, $params, $tag ) = $data;
362 $tagName = strtolower( $element );
363 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
364 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
365 array( $content, $params, $this ) );
369 $this->mStripState
->general
->setPair( $marker, $output );
371 $text = $this->mStripState
->unstripGeneral( $text );
373 $text = Sanitizer
::normalizeCharReferences( $text );
375 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
376 $text = self
::tidy($text);
378 # attempt to sanitize at least some nesting problems
379 # (bug #2702 and quite a few others)
381 # ''Something [http://www.cool.com cool''] -->
382 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
383 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
384 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
385 # fix up an anchor inside another anchor, only
386 # at least for a single single nested link (bug 3695)
387 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
388 '\\1\\2</a>\\3</a>\\1\\4</a>',
389 # fix div inside inline elements- doBlockLevels won't wrap a line which
390 # contains a div, so fix it up here; replace
391 # div with escaped text
392 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
393 '\\1\\3<div\\5>\\6</div>\\8\\9',
394 # remove empty italic or bold tag pairs, some
395 # introduced by rules above
396 '/<([bi])><\/\\1>/' => '',
399 $text = preg_replace(
400 array_keys( $tidyregs ),
401 array_values( $tidyregs ),
404 global $wgExpensiveParserFunctionLimit;
405 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
406 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
409 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
411 # Information on include size limits, for the benefit of users who try to skirt them
412 if ( $this->mOptions
->getEnableLimitReport() ) {
413 global $wgExpensiveParserFunctionLimit;
414 $max = $this->mOptions
->getMaxIncludeSize();
415 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
417 "NewPP limit report\n" .
418 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
419 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
420 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
422 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
423 $text .= "\n<!-- \n$limitReport-->\n";
425 $this->mOutput
->setText( $text );
426 $this->mRevisionId
= $oldRevisionId;
427 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
428 wfProfileOut( $fname );
429 wfProfileOut( __METHOD__
);
431 return $this->mOutput
;
435 * Recursive parser entry point that can be called from an extension tag
438 function recursiveTagParse( $text ) {
439 wfProfileIn( __METHOD__
);
440 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
441 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
442 $text = $this->internalParse( $text );
443 wfProfileOut( __METHOD__
);
448 * Expand templates and variables in the text, producing valid, static wikitext.
449 * Also removes comments.
451 function preprocess( $text, $title, $options, $revid = null ) {
452 wfProfileIn( __METHOD__
);
454 $this->setOutputType( self
::OT_PREPROCESS
);
455 $this->mOptions
= $options;
456 $this->setTitle( $title );
457 if( $revid !== null ) {
458 $this->mRevisionId
= $revid;
460 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
461 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
462 $text = $this->replaceVariables( $text );
463 $text = $this->mStripState
->unstripBoth( $text );
464 wfProfileOut( __METHOD__
);
469 * Get a random string
474 function getRandomString() {
475 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
478 function &getTitle() { return $this->mTitle
; }
479 function getOptions() { return $this->mOptions
; }
480 function getRevisionId() { return $this->mRevisionId
; }
481 function getOutput() { return $this->mOutput
; }
482 function nextLinkID() { return $this->mLinkID++
; }
484 function getFunctionLang() {
485 global $wgLang, $wgContLang;
487 $target = $this->mOptions
->getTargetLanguage();
488 if ( $target !== null ) {
491 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
496 * Get a preprocessor object
498 function getPreprocessor() {
499 if ( !isset( $this->mPreprocessor
) ) {
500 $class = $this->mPreprocessorClass
;
501 $this->mPreprocessor
= new $class( $this );
503 return $this->mPreprocessor
;
507 * Replaces all occurrences of HTML-style comments and the given tags
508 * in the text with a random marker and returns the next text. The output
509 * parameter $matches will be an associative array filled with data in
511 * 'UNIQ-xxxxx' => array(
514 * array( 'param' => 'x' ),
515 * '<element param="x">tag content</element>' ) )
517 * @param $elements list of element names. Comments are always extracted.
518 * @param $text Source text string.
519 * @param $uniq_prefix
524 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
529 $taglist = implode( '|', $elements );
530 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
532 while ( '' != $text ) {
533 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
535 if( count( $p ) < 5 ) {
538 if( count( $p ) > 5 ) {
552 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
553 $stripped .= $marker;
555 if ( $close === '/>' ) {
556 // Empty element tag, <tag />
561 if( $element === '!--' ) {
564 $end = "/(<\\/$element\\s*>)/i";
566 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
568 if( count( $q ) < 3 ) {
569 # No end tag -- let it run out to the end of the text.
578 $matches[$marker] = array( $element,
580 Sanitizer
::decodeTagAttributes( $attributes ),
581 "<$element$attributes$close$content$tail" );
587 * Get a list of strippable XML-like elements
589 function getStripList() {
591 $elements = $this->mStripList
;
593 $elements[] = 'html';
595 if( $this->mOptions
->getUseTeX() ) {
596 $elements[] = 'math';
602 * @deprecated use replaceVariables
604 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
609 * Restores pre, math, and other extensions removed by strip()
611 * always call unstripNoWiki() after this one
613 * @deprecated use $this->mStripState->unstrip()
615 function unstrip( $text, $state ) {
616 return $state->unstripGeneral( $text );
620 * Always call this after unstrip() to preserve the order
623 * @deprecated use $this->mStripState->unstrip()
625 function unstripNoWiki( $text, $state ) {
626 return $state->unstripNoWiki( $text );
630 * @deprecated use $this->mStripState->unstripBoth()
632 function unstripForHTML( $text ) {
633 return $this->mStripState
->unstripBoth( $text );
637 * Add an item to the strip state
638 * Returns the unique tag which must be inserted into the stripped text
639 * The tag will be replaced with the original text in unstrip()
643 function insertStripItem( $text ) {
644 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
645 $this->mMarkerIndex++
;
646 $this->mStripState
->general
->setPair( $rnd, $text );
651 * Interface with html tidy, used if $wgUseTidy = true.
652 * If tidy isn't able to correct the markup, the original will be
653 * returned in all its glory with a warning comment appended.
655 * Either the external tidy program or the in-process tidy extension
656 * will be used depending on availability. Override the default
657 * $wgTidyInternal setting to disable the internal if it's not working.
659 * @param string $text Hideous HTML input
660 * @return string Corrected HTML output
664 function tidy( $text ) {
665 global $wgTidyInternal;
666 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
667 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
668 '<head><title>test</title></head><body>'.$text.'</body></html>';
669 if( $wgTidyInternal ) {
670 $correctedtext = self
::internalTidy( $wrappedtext );
672 $correctedtext = self
::externalTidy( $wrappedtext );
674 if( is_null( $correctedtext ) ) {
675 wfDebug( "Tidy error detected!\n" );
676 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
678 return $correctedtext;
682 * Spawn an external HTML tidy process and get corrected markup back from it.
687 function externalTidy( $text ) {
688 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
689 wfProfileIn( __METHOD__
);
694 $descriptorspec = array(
695 0 => array('pipe', 'r'),
696 1 => array('pipe', 'w'),
697 2 => array('file', wfGetNull(), 'a')
700 if( function_exists('proc_open') ) {
701 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
702 if (is_resource($process)) {
703 // Theoretically, this style of communication could cause a deadlock
704 // here. If the stdout buffer fills up, then writes to stdin could
705 // block. This doesn't appear to happen with tidy, because tidy only
706 // writes to stdout after it's finished reading from stdin. Search
707 // for tidyParseStdin and tidySaveStdout in console/tidy.c
708 fwrite($pipes[0], $text);
710 while (!feof($pipes[1])) {
711 $cleansource .= fgets($pipes[1], 1024);
714 proc_close($process);
718 wfProfileOut( __METHOD__
);
720 if( $cleansource == '' && $text != '') {
721 // Some kind of error happened, so we couldn't get the corrected text.
722 // Just give up; we'll use the source text and append a warning.
730 * Use the HTML tidy PECL extension to use the tidy library in-process,
731 * saving the overhead of spawning a new process.
733 * 'pear install tidy' should be able to compile the extension module.
738 function internalTidy( $text ) {
739 global $wgTidyConf, $IP, $wgDebugTidy;
740 wfProfileIn( __METHOD__
);
743 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
744 $tidy->cleanRepair();
745 if( $tidy->getStatus() == 2 ) {
746 // 2 is magic number for fatal error
747 // http://www.php.net/manual/en/function.tidy-get-status.php
750 $cleansource = tidy_get_output( $tidy );
752 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
753 $cleansource .= "<!--\nTidy reports:\n" .
754 str_replace( '-->', '-->', $tidy->errorBuffer
) .
758 wfProfileOut( __METHOD__
);
763 * parse the wiki syntax used to render tables
767 function doTableStuff ( $text ) {
768 wfProfileIn( __METHOD__
);
770 $lines = StringUtils
::explode( "\n", $text );
772 $td_history = array (); // Is currently a td tag open?
773 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
774 $tr_history = array (); // Is currently a tr tag open?
775 $tr_attributes = array (); // history of tr attributes
776 $has_opened_tr = array(); // Did this table open a <tr> element?
777 $indent_level = 0; // indent level of the table
779 foreach ( $lines as $outLine ) {
780 $line = trim( $outLine );
782 if( $line == '' ) { // empty line, go to next line
783 $out .= $outLine."\n";
786 $first_character = $line[0];
789 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
790 // First check if we are starting a new table
791 $indent_level = strlen( $matches[1] );
793 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
794 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
796 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
797 array_push ( $td_history , false );
798 array_push ( $last_tag_history , '' );
799 array_push ( $tr_history , false );
800 array_push ( $tr_attributes , '' );
801 array_push ( $has_opened_tr , false );
802 } else if ( count ( $td_history ) == 0 ) {
803 // Don't do any of the following
804 $out .= $outLine."\n";
806 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
807 // We are ending a table
808 $line = '</table>' . substr ( $line , 2 );
809 $last_tag = array_pop ( $last_tag_history );
811 if ( !array_pop ( $has_opened_tr ) ) {
812 $line = "<tr><td></td></tr>{$line}";
815 if ( array_pop ( $tr_history ) ) {
816 $line = "</tr>{$line}";
819 if ( array_pop ( $td_history ) ) {
820 $line = "</{$last_tag}>{$line}";
822 array_pop ( $tr_attributes );
823 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
824 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
825 // Now we have a table row
826 $line = preg_replace( '#^\|-+#', '', $line );
828 // Whats after the tag is now only attributes
829 $attributes = $this->mStripState
->unstripBoth( $line );
830 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
831 array_pop ( $tr_attributes );
832 array_push ( $tr_attributes , $attributes );
835 $last_tag = array_pop ( $last_tag_history );
836 array_pop ( $has_opened_tr );
837 array_push ( $has_opened_tr , true );
839 if ( array_pop ( $tr_history ) ) {
843 if ( array_pop ( $td_history ) ) {
844 $line = "</{$last_tag}>{$line}";
848 array_push ( $tr_history , false );
849 array_push ( $td_history , false );
850 array_push ( $last_tag_history , '' );
852 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
853 // This might be cell elements, td, th or captions
854 if ( substr ( $line , 0 , 2 ) === '|+' ) {
855 $first_character = '+';
856 $line = substr ( $line , 1 );
859 $line = substr ( $line , 1 );
861 if ( $first_character === '!' ) {
862 $line = str_replace ( '!!' , '||' , $line );
865 // Split up multiple cells on the same line.
866 // FIXME : This can result in improper nesting of tags processed
867 // by earlier parser steps, but should avoid splitting up eg
868 // attribute values containing literal "||".
869 $cells = StringUtils
::explodeMarkup( '||' , $line );
873 // Loop through each table cell
874 foreach ( $cells as $cell )
877 if ( $first_character !== '+' )
879 $tr_after = array_pop ( $tr_attributes );
880 if ( !array_pop ( $tr_history ) ) {
881 $previous = "<tr{$tr_after}>\n";
883 array_push ( $tr_history , true );
884 array_push ( $tr_attributes , '' );
885 array_pop ( $has_opened_tr );
886 array_push ( $has_opened_tr , true );
889 $last_tag = array_pop ( $last_tag_history );
891 if ( array_pop ( $td_history ) ) {
892 $previous = "</{$last_tag}>{$previous}";
895 if ( $first_character === '|' ) {
897 } else if ( $first_character === '!' ) {
899 } else if ( $first_character === '+' ) {
900 $last_tag = 'caption';
905 array_push ( $last_tag_history , $last_tag );
907 // A cell could contain both parameters and data
908 $cell_data = explode ( '|' , $cell , 2 );
910 // Bug 553: Note that a '|' inside an invalid link should not
911 // be mistaken as delimiting cell parameters
912 if ( strpos( $cell_data[0], '[[' ) !== false ) {
913 $cell = "{$previous}<{$last_tag}>{$cell}";
914 } else if ( count ( $cell_data ) == 1 )
915 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
917 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
918 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
919 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
923 array_push ( $td_history , true );
926 $out .= $outLine . "\n";
929 // Closing open td, tr && table
930 while ( count ( $td_history ) > 0 )
932 if ( array_pop ( $td_history ) ) {
935 if ( array_pop ( $tr_history ) ) {
938 if ( !array_pop ( $has_opened_tr ) ) {
939 $out .= "<tr><td></td></tr>\n" ;
942 $out .= "</table>\n";
945 // Remove trailing line-ending (b/c)
946 if ( substr( $out, -1 ) === "\n" ) {
947 $out = substr( $out, 0, -1 );
950 // special case: don't return empty table
951 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
955 wfProfileOut( __METHOD__
);
961 * Helper function for parse() that transforms wiki markup into
962 * HTML. Only called for $mOutputType == self::OT_HTML.
966 function internalParse( $text ) {
968 wfProfileIn( __METHOD__
);
970 # Hook to suspend the parser in this state
971 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
972 wfProfileOut( __METHOD__
);
976 $text = $this->replaceVariables( $text );
977 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
978 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
980 // Tables need to come after variable replacement for things to work
981 // properly; putting them before other transformations should keep
982 // exciting things like link expansions from showing up in surprising
984 $text = $this->doTableStuff( $text );
986 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
988 $text = $this->doDoubleUnderscore( $text );
989 $text = $this->doHeadings( $text );
990 if($this->mOptions
->getUseDynamicDates()) {
991 $df = DateFormatter
::getInstance();
992 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
994 $text = $this->doAllQuotes( $text );
995 $text = $this->replaceInternalLinks( $text );
996 $text = $this->replaceExternalLinks( $text );
998 # replaceInternalLinks may sometimes leave behind
999 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1000 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1002 $text = $this->doMagicLinks( $text );
1003 $text = $this->formatHeadings( $text, $isMain );
1005 wfProfileOut( __METHOD__
);
1010 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1011 * magic external links.
1016 function doMagicLinks( $text ) {
1017 wfProfileIn( __METHOD__
);
1018 $prots = $this->mUrlProtocols
;
1019 $urlChar = self
::EXT_LINK_URL_CLASS
;
1020 $text = preg_replace_callback(
1022 (<a.*?</a>) | # m[1]: Skip link text
1023 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1024 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1025 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1026 ISBN\s+(\b # m[5]: ISBN, capture number
1027 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1028 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1029 [0-9Xx] # check digit
1031 )!x', array( &$this, 'magicLinkCallback' ), $text );
1032 wfProfileOut( __METHOD__
);
1036 function magicLinkCallback( $m ) {
1037 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1040 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1043 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1044 # Free external link
1045 return $this->makeFreeExternalLink( $m[0] );
1046 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1048 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1052 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1054 $urlmsg = 'pubmedurl';
1057 throw new MWException( __METHOD__
.': unrecognised match type "' .
1058 substr($m[0], 0, 20 ) . '"' );
1060 $url = wfMsg( $urlmsg, $id);
1061 $sk = $this->mOptions
->getSkin();
1062 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1063 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1064 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1067 $num = strtr( $isbn, array(
1072 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1074 $titleObj->escapeLocalUrl() .
1075 "\" class=\"internal\">ISBN $isbn</a>";
1082 * Make a free external link, given a user-supplied URL
1086 function makeFreeExternalLink( $url ) {
1088 wfProfileIn( __METHOD__
);
1090 $sk = $this->mOptions
->getSkin();
1093 # The characters '<' and '>' (which were escaped by
1094 # removeHTMLtags()) should not be included in
1095 # URLs, per RFC 2396.
1097 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1098 $trail = substr($url, $m2[0][1]) . $trail;
1099 $url = substr($url, 0, $m2[0][1]);
1102 # Move trailing punctuation to $trail
1104 # If there is no left bracket, then consider right brackets fair game too
1105 if ( strpos( $url, '(' ) === false ) {
1109 $numSepChars = strspn( strrev( $url ), $sep );
1110 if ( $numSepChars ) {
1111 $trail = substr( $url, -$numSepChars ) . $trail;
1112 $url = substr( $url, 0, -$numSepChars );
1115 $url = Sanitizer
::cleanUrl( $url );
1117 # Is this an external image?
1118 $text = $this->maybeMakeExternalImage( $url );
1119 if ( $text === false ) {
1120 # Not an image, make a link
1121 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1122 $this->getExternalLinkAttribs() );
1123 # Register it in the output object...
1124 # Replace unnecessary URL escape codes with their equivalent characters
1125 $pasteurized = self
::replaceUnusualEscapes( $url );
1126 $this->mOutput
->addExternalLink( $pasteurized );
1128 wfProfileOut( __METHOD__
);
1129 return $text . $trail;
1134 * Parse headers and return html
1138 function doHeadings( $text ) {
1139 wfProfileIn( __METHOD__
);
1140 for ( $i = 6; $i >= 1; --$i ) {
1141 $h = str_repeat( '=', $i );
1142 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1143 "<h$i>\\1</h$i>", $text );
1145 wfProfileOut( __METHOD__
);
1150 * Replace single quotes with HTML markup
1152 * @return string the altered text
1154 function doAllQuotes( $text ) {
1155 wfProfileIn( __METHOD__
);
1157 $lines = StringUtils
::explode( "\n", $text );
1158 foreach ( $lines as $line ) {
1159 $outtext .= $this->doQuotes( $line ) . "\n";
1161 $outtext = substr($outtext, 0,-1);
1162 wfProfileOut( __METHOD__
);
1167 * Helper function for doAllQuotes()
1169 public function doQuotes( $text ) {
1170 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1171 if ( count( $arr ) == 1 )
1175 # First, do some preliminary work. This may shift some apostrophes from
1176 # being mark-up to being text. It also counts the number of occurrences
1177 # of bold and italics mark-ups.
1181 foreach ( $arr as $r )
1183 if ( ( $i %
2 ) == 1 )
1185 # If there are ever four apostrophes, assume the first is supposed to
1186 # be text, and the remaining three constitute mark-up for bold text.
1187 if ( strlen( $arr[$i] ) == 4 )
1192 # If there are more than 5 apostrophes in a row, assume they're all
1193 # text except for the last 5.
1194 else if ( strlen( $arr[$i] ) > 5 )
1196 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1199 # Count the number of occurrences of bold and italics mark-ups.
1200 # We are not counting sequences of five apostrophes.
1201 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1202 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1203 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1208 # If there is an odd number of both bold and italics, it is likely
1209 # that one of the bold ones was meant to be an apostrophe followed
1210 # by italics. Which one we cannot know for certain, but it is more
1211 # likely to be one that has a single-letter word before it.
1212 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1215 $firstsingleletterword = -1;
1216 $firstmultiletterword = -1;
1218 foreach ( $arr as $r )
1220 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1222 $x1 = substr ($arr[$i-1], -1);
1223 $x2 = substr ($arr[$i-1], -2, 1);
1225 if ($firstspace == -1) $firstspace = $i;
1226 } else if ($x2 === ' ') {
1227 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1229 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1235 # If there is a single-letter word, use it!
1236 if ($firstsingleletterword > -1)
1238 $arr [ $firstsingleletterword ] = "''";
1239 $arr [ $firstsingleletterword-1 ] .= "'";
1241 # If not, but there's a multi-letter word, use that one.
1242 else if ($firstmultiletterword > -1)
1244 $arr [ $firstmultiletterword ] = "''";
1245 $arr [ $firstmultiletterword-1 ] .= "'";
1247 # ... otherwise use the first one that has neither.
1248 # (notice that it is possible for all three to be -1 if, for example,
1249 # there is only one pentuple-apostrophe in the line)
1250 else if ($firstspace > -1)
1252 $arr [ $firstspace ] = "''";
1253 $arr [ $firstspace-1 ] .= "'";
1257 # Now let's actually convert our apostrophic mush to HTML!
1262 foreach ($arr as $r)
1266 if ($state === 'both')
1273 if (strlen ($r) == 2)
1276 { $output .= '</i>'; $state = ''; }
1277 else if ($state === 'bi')
1278 { $output .= '</i>'; $state = 'b'; }
1279 else if ($state === 'ib')
1280 { $output .= '</b></i><b>'; $state = 'b'; }
1281 else if ($state === 'both')
1282 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1283 else # $state can be 'b' or ''
1284 { $output .= '<i>'; $state .= 'i'; }
1286 else if (strlen ($r) == 3)
1289 { $output .= '</b>'; $state = ''; }
1290 else if ($state === 'bi')
1291 { $output .= '</i></b><i>'; $state = 'i'; }
1292 else if ($state === 'ib')
1293 { $output .= '</b>'; $state = 'i'; }
1294 else if ($state === 'both')
1295 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1296 else # $state can be 'i' or ''
1297 { $output .= '<b>'; $state .= 'b'; }
1299 else if (strlen ($r) == 5)
1302 { $output .= '</b><i>'; $state = 'i'; }
1303 else if ($state === 'i')
1304 { $output .= '</i><b>'; $state = 'b'; }
1305 else if ($state === 'bi')
1306 { $output .= '</i></b>'; $state = ''; }
1307 else if ($state === 'ib')
1308 { $output .= '</b></i>'; $state = ''; }
1309 else if ($state === 'both')
1310 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1311 else # ($state == '')
1312 { $buffer = ''; $state = 'both'; }
1317 # Now close all remaining tags. Notice that the order is important.
1318 if ($state === 'b' ||
$state === 'ib')
1320 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1322 if ($state === 'bi')
1324 # There might be lonely ''''', so make sure we have a buffer
1325 if ($state === 'both' && $buffer)
1326 $output .= '<b><i>'.$buffer.'</i></b>';
1332 * Replace external links (REL)
1334 * Note: this is all very hackish and the order of execution matters a lot.
1335 * Make sure to run maintenance/parserTests.php if you change this code.
1339 function replaceExternalLinks( $text ) {
1341 wfProfileIn( __METHOD__
);
1343 $sk = $this->mOptions
->getSkin();
1345 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1346 $s = array_shift( $bits );
1349 while ( $i<count( $bits ) ) {
1351 $protocol = $bits[$i++
];
1352 $text = $bits[$i++
];
1353 $trail = $bits[$i++
];
1355 # The characters '<' and '>' (which were escaped by
1356 # removeHTMLtags()) should not be included in
1357 # URLs, per RFC 2396.
1359 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1360 $text = substr($url, $m2[0][1]) . ' ' . $text;
1361 $url = substr($url, 0, $m2[0][1]);
1364 # If the link text is an image URL, replace it with an <img> tag
1365 # This happened by accident in the original parser, but some people used it extensively
1366 $img = $this->maybeMakeExternalImage( $text );
1367 if ( $img !== false ) {
1373 # Set linktype for CSS - if URL==text, link is essentially free
1374 $linktype = ($text === $url) ?
'free' : 'text';
1376 # No link text, e.g. [http://domain.tld/some.link]
1377 if ( $text == '' ) {
1378 # Autonumber if allowed. See bug #5918
1379 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1380 $text = '[' . ++
$this->mAutonumber
. ']';
1381 $linktype = 'autonumber';
1383 # Otherwise just use the URL
1384 $text = htmlspecialchars( $url );
1388 # Have link text, e.g. [http://domain.tld/some.link text]s
1390 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1393 $text = $wgContLang->markNoConversion($text);
1395 $url = Sanitizer
::cleanUrl( $url );
1397 if ( $this->mOptions
->mExternalLinkTarget
) {
1398 $attribs = array( 'target' => $this->mOptions
->mExternalLinkTarget
);
1403 # Use the encoded URL
1404 # This means that users can paste URLs directly into the text
1405 # Funny characters like ö aren't valid in URLs anyway
1406 # This was changed in August 2004
1407 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->getExternalLinkAttribs() )
1410 # Register link in the output object.
1411 # Replace unnecessary URL escape codes with the referenced character
1412 # This prevents spammers from hiding links from the filters
1413 $pasteurized = self
::replaceUnusualEscapes( $url );
1414 $this->mOutput
->addExternalLink( $pasteurized );
1417 wfProfileOut( __METHOD__
);
1421 function getExternalLinkAttribs() {
1423 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1424 $ns = $this->mTitle
->getNamespace();
1425 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1426 $attribs['rel'] = 'nofollow';
1428 if ( $this->mOptions
->getExternalLinkTarget() ) {
1429 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1436 * Replace unusual URL escape codes with their equivalent characters
1440 * @todo This can merge genuinely required bits in the path or query string,
1441 * breaking legit URLs. A proper fix would treat the various parts of
1442 * the URL differently; as a workaround, just use the output for
1443 * statistical records, not for actual linking/output.
1445 static function replaceUnusualEscapes( $url ) {
1446 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1447 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1451 * Callback function used in replaceUnusualEscapes().
1452 * Replaces unusual URL escape codes with their equivalent character
1456 private static function replaceUnusualEscapesCallback( $matches ) {
1457 $char = urldecode( $matches[0] );
1458 $ord = ord( $char );
1459 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1460 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1461 // No, shouldn't be escaped
1464 // Yes, leave it escaped
1470 * make an image if it's allowed, either through the global
1471 * option, through the exception, or through the on-wiki whitelist
1474 function maybeMakeExternalImage( $url ) {
1475 $sk = $this->mOptions
->getSkin();
1476 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1477 $imagesexception = !empty($imagesfrom);
1479 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1480 if( $imagesexception && is_array( $imagesfrom ) ) {
1481 $imagematch = false;
1482 foreach( $imagesfrom as $match ) {
1483 if( strpos( $url, $match ) === 0 ) {
1488 } elseif( $imagesexception ) {
1489 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1491 $imagematch = false;
1493 if ( $this->mOptions
->getAllowExternalImages()
1494 ||
( $imagesexception && $imagematch ) ) {
1495 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1497 $text = $sk->makeExternalImage( $url );
1500 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1501 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1502 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1503 foreach( $whitelist as $entry ) {
1504 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1505 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1507 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1508 # Image matches a whitelist entry
1509 $text = $sk->makeExternalImage( $url );
1518 * Process [[ ]] wikilinks
1519 * @return processed text
1523 function replaceInternalLinks( $s ) {
1524 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1529 * Process [[ ]] wikilinks (RIL)
1530 * @return LinkHolderArray
1534 function replaceInternalLinks2( &$s ) {
1537 wfProfileIn( __METHOD__
);
1539 wfProfileIn( __METHOD__
.'-setup' );
1540 static $tc = FALSE, $e1, $e1_img;
1541 # the % is needed to support urlencoded titles as well
1543 $tc = Title
::legalChars() . '#%';
1544 # Match a link having the form [[namespace:link|alternate]]trail
1545 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1546 # Match cases where there is no "]]", which might still be images
1547 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1550 $sk = $this->mOptions
->getSkin();
1551 $holders = new LinkHolderArray( $this );
1553 #split the entire text string on occurences of [[
1554 $a = StringUtils
::explode( '[[', ' ' . $s );
1555 #get the first element (all text up to first [[), and remove the space we added
1558 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1559 $s = substr( $s, 1 );
1561 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1563 if ( $useLinkPrefixExtension ) {
1564 # Match the end of a line for a word that's not followed by whitespace,
1565 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1566 $e2 = wfMsgForContent( 'linkprefix' );
1569 if( is_null( $this->mTitle
) ) {
1570 wfProfileOut( __METHOD__
.'-setup' );
1571 wfProfileOut( __METHOD__
);
1572 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1574 $nottalk = !$this->mTitle
->isTalkPage();
1576 if ( $useLinkPrefixExtension ) {
1578 if ( preg_match( $e2, $s, $m ) ) {
1579 $first_prefix = $m[2];
1581 $first_prefix = false;
1587 if($wgContLang->hasVariants()) {
1588 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1590 $selflink = array($this->mTitle
->getPrefixedText());
1592 $useSubpages = $this->areSubpagesAllowed();
1593 wfProfileOut( __METHOD__
.'-setup' );
1595 # Loop for each link
1596 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1597 # Check for excessive memory usage
1598 if ( $holders->isBig() ) {
1600 # Do the existence check, replace the link holders and clear the array
1601 $holders->replace( $s );
1605 if ( $useLinkPrefixExtension ) {
1606 wfProfileIn( __METHOD__
.'-prefixhandling' );
1607 if ( preg_match( $e2, $s, $m ) ) {
1615 $prefix = $first_prefix;
1616 $first_prefix = false;
1618 wfProfileOut( __METHOD__
.'-prefixhandling' );
1621 $might_be_img = false;
1623 wfProfileIn( __METHOD__
."-e1" );
1624 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1626 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1627 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1628 # the real problem is with the $e1 regex
1631 # Still some problems for cases where the ] is meant to be outside punctuation,
1632 # and no image is in sight. See bug 2095.
1635 substr( $m[3], 0, 1 ) === ']' &&
1636 strpos($text, '[') !== false
1639 $text .= ']'; # so that replaceExternalLinks($text) works later
1640 $m[3] = substr( $m[3], 1 );
1642 # fix up urlencoded title texts
1643 if( strpos( $m[1], '%' ) !== false ) {
1644 # Should anchors '#' also be rejected?
1645 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1648 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1649 $might_be_img = true;
1651 if ( strpos( $m[1], '%' ) !== false ) {
1652 $m[1] = urldecode($m[1]);
1655 } else { # Invalid form; output directly
1656 $s .= $prefix . '[[' . $line ;
1657 wfProfileOut( __METHOD__
."-e1" );
1660 wfProfileOut( __METHOD__
."-e1" );
1661 wfProfileIn( __METHOD__
."-misc" );
1663 # Don't allow internal links to pages containing
1664 # PROTO: where PROTO is a valid URL protocol; these
1665 # should be external links.
1666 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1667 $s .= $prefix . '[[' . $line ;
1668 wfProfileOut( __METHOD__
."-misc" );
1672 # Make subpage if necessary
1673 if( $useSubpages ) {
1674 $link = $this->maybeDoSubpageLink( $m[1], $text );
1679 $noforce = (substr($m[1], 0, 1) !== ':');
1681 # Strip off leading ':'
1682 $link = substr($link, 1);
1685 wfProfileOut( __METHOD__
."-misc" );
1686 wfProfileIn( __METHOD__
."-title" );
1687 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1689 $s .= $prefix . '[[' . $line;
1690 wfProfileOut( __METHOD__
."-title" );
1694 $ns = $nt->getNamespace();
1695 $iw = $nt->getInterWiki();
1696 wfProfileOut( __METHOD__
."-title" );
1698 if ($might_be_img) { # if this is actually an invalid link
1699 wfProfileIn( __METHOD__
."-might_be_img" );
1700 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1703 #look at the next 'line' to see if we can close it there
1705 $next_line = $a->current();
1706 if ( $next_line === false ||
$next_line === null ) {
1709 $m = explode( ']]', $next_line, 3 );
1710 if ( count( $m ) == 3 ) {
1711 # the first ]] closes the inner link, the second the image
1713 $text .= "[[{$m[0]}]]{$m[1]}";
1716 } elseif ( count( $m ) == 2 ) {
1717 #if there's exactly one ]] that's fine, we'll keep looking
1718 $text .= "[[{$m[0]}]]{$m[1]}";
1720 #if $next_line is invalid too, we need look no further
1721 $text .= '[[' . $next_line;
1726 # we couldn't find the end of this imageLink, so output it raw
1727 #but don't ignore what might be perfectly normal links in the text we've examined
1728 $holders->merge( $this->replaceInternalLinks2( $text ) );
1729 $s .= "{$prefix}[[$link|$text";
1730 # note: no $trail, because without an end, there *is* no trail
1731 wfProfileOut( __METHOD__
."-might_be_img" );
1734 } else { #it's not an image, so output it raw
1735 $s .= "{$prefix}[[$link|$text";
1736 # note: no $trail, because without an end, there *is* no trail
1737 wfProfileOut( __METHOD__
."-might_be_img" );
1740 wfProfileOut( __METHOD__
."-might_be_img" );
1743 $wasblank = ( '' == $text );
1744 if( $wasblank ) $text = $link;
1746 # Link not escaped by : , create the various objects
1750 wfProfileIn( __METHOD__
."-interwiki" );
1751 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1752 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1753 $s = rtrim($s . $prefix);
1754 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1755 wfProfileOut( __METHOD__
."-interwiki" );
1758 wfProfileOut( __METHOD__
."-interwiki" );
1760 if ( $ns == NS_IMAGE
) {
1761 wfProfileIn( __METHOD__
."-image" );
1762 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1763 # recursively parse links inside the image caption
1764 # actually, this will parse them in any other parameters, too,
1765 # but it might be hard to fix that, and it doesn't matter ATM
1766 $text = $this->replaceExternalLinks($text);
1767 $holders->merge( $this->replaceInternalLinks2( $text ) );
1769 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1770 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1772 $this->mOutput
->addImage( $nt->getDBkey() );
1773 wfProfileOut( __METHOD__
."-image" );
1778 if ( $ns == NS_CATEGORY
) {
1779 wfProfileIn( __METHOD__
."-category" );
1780 $s = rtrim($s . "\n"); # bug 87
1783 $sortkey = $this->getDefaultSort();
1787 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1788 $sortkey = str_replace( "\n", '', $sortkey );
1789 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1790 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1793 * Strip the whitespace Category links produce, see bug 87
1794 * @todo We might want to use trim($tmp, "\n") here.
1796 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1798 wfProfileOut( __METHOD__
."-category" );
1803 # Self-link checking
1804 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1805 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1806 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1811 # Special and Media are pseudo-namespaces; no pages actually exist in them
1812 if( $ns == NS_MEDIA
) {
1813 # Give extensions a chance to select the file revision for us
1814 $skip = $time = false;
1815 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1817 $link = $sk->link( $nt );
1819 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1821 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1822 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1823 $this->mOutput
->addImage( $nt->getDBkey() );
1825 } elseif( $ns == NS_SPECIAL
) {
1826 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1827 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1829 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1832 } elseif( $ns == NS_IMAGE
) {
1833 $img = wfFindFile( $nt );
1835 // Force a blue link if the file exists; may be a remote
1836 // upload on the shared repository, and we want to see its
1837 // auto-generated page.
1838 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1839 $this->mOutput
->addLink( $nt );
1843 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1845 wfProfileOut( __METHOD__
);
1850 * Make a link placeholder. The text returned can be later resolved to a real link with
1851 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1852 * parsing of interwiki links, and secondly to allow all existence checks and
1853 * article length checks (for stub links) to be bundled into a single query.
1857 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1858 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1862 * Render a forced-blue link inline; protect against double expansion of
1863 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1864 * Since this little disaster has to split off the trail text to avoid
1865 * breaking URLs in the following text without breaking trails on the
1866 * wiki links, it's been made into a horrible function.
1869 * @param string $text
1870 * @param string $query
1871 * @param string $trail
1872 * @param string $prefix
1873 * @return string HTML-wikitext mix oh yuck
1875 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1876 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1877 $sk = $this->mOptions
->getSkin();
1878 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1879 return $this->armorLinks( $link ) . $trail;
1883 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1884 * going to go through further parsing steps before inline URL expansion.
1886 * Not needed quite as much as it used to be since free links are a bit
1887 * more sensible these days. But bracketed links are still an issue.
1889 * @param string more-or-less HTML
1890 * @return string less-or-more HTML with NOPARSE bits
1892 function armorLinks( $text ) {
1893 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1894 "{$this->mUniqPrefix}NOPARSE$1", $text );
1898 * Return true if subpage links should be expanded on this page.
1901 function areSubpagesAllowed() {
1902 # Some namespaces don't allow subpages
1903 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1907 * Handle link to subpage if necessary
1908 * @param string $target the source of the link
1909 * @param string &$text the link text, modified as necessary
1910 * @return string the full name of the link
1913 function maybeDoSubpageLink($target, &$text) {
1916 # :Foobar -- override special treatment of prefix (images, language links)
1917 # /Foobar -- convert to CurrentPage/Foobar
1918 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1919 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1920 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1922 wfProfileIn( __METHOD__
);
1923 $ret = $target; # default return value is no change
1925 # Some namespaces don't allow subpages,
1926 # so only perform processing if subpages are allowed
1927 if( $this->areSubpagesAllowed() ) {
1928 $hash = strpos( $target, '#' );
1929 if( $hash !== false ) {
1930 $suffix = substr( $target, $hash );
1931 $target = substr( $target, 0, $hash );
1936 $target = trim( $target );
1937 # Look at the first character
1938 if( $target != '' && $target{0} === '/' ) {
1939 # / at end means we don't want the slash to be shown
1941 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1942 if( $trailingSlashes ) {
1943 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1945 $noslash = substr( $target, 1 );
1948 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1949 if( '' === $text ) {
1950 $text = $target . $suffix;
1951 } # this might be changed for ugliness reasons
1953 # check for .. subpage backlinks
1955 $nodotdot = $target;
1956 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1958 $nodotdot = substr( $nodotdot, 3 );
1960 if($dotdotcount > 0) {
1961 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1962 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1963 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1964 # / at the end means don't show full path
1965 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1966 $nodotdot = substr( $nodotdot, 0, -1 );
1967 if( '' === $text ) {
1968 $text = $nodotdot . $suffix;
1971 $nodotdot = trim( $nodotdot );
1972 if( $nodotdot != '' ) {
1973 $ret .= '/' . $nodotdot;
1981 wfProfileOut( __METHOD__
);
1986 * Used by doBlockLevels()
1989 /* private */ function closeParagraph() {
1991 if ( '' != $this->mLastSection
) {
1992 $result = '</' . $this->mLastSection
. ">\n";
1994 $this->mInPre
= false;
1995 $this->mLastSection
= '';
1998 # getCommon() returns the length of the longest common substring
1999 # of both arguments, starting at the beginning of both.
2001 /* private */ function getCommon( $st1, $st2 ) {
2002 $fl = strlen( $st1 );
2003 $shorter = strlen( $st2 );
2004 if ( $fl < $shorter ) { $shorter = $fl; }
2006 for ( $i = 0; $i < $shorter; ++
$i ) {
2007 if ( $st1{$i} != $st2{$i} ) { break; }
2011 # These next three functions open, continue, and close the list
2012 # element appropriate to the prefix character passed into them.
2014 /* private */ function openList( $char ) {
2015 $result = $this->closeParagraph();
2017 if ( '*' === $char ) { $result .= '<ul><li>'; }
2018 else if ( '#' === $char ) { $result .= '<ol><li>'; }
2019 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
2020 else if ( ';' === $char ) {
2021 $result .= '<dl><dt>';
2022 $this->mDTopen
= true;
2024 else { $result = '<!-- ERR 1 -->'; }
2029 /* private */ function nextItem( $char ) {
2030 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2031 else if ( ':' === $char ||
';' === $char ) {
2033 if ( $this->mDTopen
) { $close = '</dt>'; }
2034 if ( ';' === $char ) {
2035 $this->mDTopen
= true;
2036 return $close . '<dt>';
2038 $this->mDTopen
= false;
2039 return $close . '<dd>';
2042 return '<!-- ERR 2 -->';
2045 /* private */ function closeList( $char ) {
2046 if ( '*' === $char ) { $text = '</li></ul>'; }
2047 else if ( '#' === $char ) { $text = '</li></ol>'; }
2048 else if ( ':' === $char ) {
2049 if ( $this->mDTopen
) {
2050 $this->mDTopen
= false;
2051 $text = '</dt></dl>';
2053 $text = '</dd></dl>';
2056 else { return '<!-- ERR 3 -->'; }
2062 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2065 * @return string the lists rendered as HTML
2067 function doBlockLevels( $text, $linestart ) {
2068 wfProfileIn( __METHOD__
);
2070 # Parsing through the text line by line. The main thing
2071 # happening here is handling of block-level elements p, pre,
2072 # and making lists from lines starting with * # : etc.
2074 $textLines = StringUtils
::explode( "\n", $text );
2076 $lastPrefix = $output = '';
2077 $this->mDTopen
= $inBlockElem = false;
2079 $paragraphStack = false;
2081 foreach ( $textLines as $oLine ) {
2083 if ( !$linestart ) {
2089 $lastPrefixLength = strlen( $lastPrefix );
2090 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2091 $preOpenMatch = preg_match('/<pre/i', $oLine );
2092 if ( !$this->mInPre
) {
2093 # Multiple prefixes may abut each other for nested lists.
2094 $prefixLength = strspn( $oLine, '*#:;' );
2095 $prefix = substr( $oLine, 0, $prefixLength );
2098 $prefix2 = str_replace( ';', ':', $prefix );
2099 $t = substr( $oLine, $prefixLength );
2100 $this->mInPre
= (bool)$preOpenMatch;
2102 # Don't interpret any other prefixes in preformatted text
2104 $prefix = $prefix2 = '';
2109 if( $prefixLength && $lastPrefix === $prefix2 ) {
2110 # Same as the last item, so no need to deal with nesting or opening stuff
2111 $output .= $this->nextItem( substr( $prefix, -1 ) );
2112 $paragraphStack = false;
2114 if ( substr( $prefix, -1 ) === ';') {
2115 # The one nasty exception: definition lists work like this:
2116 # ; title : definition text
2117 # So we check for : in the remainder text to split up the
2118 # title and definition, without b0rking links.
2120 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2122 $output .= $term . $this->nextItem( ':' );
2125 } elseif( $prefixLength ||
$lastPrefixLength ) {
2126 # Either open or close a level...
2127 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2128 $paragraphStack = false;
2130 while( $commonPrefixLength < $lastPrefixLength ) {
2131 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2132 --$lastPrefixLength;
2134 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2135 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2137 while ( $prefixLength > $commonPrefixLength ) {
2138 $char = substr( $prefix, $commonPrefixLength, 1 );
2139 $output .= $this->openList( $char );
2141 if ( ';' === $char ) {
2142 # FIXME: This is dupe of code above
2143 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2145 $output .= $term . $this->nextItem( ':' );
2148 ++
$commonPrefixLength;
2150 $lastPrefix = $prefix2;
2152 if( 0 == $prefixLength ) {
2153 wfProfileIn( __METHOD__
."-paragraph" );
2154 # No prefix (not in list)--go to paragraph mode
2155 // XXX: use a stack for nestable elements like span, table and div
2156 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2157 $closematch = preg_match(
2158 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2159 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2160 if ( $openmatch or $closematch ) {
2161 $paragraphStack = false;
2162 #Â TODO bug 5718: paragraph closed
2163 $output .= $this->closeParagraph();
2164 if ( $preOpenMatch and !$preCloseMatch ) {
2165 $this->mInPre
= true;
2167 if ( $closematch ) {
2168 $inBlockElem = false;
2170 $inBlockElem = true;
2172 } else if ( !$inBlockElem && !$this->mInPre
) {
2173 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2175 if ($this->mLastSection
!== 'pre') {
2176 $paragraphStack = false;
2177 $output .= $this->closeParagraph().'<pre>';
2178 $this->mLastSection
= 'pre';
2180 $t = substr( $t, 1 );
2183 if ( '' == trim($t) ) {
2184 if ( $paragraphStack ) {
2185 $output .= $paragraphStack.'<br />';
2186 $paragraphStack = false;
2187 $this->mLastSection
= 'p';
2189 if ($this->mLastSection
!== 'p' ) {
2190 $output .= $this->closeParagraph();
2191 $this->mLastSection
= '';
2192 $paragraphStack = '<p>';
2194 $paragraphStack = '</p><p>';
2198 if ( $paragraphStack ) {
2199 $output .= $paragraphStack;
2200 $paragraphStack = false;
2201 $this->mLastSection
= 'p';
2202 } else if ($this->mLastSection
!== 'p') {
2203 $output .= $this->closeParagraph().'<p>';
2204 $this->mLastSection
= 'p';
2209 wfProfileOut( __METHOD__
."-paragraph" );
2211 // somewhere above we forget to get out of pre block (bug 785)
2212 if($preCloseMatch && $this->mInPre
) {
2213 $this->mInPre
= false;
2215 if ($paragraphStack === false) {
2219 while ( $prefixLength ) {
2220 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2223 if ( '' != $this->mLastSection
) {
2224 $output .= '</' . $this->mLastSection
. '>';
2225 $this->mLastSection
= '';
2228 wfProfileOut( __METHOD__
);
2233 * Split up a string on ':', ignoring any occurences inside tags
2234 * to prevent illegal overlapping.
2235 * @param string $str the string to split
2236 * @param string &$before set to everything before the ':'
2237 * @param string &$after set to everything after the ':'
2238 * return string the position of the ':', or false if none found
2240 function findColonNoLinks($str, &$before, &$after) {
2241 wfProfileIn( __METHOD__
);
2243 $pos = strpos( $str, ':' );
2244 if( $pos === false ) {
2246 wfProfileOut( __METHOD__
);
2250 $lt = strpos( $str, '<' );
2251 if( $lt === false ||
$lt > $pos ) {
2252 // Easy; no tag nesting to worry about
2253 $before = substr( $str, 0, $pos );
2254 $after = substr( $str, $pos+
1 );
2255 wfProfileOut( __METHOD__
);
2259 // Ugly state machine to walk through avoiding tags.
2260 $state = self
::COLON_STATE_TEXT
;
2262 $len = strlen( $str );
2263 for( $i = 0; $i < $len; $i++
) {
2267 // (Using the number is a performance hack for common cases)
2268 case 0: // self::COLON_STATE_TEXT:
2271 // Could be either a <start> tag or an </end> tag
2272 $state = self
::COLON_STATE_TAGSTART
;
2277 $before = substr( $str, 0, $i );
2278 $after = substr( $str, $i +
1 );
2279 wfProfileOut( __METHOD__
);
2282 // Embedded in a tag; don't break it.
2285 // Skip ahead looking for something interesting
2286 $colon = strpos( $str, ':', $i );
2287 if( $colon === false ) {
2288 // Nothing else interesting
2289 wfProfileOut( __METHOD__
);
2292 $lt = strpos( $str, '<', $i );
2293 if( $stack === 0 ) {
2294 if( $lt === false ||
$colon < $lt ) {
2296 $before = substr( $str, 0, $colon );
2297 $after = substr( $str, $colon +
1 );
2298 wfProfileOut( __METHOD__
);
2302 if( $lt === false ) {
2303 // Nothing else interesting to find; abort!
2304 // We're nested, but there's no close tags left. Abort!
2307 // Skip ahead to next tag start
2309 $state = self
::COLON_STATE_TAGSTART
;
2312 case 1: // self::COLON_STATE_TAG:
2317 $state = self
::COLON_STATE_TEXT
;
2320 // Slash may be followed by >?
2321 $state = self
::COLON_STATE_TAGSLASH
;
2327 case 2: // self::COLON_STATE_TAGSTART:
2330 $state = self
::COLON_STATE_CLOSETAG
;
2333 $state = self
::COLON_STATE_COMMENT
;
2336 // Illegal early close? This shouldn't happen D:
2337 $state = self
::COLON_STATE_TEXT
;
2340 $state = self
::COLON_STATE_TAG
;
2343 case 3: // self::COLON_STATE_CLOSETAG:
2348 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2349 wfProfileOut( __METHOD__
);
2352 $state = self
::COLON_STATE_TEXT
;
2355 case self
::COLON_STATE_TAGSLASH
:
2357 // Yes, a self-closed tag <blah/>
2358 $state = self
::COLON_STATE_TEXT
;
2360 // Probably we're jumping the gun, and this is an attribute
2361 $state = self
::COLON_STATE_TAG
;
2364 case 5: // self::COLON_STATE_COMMENT:
2366 $state = self
::COLON_STATE_COMMENTDASH
;
2369 case self
::COLON_STATE_COMMENTDASH
:
2371 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2373 $state = self
::COLON_STATE_COMMENT
;
2376 case self
::COLON_STATE_COMMENTDASHDASH
:
2378 $state = self
::COLON_STATE_TEXT
;
2380 $state = self
::COLON_STATE_COMMENT
;
2384 throw new MWException( "State machine error in " . __METHOD__
);
2388 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2391 wfProfileOut( __METHOD__
);
2396 * Return value of a magic variable (like PAGENAME)
2400 function getVariableValue( $index ) {
2401 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2404 * Some of these require message or data lookups and can be
2405 * expensive to check many times.
2407 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2408 if ( isset( $this->mVarCache
[$index] ) ) {
2409 return $this->mVarCache
[$index];
2413 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2414 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2417 global $wgLocaltimezone;
2418 if ( isset( $wgLocaltimezone ) ) {
2419 $oldtz = getenv( 'TZ' );
2420 putenv( 'TZ='.$wgLocaltimezone );
2423 wfSuppressWarnings(); // E_STRICT system time bitching
2424 $localTimestamp = date( 'YmdHis', $ts );
2425 $localMonth = date( 'm', $ts );
2426 $localMonthName = date( 'n', $ts );
2427 $localDay = date( 'j', $ts );
2428 $localDay2 = date( 'd', $ts );
2429 $localDayOfWeek = date( 'w', $ts );
2430 $localWeek = date( 'W', $ts );
2431 $localYear = date( 'Y', $ts );
2432 $localHour = date( 'H', $ts );
2433 if ( isset( $wgLocaltimezone ) ) {
2434 putenv( 'TZ='.$oldtz );
2436 wfRestoreWarnings();
2439 case 'currentmonth':
2440 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2441 case 'currentmonthname':
2442 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2443 case 'currentmonthnamegen':
2444 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2445 case 'currentmonthabbrev':
2446 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2448 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2450 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2452 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2453 case 'localmonthname':
2454 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2455 case 'localmonthnamegen':
2456 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2457 case 'localmonthabbrev':
2458 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2460 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2462 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2464 return wfEscapeWikiText( $this->mTitle
->getText() );
2466 return $this->mTitle
->getPartialURL();
2467 case 'fullpagename':
2468 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2469 case 'fullpagenamee':
2470 return $this->mTitle
->getPrefixedURL();
2472 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2473 case 'subpagenamee':
2474 return $this->mTitle
->getSubpageUrlForm();
2475 case 'basepagename':
2476 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2477 case 'basepagenamee':
2478 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2479 case 'talkpagename':
2480 if( $this->mTitle
->canTalk() ) {
2481 $talkPage = $this->mTitle
->getTalkPage();
2482 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2486 case 'talkpagenamee':
2487 if( $this->mTitle
->canTalk() ) {
2488 $talkPage = $this->mTitle
->getTalkPage();
2489 return $talkPage->getPrefixedUrl();
2493 case 'subjectpagename':
2494 $subjPage = $this->mTitle
->getSubjectPage();
2495 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2496 case 'subjectpagenamee':
2497 $subjPage = $this->mTitle
->getSubjectPage();
2498 return $subjPage->getPrefixedUrl();
2500 // Let the edit saving system know we should parse the page
2501 // *after* a revision ID has been assigned.
2502 $this->mOutput
->setFlag( 'vary-revision' );
2503 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2504 return $this->mRevisionId
;
2506 // Let the edit saving system know we should parse the page
2507 // *after* a revision ID has been assigned. This is for null edits.
2508 $this->mOutput
->setFlag( 'vary-revision' );
2509 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2510 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2511 case 'revisionday2':
2512 // Let the edit saving system know we should parse the page
2513 // *after* a revision ID has been assigned. This is for null edits.
2514 $this->mOutput
->setFlag( 'vary-revision' );
2515 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2516 return substr( $this->getRevisionTimestamp(), 6, 2 );
2517 case 'revisionmonth':
2518 // Let the edit saving system know we should parse the page
2519 // *after* a revision ID has been assigned. This is for null edits.
2520 $this->mOutput
->setFlag( 'vary-revision' );
2521 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2522 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2523 case 'revisionyear':
2524 // Let the edit saving system know we should parse the page
2525 // *after* a revision ID has been assigned. This is for null edits.
2526 $this->mOutput
->setFlag( 'vary-revision' );
2527 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2528 return substr( $this->getRevisionTimestamp(), 0, 4 );
2529 case 'revisiontimestamp':
2530 // Let the edit saving system know we should parse the page
2531 // *after* a revision ID has been assigned. This is for null edits.
2532 $this->mOutput
->setFlag( 'vary-revision' );
2533 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2534 return $this->getRevisionTimestamp();
2536 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2538 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2540 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2542 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2543 case 'subjectspace':
2544 return $this->mTitle
->getSubjectNsText();
2545 case 'subjectspacee':
2546 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2547 case 'currentdayname':
2548 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2550 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2552 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2554 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2556 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2557 // int to remove the padding
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2560 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2561 case 'localdayname':
2562 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2564 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2566 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2568 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2570 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2571 // int to remove the padding
2572 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2574 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2575 case 'numberofarticles':
2576 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2577 case 'numberoffiles':
2578 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2579 case 'numberofusers':
2580 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2581 case 'numberofpages':
2582 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2583 case 'numberofadmins':
2584 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2585 case 'numberofedits':
2586 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2587 case 'currenttimestamp':
2588 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2589 case 'localtimestamp':
2590 return $this->mVarCache
[$index] = $localTimestamp;
2591 case 'currentversion':
2592 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2598 return $wgServerName;
2600 return $wgScriptPath;
2601 case 'directionmark':
2602 return $wgContLang->getDirMark();
2603 case 'contentlanguage':
2604 global $wgContLanguageCode;
2605 return $wgContLanguageCode;
2608 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2616 * initialise the magic variables (like CURRENTMONTHNAME)
2620 function initialiseVariables() {
2621 wfProfileIn( __METHOD__
);
2622 $variableIDs = MagicWord
::getVariableIDs();
2624 $this->mVariables
= new MagicWordArray( $variableIDs );
2625 wfProfileOut( __METHOD__
);
2629 * Preprocess some wikitext and return the document tree.
2630 * This is the ghost of replace_variables().
2632 * @param string $text The text to parse
2633 * @param integer flags Bitwise combination of:
2634 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2635 * included. Default is to assume a direct page view.
2637 * The generated DOM tree must depend only on the input text and the flags.
2638 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2640 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2641 * change in the DOM tree for a given text, must be passed through the section identifier
2642 * in the section edit link and thus back to extractSections().
2644 * The output of this function is currently only cached in process memory, but a persistent
2645 * cache may be implemented at a later date which takes further advantage of these strict
2646 * dependency requirements.
2650 function preprocessToDom ( $text, $flags = 0 ) {
2651 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2656 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2658 public static function splitWhitespace( $s ) {
2659 $ltrimmed = ltrim( $s );
2660 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2661 $trimmed = rtrim( $ltrimmed );
2662 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2664 $w2 = substr( $ltrimmed, -$diff );
2668 return array( $w1, $trimmed, $w2 );
2672 * Replace magic variables, templates, and template arguments
2673 * with the appropriate text. Templates are substituted recursively,
2674 * taking care to avoid infinite loops.
2676 * Note that the substitution depends on value of $mOutputType:
2677 * self::OT_WIKI: only {{subst:}} templates
2678 * self::OT_PREPROCESS: templates but not extension tags
2679 * self::OT_HTML: all templates and extension tags
2681 * @param string $tex The text to transform
2682 * @param PPFrame $frame Object describing the arguments passed to the template.
2683 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2684 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2685 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2688 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2689 # Prevent too big inclusions
2690 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2694 wfProfileIn( __METHOD__
);
2696 if ( $frame === false ) {
2697 $frame = $this->getPreprocessor()->newFrame();
2698 } elseif ( !( $frame instanceof PPFrame
) ) {
2699 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2700 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2703 $dom = $this->preprocessToDom( $text );
2704 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2705 $text = $frame->expand( $dom, $flags );
2707 wfProfileOut( __METHOD__
);
2711 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2712 static function createAssocArgs( $args ) {
2713 $assocArgs = array();
2715 foreach( $args as $arg ) {
2716 $eqpos = strpos( $arg, '=' );
2717 if ( $eqpos === false ) {
2718 $assocArgs[$index++
] = $arg;
2720 $name = trim( substr( $arg, 0, $eqpos ) );
2721 $value = trim( substr( $arg, $eqpos+
1 ) );
2722 if ( $value === false ) {
2725 if ( $name !== false ) {
2726 $assocArgs[$name] = $value;
2735 * Warn the user when a parser limitation is reached
2736 * Will warn at most once the user per limitation type
2738 * @param string $limitationType, should be one of:
2739 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2740 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2741 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2742 * @params int $current, $max When an explicit limit has been
2743 * exceeded, provide the values (optional)
2745 function limitationWarn( $limitationType, $current=null, $max=null) {
2746 $msgName = $limitationType . '-warning';
2747 //does no harm if $current and $max are present but are unnecessary for the message
2748 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2749 $this->mOutput
->addWarning( $warning );
2750 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2752 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2757 * Return the text of a template, after recursively
2758 * replacing any variables or templates within the template.
2760 * @param array $piece The parts of the template
2761 * $piece['title']: the title, i.e. the part before the |
2762 * $piece['parts']: the parameter array
2763 * $piece['lineStart']: whether the brace was at the start of a line
2764 * @param PPFrame The current frame, contains template arguments
2765 * @return string the text of the template
2768 function braceSubstitution( $piece, $frame ) {
2769 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2770 wfProfileIn( __METHOD__
);
2771 wfProfileIn( __METHOD__
.'-setup' );
2774 $found = false; # $text has been filled
2775 $nowiki = false; # wiki markup in $text should be escaped
2776 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2777 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2778 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2779 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2781 # Title object, where $text came from
2784 # $part1 is the bit before the first |, and must contain only title characters.
2785 # Various prefixes will be stripped from it later.
2786 $titleWithSpaces = $frame->expand( $piece['title'] );
2787 $part1 = trim( $titleWithSpaces );
2790 # Original title text preserved for various purposes
2791 $originalTitle = $part1;
2793 # $args is a list of argument nodes, starting from index 0, not including $part1
2794 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2795 wfProfileOut( __METHOD__
.'-setup' );
2798 wfProfileIn( __METHOD__
.'-modifiers' );
2800 $mwSubst = MagicWord
::get( 'subst' );
2801 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2802 # One of two possibilities is true:
2803 # 1) Found SUBST but not in the PST phase
2804 # 2) Didn't find SUBST and in the PST phase
2805 # In either case, return without further processing
2806 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2813 if ( !$found && $args->getLength() == 0 ) {
2814 $id = $this->mVariables
->matchStartToEnd( $part1 );
2815 if ( $id !== false ) {
2816 $text = $this->getVariableValue( $id );
2817 if (MagicWord
::getCacheTTL($id)>-1)
2818 $this->mOutput
->mContainsOldMagic
= true;
2823 # MSG, MSGNW and RAW
2826 $mwMsgnw = MagicWord
::get( 'msgnw' );
2827 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2830 # Remove obsolete MSG:
2831 $mwMsg = MagicWord
::get( 'msg' );
2832 $mwMsg->matchStartAndRemove( $part1 );
2836 $mwRaw = MagicWord
::get( 'raw' );
2837 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2838 $forceRawInterwiki = true;
2841 wfProfileOut( __METHOD__
.'-modifiers' );
2845 wfProfileIn( __METHOD__
. '-pfunc' );
2847 $colonPos = strpos( $part1, ':' );
2848 if ( $colonPos !== false ) {
2849 # Case sensitive functions
2850 $function = substr( $part1, 0, $colonPos );
2851 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2852 $function = $this->mFunctionSynonyms
[1][$function];
2854 # Case insensitive functions
2855 $function = strtolower( $function );
2856 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2857 $function = $this->mFunctionSynonyms
[0][$function];
2863 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2864 $initialArgs = array( &$this );
2865 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2866 if ( $flags & SFH_OBJECT_ARGS
) {
2867 # Add a frame parameter, and pass the arguments as an array
2868 $allArgs = $initialArgs;
2869 $allArgs[] = $frame;
2870 for ( $i = 0; $i < $args->getLength(); $i++
) {
2871 $funcArgs[] = $args->item( $i );
2873 $allArgs[] = $funcArgs;
2875 # Convert arguments to plain text
2876 for ( $i = 0; $i < $args->getLength(); $i++
) {
2877 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2879 $allArgs = array_merge( $initialArgs, $funcArgs );
2882 # Workaround for PHP bug 35229 and similar
2883 if ( !is_callable( $callback ) ) {
2884 throw new MWException( "Tag hook for $function is not callable\n" );
2886 $result = call_user_func_array( $callback, $allArgs );
2889 $preprocessFlags = 0;
2891 if ( is_array( $result ) ) {
2892 if ( isset( $result[0] ) ) {
2894 unset( $result[0] );
2897 // Extract flags into the local scope
2898 // This allows callers to set flags such as nowiki, found, etc.
2904 $text = $this->preprocessToDom( $text, $preprocessFlags );
2909 wfProfileOut( __METHOD__
. '-pfunc' );
2912 # Finish mangling title and then check for loops.
2913 # Set $title to a Title object and $titleText to the PDBK
2916 # Split the title into page and subpage
2918 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2919 if ($subpage !== '') {
2920 $ns = $this->mTitle
->getNamespace();
2922 $title = Title
::newFromText( $part1, $ns );
2924 $titleText = $title->getPrefixedText();
2925 # Check for language variants if the template is not found
2926 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2927 $wgContLang->findVariantLink( $part1, $title, true );
2929 # Do infinite loop check
2930 if ( !$frame->loopCheck( $title ) ) {
2932 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2933 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2935 # Do recursion depth check
2936 $limit = $this->mOptions
->getMaxTemplateDepth();
2937 if ( $frame->depth
>= $limit ) {
2939 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2944 # Load from database
2945 if ( !$found && $title ) {
2946 wfProfileIn( __METHOD__
. '-loadtpl' );
2947 if ( !$title->isExternal() ) {
2948 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2949 $text = SpecialPage
::capturePath( $title );
2950 if ( is_string( $text ) ) {
2953 $this->disableCache();
2955 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2956 $found = false; //access denied
2957 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2959 list( $text, $title ) = $this->getTemplateDom( $title );
2960 if ( $text !== false ) {
2966 # If the title is valid but undisplayable, make a link to it
2967 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2968 $text = "[[:$titleText]]";
2971 } elseif ( $title->isTrans() ) {
2972 // Interwiki transclusion
2973 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2974 $text = $this->interwikiTransclude( $title, 'render' );
2977 $text = $this->interwikiTransclude( $title, 'raw' );
2978 // Preprocess it like a template
2979 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2984 wfProfileOut( __METHOD__
. '-loadtpl' );
2987 # If we haven't found text to substitute by now, we're done
2988 # Recover the source wikitext and return it
2990 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2991 wfProfileOut( __METHOD__
);
2992 return array( 'object' => $text );
2995 # Expand DOM-style return values in a child frame
2996 if ( $isChildObj ) {
2997 # Clean up argument array
2998 $newFrame = $frame->newChild( $args, $title );
3001 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3002 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3003 # Expansion is eligible for the empty-frame cache
3004 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3005 $text = $this->mTplExpandCache
[$titleText];
3007 $text = $newFrame->expand( $text );
3008 $this->mTplExpandCache
[$titleText] = $text;
3011 # Uncached expansion
3012 $text = $newFrame->expand( $text );
3015 if ( $isLocalObj && $nowiki ) {
3016 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3017 $isLocalObj = false;
3020 # Replace raw HTML by a placeholder
3021 # Add a blank line preceding, to prevent it from mucking up
3022 # immediately preceding headings
3024 $text = "\n\n" . $this->insertStripItem( $text );
3026 # Escape nowiki-style return values
3027 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3028 $text = wfEscapeWikiText( $text );
3030 # Bug 529: if the template begins with a table or block-level
3031 # element, it should be treated as beginning a new line.
3032 # This behaviour is somewhat controversial.
3033 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3034 $text = "\n" . $text;
3037 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3038 # Error, oversize inclusion
3039 $text = "[[$originalTitle]]" .
3040 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3041 $this->limitationWarn( 'post-expand-template-inclusion' );
3044 if ( $isLocalObj ) {
3045 $ret = array( 'object' => $text );
3047 $ret = array( 'text' => $text );
3050 wfProfileOut( __METHOD__
);
3055 * Get the semi-parsed DOM representation of a template with a given title,
3056 * and its redirect destination title. Cached.
3058 function getTemplateDom( $title ) {
3059 $cacheTitle = $title;
3060 $titleText = $title->getPrefixedDBkey();
3062 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3063 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3064 $title = Title
::makeTitle( $ns, $dbk );
3065 $titleText = $title->getPrefixedDBkey();
3067 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3068 return array( $this->mTplDomCache
[$titleText], $title );
3071 // Cache miss, go to the database
3072 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3074 if ( $text === false ) {
3075 $this->mTplDomCache
[$titleText] = false;
3076 return array( false, $title );
3079 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3080 $this->mTplDomCache
[ $titleText ] = $dom;
3082 if (! $title->equals($cacheTitle)) {
3083 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3084 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3087 return array( $dom, $title );
3091 * Fetch the unparsed text of a template and register a reference to it.
3093 function fetchTemplateAndTitle( $title ) {
3094 $templateCb = $this->mOptions
->getTemplateCallback();
3095 $stuff = call_user_func( $templateCb, $title, $this );
3096 $text = $stuff['text'];
3097 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3098 if ( isset( $stuff['deps'] ) ) {
3099 foreach ( $stuff['deps'] as $dep ) {
3100 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3103 return array($text,$finalTitle);
3106 function fetchTemplate( $title ) {
3107 $rv = $this->fetchTemplateAndTitle($title);
3112 * Static function to get a template
3113 * Can be overridden via ParserOptions::setTemplateCallback().
3115 static function statelessFetchTemplate( $title, $parser=false ) {
3116 $text = $skip = false;
3117 $finalTitle = $title;
3120 // Loop to fetch the article, with up to 1 redirect
3121 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3122 # Give extensions a chance to select the revision instead
3123 $id = false; // Assume current
3124 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3130 'page_id' => $title->getArticleID(),
3134 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3135 $rev_id = $rev ?
$rev->getId() : 0;
3136 // If there is no current revision, there is no page
3137 if( $id === false && !$rev ) {
3138 $linkCache = LinkCache
::singleton();
3139 $linkCache->addBadLinkObj( $title );
3144 'page_id' => $title->getArticleID(),
3145 'rev_id' => $rev_id );
3148 $text = $rev->getText();
3149 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3151 $message = $wgLang->lcfirst( $title->getText() );
3152 $text = wfMsgForContentNoTrans( $message );
3153 if( wfEmptyMsg( $message, $text ) ) {
3160 if ( $text === false ) {
3164 $finalTitle = $title;
3165 $title = Title
::newFromRedirect( $text );
3169 'finalTitle' => $finalTitle,
3174 * Transclude an interwiki link.
3176 function interwikiTransclude( $title, $action ) {
3177 global $wgEnableScaryTranscluding;
3179 if (!$wgEnableScaryTranscluding)
3180 return wfMsg('scarytranscludedisabled');
3182 $url = $title->getFullUrl( "action=$action" );
3184 if (strlen($url) > 255)
3185 return wfMsg('scarytranscludetoolong');
3186 return $this->fetchScaryTemplateMaybeFromCache($url);
3189 function fetchScaryTemplateMaybeFromCache($url) {
3190 global $wgTranscludeCacheExpiry;
3191 $dbr = wfGetDB(DB_SLAVE
);
3192 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3193 array('tc_url' => $url));
3195 $time = $obj->tc_time
;
3196 $text = $obj->tc_contents
;
3197 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3202 $text = Http
::get($url);
3204 return wfMsg('scarytranscludefailed', $url);
3206 $dbw = wfGetDB(DB_MASTER
);
3207 $dbw->replace('transcache', array('tc_url'), array(
3209 'tc_time' => time(),
3210 'tc_contents' => $text));
3216 * Triple brace replacement -- used for template arguments
3219 function argSubstitution( $piece, $frame ) {
3220 wfProfileIn( __METHOD__
);
3223 $parts = $piece['parts'];
3224 $nameWithSpaces = $frame->expand( $piece['title'] );
3225 $argName = trim( $nameWithSpaces );
3227 $text = $frame->getArgument( $argName );
3228 if ( $text === false && $parts->getLength() > 0
3232 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3235 # No match in frame, use the supplied default
3236 $object = $parts->item( 0 )->getChildren();
3238 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3239 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3240 $this->limitationWarn( 'post-expand-template-argument' );
3243 if ( $text === false && $object === false ) {
3245 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3247 if ( $error !== false ) {
3250 if ( $object !== false ) {
3251 $ret = array( 'object' => $object );
3253 $ret = array( 'text' => $text );
3256 wfProfileOut( __METHOD__
);
3261 * Return the text to be used for a given extension tag.
3262 * This is the ghost of strip().
3264 * @param array $params Associative array of parameters:
3265 * name PPNode for the tag name
3266 * attr PPNode for unparsed text where tag attributes are thought to be
3267 * attributes Optional associative array of parsed attributes
3268 * inner Contents of extension element
3269 * noClose Original text did not have a close tag
3270 * @param PPFrame $frame
3272 function extensionSubstitution( $params, $frame ) {
3273 global $wgRawHtml, $wgContLang;
3275 $name = $frame->expand( $params['name'] );
3276 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3277 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3279 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3281 if ( $this->ot
['html'] ) {
3282 $name = strtolower( $name );
3284 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3285 if ( isset( $params['attributes'] ) ) {
3286 $attributes = $attributes +
$params['attributes'];
3294 throw new MWException( '<html> extension tag encountered unexpectedly' );
3297 $output = Xml
::escapeTagsOnly( $content );
3300 $output = $wgContLang->armourMath(
3301 MathRenderer
::renderMath( $content, $attributes ) );
3304 $output = $this->renderImageGallery( $content, $attributes );
3307 if( isset( $this->mTagHooks
[$name] ) ) {
3308 # Workaround for PHP bug 35229 and similar
3309 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3310 throw new MWException( "Tag hook for $name is not callable\n" );
3312 $output = call_user_func_array( $this->mTagHooks
[$name],
3313 array( $content, $attributes, $this ) );
3315 $output = '<span class="error">Invalid tag extension name: ' .
3316 htmlspecialchars( $name ) . '</span>';
3320 if ( is_null( $attrText ) ) {
3323 if ( isset( $params['attributes'] ) ) {
3324 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3325 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3326 htmlspecialchars( $attrValue ) . '"';
3329 if ( $content === null ) {
3330 $output = "<$name$attrText/>";
3332 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3333 $output = "<$name$attrText>$content$close";
3337 if ( $name === 'html' ||
$name === 'nowiki' ) {
3338 $this->mStripState
->nowiki
->setPair( $marker, $output );
3340 $this->mStripState
->general
->setPair( $marker, $output );
3346 * Increment an include size counter
3348 * @param string $type The type of expansion
3349 * @param integer $size The size of the text
3350 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3352 function incrementIncludeSize( $type, $size ) {
3353 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3356 $this->mIncludeSizes
[$type] +
= $size;
3362 * Increment the expensive function count
3364 * @return boolean False if the limit has been exceeded
3366 function incrementExpensiveFunctionCount() {
3367 global $wgExpensiveParserFunctionLimit;
3368 $this->mExpensiveFunctionCount++
;
3369 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3376 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3377 * Fills $this->mDoubleUnderscores, returns the modified text
3379 function doDoubleUnderscore( $text ) {
3380 // The position of __TOC__ needs to be recorded
3381 $mw = MagicWord
::get( 'toc' );
3382 if( $mw->match( $text ) ) {
3383 $this->mShowToc
= true;
3384 $this->mForceTocPosition
= true;
3386 // Set a placeholder. At the end we'll fill it in with the TOC.
3387 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3389 // Only keep the first one.
3390 $text = $mw->replace( '', $text );
3393 // Now match and remove the rest of them
3394 $mwa = MagicWord
::getDoubleUnderscoreArray();
3395 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3397 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3398 $this->mOutput
->mNoGallery
= true;
3400 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3401 $this->mShowToc
= false;
3403 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3404 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3406 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3407 if ( $containerCategory ) {
3408 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3410 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3413 # (bug 8068) Allow control over whether robots index a page.
3415 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3416 # is not desirable, the last one on the page should win.
3417 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3418 $this->mOutput
->setIndexPolicy( 'noindex' );
3419 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3420 $this->mOutput
->setIndexPolicy( 'index' );
3427 * This function accomplishes several tasks:
3428 * 1) Auto-number headings if that option is enabled
3429 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3430 * 3) Add a Table of contents on the top for users who have enabled the option
3431 * 4) Auto-anchor headings
3433 * It loops through all headlines, collects the necessary data, then splits up the
3434 * string and re-inserts the newly formatted headlines.
3436 * @param string $text
3437 * @param boolean $isMain
3440 function formatHeadings( $text, $isMain=true ) {
3441 global $wgMaxTocLevel, $wgContLang;
3443 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3444 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3447 $showEditLink = $this->mOptions
->getEditSection();
3450 # Inhibit editsection links if requested in the page
3451 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3455 # Get all headlines for numbering them and adding funky stuff like [edit]
3456 # links - this is for later, but we need the number of headlines right now
3458 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3460 # if there are fewer than 4 headlines in the article, do not show TOC
3461 # unless it's been explicitly enabled.
3462 $enoughToc = $this->mShowToc
&&
3463 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3465 # Allow user to stipulate that a page should have a "new section"
3466 # link added via __NEWSECTIONLINK__
3467 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3468 $this->mOutput
->setNewSection( true );
3471 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3472 # override above conditions and always show TOC above first header
3473 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3474 $this->mShowToc
= true;
3478 # We need this to perform operations on the HTML
3479 $sk = $this->mOptions
->getSkin();
3485 # Ugh .. the TOC should have neat indentation levels which can be
3486 # passed to the skin functions. These are determined here
3490 $sublevelCount = array();
3491 $levelCount = array();
3497 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3498 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3501 foreach( $matches[3] as $headline ) {
3502 $isTemplate = false;
3504 $sectionIndex = false;
3506 $markerMatches = array();
3507 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3508 $serial = $markerMatches[1];
3509 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3510 $isTemplate = ($titleText != $baseTitleText);
3511 $headline = preg_replace("/^$markerRegex/", "", $headline);
3515 $prevlevel = $level;
3516 $prevtoclevel = $toclevel;
3518 $level = $matches[1][$headlineCount];
3520 if( $doNumberHeadings ||
$enoughToc ) {
3522 if ( $level > $prevlevel ) {
3523 # Increase TOC level
3525 $sublevelCount[$toclevel] = 0;
3526 if( $toclevel<$wgMaxTocLevel ) {
3527 $prevtoclevel = $toclevel;
3528 $toc .= $sk->tocIndent();
3532 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3533 # Decrease TOC level, find level to jump to
3535 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3536 # Can only go down to level 1
3539 for ($i = $toclevel; $i > 0; $i--) {
3540 if ( $levelCount[$i] == $level ) {
3541 # Found last matching level
3545 elseif ( $levelCount[$i] < $level ) {
3546 # Found first matching level below current level
3552 if( $toclevel<$wgMaxTocLevel ) {
3553 if($prevtoclevel < $wgMaxTocLevel) {
3554 # Unindent only if the previous toc level was shown :p
3555 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3556 $prevtoclevel = $toclevel;
3558 $toc .= $sk->tocLineEnd();
3563 # No change in level, end TOC line
3564 if( $toclevel<$wgMaxTocLevel ) {
3565 $toc .= $sk->tocLineEnd();
3569 $levelCount[$toclevel] = $level;
3571 # count number of headlines for each level
3572 @$sublevelCount[$toclevel]++
;
3574 for( $i = 1; $i <= $toclevel; $i++
) {
3575 if( !empty( $sublevelCount[$i] ) ) {
3579 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3585 # The safe header is a version of the header text safe to use for links
3586 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3587 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3589 # Remove link placeholders by the link text.
3590 # <!--LINK number-->
3592 # link text with suffix
3593 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3595 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3596 $tocline = preg_replace(
3597 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3601 $tocline = trim( $tocline );
3603 # For the anchor, strip out HTML-y stuff period
3604 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3605 $safeHeadline = trim( $safeHeadline );
3607 # Save headline for section edit hint before it's escaped
3608 $headlineHint = $safeHeadline;
3609 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3610 # HTML names must be case-insensitively unique (bug 10721)
3611 $arrayKey = strtolower( $safeHeadline );
3613 # count how many in assoc. array so we can track dupes in anchors
3614 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3615 $refcount[$headlineCount] = $refers[$arrayKey];
3617 # Don't number the heading if it is the only one (looks silly)
3618 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3619 # the two are different if the line contains a link
3620 $headline=$numbering . ' ' . $headline;
3623 # Create the anchor for linking from the TOC to the section
3624 $anchor = $safeHeadline;
3625 if($refcount[$headlineCount] > 1 ) {
3626 $anchor .= '_' . $refcount[$headlineCount];
3628 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3629 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3630 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3632 # give headline the correct <h#> tag
3633 if( $showEditLink && $sectionIndex !== false ) {
3635 # Put a T flag in the section identifier, to indicate to extractSections()
3636 # that sections inside <includeonly> should be counted.
3637 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3639 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3644 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3649 $this->mOutput
->setSections( $tocraw );
3651 # Never ever show TOC if no headers
3652 if( $numVisible < 1 ) {
3657 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3658 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3660 $toc = $sk->tocList( $toc );
3663 # split up and insert constructed headlines
3665 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3668 foreach( $blocks as $block ) {
3669 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3670 # This is the [edit] link that appears for the top block of text when
3671 # section editing is enabled
3673 # Disabled because it broke block formatting
3674 # For example, a bullet point in the top line
3675 # $full .= $sk->editSectionLink(0);
3678 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3679 # Top anchor now in skin
3683 if( !empty( $head[$i] ) ) {
3688 if( $this->mForceTocPosition
) {
3689 return str_replace( '<!--MWTOC-->', $toc, $full );
3696 * Transform wiki markup when saving a page by doing \r\n -> \n
3697 * conversion, substitting signatures, {{subst:}} templates, etc.
3699 * @param string $text the text to transform
3700 * @param Title &$title the Title object for the current article
3701 * @param User &$user the User object describing the current user
3702 * @param ParserOptions $options parsing options
3703 * @param bool $clearState whether to clear the parser state first
3704 * @return string the altered wiki markup
3707 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3708 $this->mOptions
= $options;
3709 $this->setTitle( $title );
3710 $this->setOutputType( self
::OT_WIKI
);
3712 if ( $clearState ) {
3713 $this->clearState();
3719 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3720 $text = $this->pstPass2( $text, $user );
3721 $text = $this->mStripState
->unstripBoth( $text );
3726 * Pre-save transform helper function
3729 function pstPass2( $text, $user ) {
3730 global $wgContLang, $wgLocaltimezone;
3732 /* Note: This is the timestamp saved as hardcoded wikitext to
3733 * the database, we use $wgContLang here in order to give
3734 * everyone the same signature and use the default one rather
3735 * than the one selected in each user's preferences.
3737 * (see also bug 12815)
3739 $ts = $this->mOptions
->getTimestamp();
3740 $tz = wfMsgForContent( 'timezone-utc' );
3741 if ( isset( $wgLocaltimezone ) ) {
3742 $unixts = wfTimestamp( TS_UNIX
, $ts );
3743 $oldtz = getenv( 'TZ' );
3744 putenv( 'TZ='.$wgLocaltimezone );
3745 $ts = date( 'YmdHis', $unixts );
3746 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3747 putenv( 'TZ='.$oldtz );
3750 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3752 # Variable replacement
3753 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3754 $text = $this->replaceVariables( $text );
3757 $sigText = $this->getUserSig( $user );
3758 $text = strtr( $text, array(
3760 '~~~~' => "$sigText $d",
3764 # Context links: [[|name]] and [[name (context)|]]
3766 global $wgLegalTitleChars;
3767 $tc = "[$wgLegalTitleChars]";
3768 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3770 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3771 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3772 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3773 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3775 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3776 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3777 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3778 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3780 $t = $this->mTitle
->getText();
3782 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3783 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3784 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3785 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3787 # if there's no context, don't bother duplicating the title
3788 $text = preg_replace( $p2, '[[\\1]]', $text );
3791 # Trim trailing whitespace
3792 $text = rtrim( $text );
3798 * Fetch the user's signature text, if any, and normalize to
3799 * validated, ready-to-insert wikitext.
3805 function getUserSig( &$user ) {
3806 global $wgMaxSigChars;
3808 $username = $user->getName();
3809 $nickname = $user->getOption( 'nickname' );
3810 $nickname = $nickname === '' ?
$username : $nickname;
3812 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3813 $nickname = $username;
3814 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3815 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3816 # Sig. might contain markup; validate this
3817 if( $this->validateSig( $nickname ) !== false ) {
3818 # Validated; clean up (if needed) and return it
3819 return $this->cleanSig( $nickname, true );
3821 # Failed to validate; fall back to the default
3822 $nickname = $username;
3823 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3827 // Make sure nickname doesnt get a sig in a sig
3828 $nickname = $this->cleanSigInSig( $nickname );
3830 # If we're still here, make it a link to the user page
3831 $userText = wfEscapeWikiText( $username );
3832 $nickText = wfEscapeWikiText( $nickname );
3833 if ( $user->isAnon() ) {
3834 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3836 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3841 * Check that the user's signature contains no bad XML
3843 * @param string $text
3844 * @return mixed An expanded string, or false if invalid.
3846 function validateSig( $text ) {
3847 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3851 * Clean up signature text
3853 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3854 * 2) Substitute all transclusions
3856 * @param string $text
3857 * @param $parsing Whether we're cleaning (preferences save) or parsing
3858 * @return string Signature text
3860 function cleanSig( $text, $parsing = false ) {
3863 $this->clearState();
3864 $this->setTitle( $wgTitle );
3865 $this->mOptions
= new ParserOptions
;
3866 $this->setOutputType
= self
::OT_PREPROCESS
;
3869 # Option to disable this feature
3870 if ( !$this->mOptions
->getCleanSignatures() ) {
3874 # FIXME: regex doesn't respect extension tags or nowiki
3875 # => Move this logic to braceSubstitution()
3876 $substWord = MagicWord
::get( 'subst' );
3877 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3878 $substText = '{{' . $substWord->getSynonym( 0 );
3880 $text = preg_replace( $substRegex, $substText, $text );
3881 $text = $this->cleanSigInSig( $text );
3882 $dom = $this->preprocessToDom( $text );
3883 $frame = $this->getPreprocessor()->newFrame();
3884 $text = $frame->expand( $dom );
3887 $text = $this->mStripState
->unstripBoth( $text );
3894 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3895 * @param string $text
3896 * @return string Signature text with /~{3,5}/ removed
3898 function cleanSigInSig( $text ) {
3899 $text = preg_replace( '/~{3,5}/', '', $text );
3904 * Set up some variables which are usually set up in parse()
3905 * so that an external function can call some class members with confidence
3908 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3909 $this->setTitle( $title );
3910 $this->mOptions
= $options;
3911 $this->setOutputType( $outputType );
3912 if ( $clearState ) {
3913 $this->clearState();
3918 * Wrapper for preprocess()
3920 * @param string $text the text to preprocess
3921 * @param ParserOptions $options options
3925 function transformMsg( $text, $options ) {
3927 static $executing = false;
3929 # Guard against infinite recursion
3935 wfProfileIn(__METHOD__
);
3936 $text = $this->preprocess( $text, $wgTitle, $options );
3939 wfProfileOut(__METHOD__
);
3944 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3945 * The callback should have the following form:
3946 * function myParserHook( $text, $params, &$parser ) { ... }
3948 * Transform and return $text. Use $parser for any required context, e.g. use
3949 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3953 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3954 * @param mixed $callback The callback function (and object) to use for the tag
3956 * @return The old value of the mTagHooks array associated with the hook
3958 function setHook( $tag, $callback ) {
3959 $tag = strtolower( $tag );
3960 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3961 $this->mTagHooks
[$tag] = $callback;
3962 if( !in_array( $tag, $this->mStripList
) ) {
3963 $this->mStripList
[] = $tag;
3969 function setTransparentTagHook( $tag, $callback ) {
3970 $tag = strtolower( $tag );
3971 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3972 $this->mTransparentTagHooks
[$tag] = $callback;
3978 * Remove all tag hooks
3980 function clearTagHooks() {
3981 $this->mTagHooks
= array();
3982 $this->mStripList
= $this->mDefaultStripList
;
3986 * Create a function, e.g. {{sum:1|2|3}}
3987 * The callback function should have the form:
3988 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3990 * Or with SFH_OBJECT_ARGS:
3991 * function myParserFunction( $parser, $frame, $args ) { ... }
3993 * The callback may either return the text result of the function, or an array with the text
3994 * in element 0, and a number of flags in the other elements. The names of the flags are
3995 * specified in the keys. Valid flags are:
3996 * found The text returned is valid, stop processing the template. This
3998 * nowiki Wiki markup in the return value should be escaped
3999 * isHTML The returned text is HTML, armour it against wikitext transformation
4003 * @param string $id The magic word ID
4004 * @param mixed $callback The callback function (and object) to use
4005 * @param integer $flags a combination of the following flags:
4006 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4008 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4009 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4010 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4011 * the arguments, and to control the way they are expanded.
4013 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4014 * arguments, for instance:
4015 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4017 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4018 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4019 * working if/when this is changed.
4021 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4024 * Please read the documentation in includes/parser/Preprocessor.php for more information
4025 * about the methods available in PPFrame and PPNode.
4027 * @return The old callback function for this name, if any
4029 function setFunctionHook( $id, $callback, $flags = 0 ) {
4030 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4031 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4033 # Add to function cache
4034 $mw = MagicWord
::get( $id );
4036 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4038 $synonyms = $mw->getSynonyms();
4039 $sensitive = intval( $mw->isCaseSensitive() );
4041 foreach ( $synonyms as $syn ) {
4043 if ( !$sensitive ) {
4044 $syn = strtolower( $syn );
4047 if ( !( $flags & SFH_NO_HASH
) ) {
4050 # Remove trailing colon
4051 if ( substr( $syn, -1, 1 ) === ':' ) {
4052 $syn = substr( $syn, 0, -1 );
4054 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4060 * Get all registered function hook identifiers
4064 function getFunctionHooks() {
4065 return array_keys( $this->mFunctionHooks
);
4069 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4070 * Placeholders created in Skin::makeLinkObj()
4071 * Returns an array of link CSS classes, indexed by PDBK.
4073 function replaceLinkHolders( &$text, $options = 0 ) {
4074 return $this->mLinkHolders
->replace( $text );
4078 * Replace <!--LINK--> link placeholders with plain text of links
4079 * (not HTML-formatted).
4080 * @param string $text
4083 function replaceLinkHoldersText( $text ) {
4084 return $this->mLinkHolders
->replaceText( $text );
4088 * Tag hook handler for 'pre'.
4090 function renderPreTag( $text, $attribs ) {
4091 // Backwards-compatibility hack
4092 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4094 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4095 return wfOpenElement( 'pre', $attribs ) .
4096 Xml
::escapeTagsOnly( $content ) .
4101 * Renders an image gallery from a text with one line per image.
4102 * text labels may be given by using |-style alternative text. E.g.
4103 * Image:one.jpg|The number "1"
4104 * Image:tree.jpg|A tree
4105 * given as text will return the HTML of a gallery with two images,
4106 * labeled 'The number "1"' and
4109 function renderImageGallery( $text, $params ) {
4110 $ig = new ImageGallery();
4111 $ig->setContextTitle( $this->mTitle
);
4112 $ig->setShowBytes( false );
4113 $ig->setShowFilename( false );
4114 $ig->setParser( $this );
4115 $ig->setHideBadImages();
4116 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4117 $ig->useSkin( $this->mOptions
->getSkin() );
4118 $ig->mRevisionId
= $this->mRevisionId
;
4120 if( isset( $params['caption'] ) ) {
4121 $caption = $params['caption'];
4122 $caption = htmlspecialchars( $caption );
4123 $caption = $this->replaceInternalLinks( $caption );
4124 $ig->setCaptionHtml( $caption );
4126 if( isset( $params['perrow'] ) ) {
4127 $ig->setPerRow( $params['perrow'] );
4129 if( isset( $params['widths'] ) ) {
4130 $ig->setWidths( $params['widths'] );
4132 if( isset( $params['heights'] ) ) {
4133 $ig->setHeights( $params['heights'] );
4136 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4138 $lines = StringUtils
::explode( "\n", $text );
4139 foreach ( $lines as $line ) {
4140 # match lines like these:
4141 # Image:someimage.jpg|This is some image
4143 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4145 if ( count( $matches ) == 0 ) {
4149 if ( strpos( $matches[0], '%' ) !== false )
4150 $matches[1] = urldecode( $matches[1] );
4151 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4153 if( is_null( $nt ) ) {
4154 # Bogus title. Ignore these so we don't bomb out later.
4157 if ( isset( $matches[3] ) ) {
4158 $label = $matches[3];
4163 $html = $this->recursiveTagParse( trim( $label ) );
4165 $ig->add( $nt, $html );
4167 # Only add real images (bug #5586)
4168 if ( $nt->getNamespace() == NS_IMAGE
) {
4169 $this->mOutput
->addImage( $nt->getDBkey() );
4172 return $ig->toHTML();
4175 function getImageParams( $handler ) {
4177 $handlerClass = get_class( $handler );
4181 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4182 // Initialise static lists
4183 static $internalParamNames = array(
4184 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4185 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4186 'bottom', 'text-bottom' ),
4187 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4188 'upright', 'border' ),
4190 static $internalParamMap;
4191 if ( !$internalParamMap ) {
4192 $internalParamMap = array();
4193 foreach ( $internalParamNames as $type => $names ) {
4194 foreach ( $names as $name ) {
4195 $magicName = str_replace( '-', '_', "img_$name" );
4196 $internalParamMap[$magicName] = array( $type, $name );
4201 // Add handler params
4202 $paramMap = $internalParamMap;
4204 $handlerParamMap = $handler->getParamMap();
4205 foreach ( $handlerParamMap as $magic => $paramName ) {
4206 $paramMap[$magic] = array( 'handler', $paramName );
4209 $this->mImageParams
[$handlerClass] = $paramMap;
4210 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4212 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4216 * Parse image options text and use it to make an image
4217 * @param Title $title
4218 * @param string $options
4219 * @param LinkHolderArray $holders
4221 function makeImage( $title, $options, $holders = false ) {
4222 # Check if the options text is of the form "options|alt text"
4224 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4225 # * left no resizing, just left align. label is used for alt= only
4226 # * right same, but right aligned
4227 # * none same, but not aligned
4228 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4229 # * center center the image
4230 # * framed Keep original image size, no magnify-button.
4231 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4232 # * upright reduce width for upright images, rounded to full __0 px
4233 # * border draw a 1px border around the image
4234 # vertical-align values (no % or length right now):
4244 $parts = StringUtils
::explode( "|", $options );
4245 $sk = $this->mOptions
->getSkin();
4247 # Give extensions a chance to select the file revision for us
4248 $skip = $time = $descQuery = false;
4249 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4252 return $sk->link( $title );
4256 $file = wfFindFile( $title, $time );
4257 $handler = $file ?
$file->getHandler() : false;
4259 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4261 # Process the input parameters
4263 $params = array( 'frame' => array(), 'handler' => array(),
4264 'horizAlign' => array(), 'vertAlign' => array() );
4265 foreach( $parts as $part ) {
4266 $part = trim( $part );
4267 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4269 if( isset( $paramMap[$magicName] ) ) {
4270 list( $type, $paramName ) = $paramMap[$magicName];
4272 // Special case; width and height come in one variable together
4273 if( $type === 'handler' && $paramName === 'width' ) {
4275 # (bug 13500) In both cases (width/height and width only),
4276 # permit trailing "px" for backward compatibility.
4277 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4278 $width = intval( $m[1] );
4279 $height = intval( $m[2] );
4280 if ( $handler->validateParam( 'width', $width ) ) {
4281 $params[$type]['width'] = $width;
4284 if ( $handler->validateParam( 'height', $height ) ) {
4285 $params[$type]['height'] = $height;
4288 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4289 $width = intval( $value );
4290 if ( $handler->validateParam( 'width', $width ) ) {
4291 $params[$type]['width'] = $width;
4294 } // else no validation -- bug 13436
4296 if ( $type === 'handler' ) {
4297 # Validate handler parameter
4298 $validated = $handler->validateParam( $paramName, $value );
4300 # Validate internal parameters
4301 switch( $paramName ) {
4303 /// @fixme - possibly check validity here?
4304 /// downstream behavior seems odd with missing manual thumbs.
4308 // Most other things appear to be empty or numeric...
4309 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4314 $params[$type][$paramName] = $value;
4318 if ( !$validated ) {
4323 # Process alignment parameters
4324 if ( $params['horizAlign'] ) {
4325 $params['frame']['align'] = key( $params['horizAlign'] );
4327 if ( $params['vertAlign'] ) {
4328 $params['frame']['valign'] = key( $params['vertAlign'] );
4331 # Strip bad stuff out of the alt text
4332 # We can't just use replaceLinkHoldersText() here, because if this function
4333 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4335 $alt = $holders->replaceText( $caption );
4337 $alt = $this->replaceLinkHoldersText( $caption );
4340 # make sure there are no placeholders in thumbnail attributes
4341 # that are later expanded to html- so expand them now and
4343 $alt = $this->mStripState
->unstripBoth( $alt );
4344 $alt = Sanitizer
::stripAllTags( $alt );
4346 $params['frame']['alt'] = $alt;
4347 $params['frame']['caption'] = $caption;
4349 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4351 # Linker does the rest
4352 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4354 # Give the handler a chance to modify the parser object
4356 $handler->parserTransformHook( $this, $file );
4363 * Set a flag in the output object indicating that the content is dynamic and
4364 * shouldn't be cached.
4366 function disableCache() {
4367 wfDebug( "Parser output marked as uncacheable.\n" );
4368 $this->mOutput
->mCacheTime
= -1;
4372 * Callback from the Sanitizer for expanding items found in HTML attribute
4373 * values, so they can be safely tested and escaped.
4374 * @param string $text
4375 * @param PPFrame $frame
4379 function attributeStripCallback( &$text, $frame = false ) {
4380 $text = $this->replaceVariables( $text, $frame );
4381 $text = $this->mStripState
->unstripBoth( $text );
4390 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4391 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4392 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4398 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4403 * Break wikitext input into sections, and either pull or replace
4404 * some particular section's text.
4406 * External callers should use the getSection and replaceSection methods.
4408 * @param string $text Page wikitext
4409 * @param string $section A section identifier string of the form:
4410 * <flag1> - <flag2> - ... - <section number>
4412 * Currently the only recognised flag is "T", which means the target section number
4413 * was derived during a template inclusion parse, in other words this is a template
4414 * section edit link. If no flags are given, it was an ordinary section edit link.
4415 * This flag is required to avoid a section numbering mismatch when a section is
4416 * enclosed by <includeonly> (bug 6563).
4418 * The section number 0 pulls the text before the first heading; other numbers will
4419 * pull the given section along with its lower-level subsections. If the section is
4420 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4422 * @param string $mode One of "get" or "replace"
4423 * @param string $newText Replacement text for section data.
4424 * @return string for "get", the extracted section text.
4425 * for "replace", the whole page with the section replaced.
4427 private function extractSections( $text, $section, $mode, $newText='' ) {
4429 $this->clearState();
4430 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4431 $this->mOptions
= new ParserOptions
;
4432 $this->setOutputType( self
::OT_WIKI
);
4434 $frame = $this->getPreprocessor()->newFrame();
4436 // Process section extraction flags
4438 $sectionParts = explode( '-', $section );
4439 $sectionIndex = array_pop( $sectionParts );
4440 foreach ( $sectionParts as $part ) {
4441 if ( $part === 'T' ) {
4442 $flags |
= self
::PTD_FOR_INCLUSION
;
4445 // Preprocess the text
4446 $root = $this->preprocessToDom( $text, $flags );
4448 // <h> nodes indicate section breaks
4449 // They can only occur at the top level, so we can find them by iterating the root's children
4450 $node = $root->getFirstChild();
4452 // Find the target section
4453 if ( $sectionIndex == 0 ) {
4454 // Section zero doesn't nest, level=big
4455 $targetLevel = 1000;
4458 if ( $node->getName() === 'h' ) {
4459 $bits = $node->splitHeading();
4460 if ( $bits['i'] == $sectionIndex ) {
4461 $targetLevel = $bits['level'];
4465 if ( $mode === 'replace' ) {
4466 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4468 $node = $node->getNextSibling();
4474 if ( $mode === 'get' ) {
4481 // Find the end of the section, including nested sections
4483 if ( $node->getName() === 'h' ) {
4484 $bits = $node->splitHeading();
4485 $curLevel = $bits['level'];
4486 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4490 if ( $mode === 'get' ) {
4491 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4493 $node = $node->getNextSibling();
4496 // Write out the remainder (in replace mode only)
4497 if ( $mode === 'replace' ) {
4498 // Output the replacement text
4499 // Add two newlines on -- trailing whitespace in $newText is conventionally
4500 // stripped by the editor, so we need both newlines to restore the paragraph gap
4501 $outText .= $newText . "\n\n";
4503 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4504 $node = $node->getNextSibling();
4508 if ( is_string( $outText ) ) {
4509 // Re-insert stripped tags
4510 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4517 * This function returns the text of a section, specified by a number ($section).
4518 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4519 * the first section before any such heading (section 0).
4521 * If a section contains subsections, these are also returned.
4523 * @param string $text text to look in
4524 * @param string $section section identifier
4525 * @param string $deftext default to return if section is not found
4526 * @return string text of the requested section
4528 public function getSection( $text, $section, $deftext='' ) {
4529 return $this->extractSections( $text, $section, "get", $deftext );
4532 public function replaceSection( $oldtext, $section, $text ) {
4533 return $this->extractSections( $oldtext, $section, "replace", $text );
4537 * Get the timestamp associated with the current revision, adjusted for
4538 * the default server-local timestamp
4540 function getRevisionTimestamp() {
4541 if ( is_null( $this->mRevisionTimestamp
) ) {
4542 wfProfileIn( __METHOD__
);
4544 $dbr = wfGetDB( DB_SLAVE
);
4545 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4546 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4548 // Normalize timestamp to internal MW format for timezone processing.
4549 // This has the added side-effect of replacing a null value with
4550 // the current time, which gives us more sensible behavior for
4552 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4554 // The cryptic '' timezone parameter tells to use the site-default
4555 // timezone offset instead of the user settings.
4557 // Since this value will be saved into the parser cache, served
4558 // to other users, and potentially even used inside links and such,
4559 // it needs to be consistent for all visitors.
4560 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4562 wfProfileOut( __METHOD__
);
4564 return $this->mRevisionTimestamp
;
4568 * Mutator for $mDefaultSort
4570 * @param $sort New value
4572 public function setDefaultSort( $sort ) {
4573 $this->mDefaultSort
= $sort;
4577 * Accessor for $mDefaultSort
4578 * Will use the title/prefixed title if none is set
4582 public function getDefaultSort() {
4583 global $wgCategoryPrefixedDefaultSortkey;
4584 if( $this->mDefaultSort
!== false ) {
4585 return $this->mDefaultSort
;
4586 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4587 !$wgCategoryPrefixedDefaultSortkey) {
4588 return $this->mTitle
->getText();
4590 return $this->mTitle
->getPrefixedText();
4595 * Try to guess the section anchor name based on a wikitext fragment
4596 * presumably extracted from a heading, for example "Header" from
4599 public function guessSectionNameFromWikiText( $text ) {
4600 # Strip out wikitext links(they break the anchor)
4601 $text = $this->stripSectionName( $text );
4602 $headline = Sanitizer
::decodeCharReferences( $text );
4604 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4605 $headline = trim( $headline );
4606 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4607 $replacearray = array(
4612 array_keys( $replacearray ),
4613 array_values( $replacearray ),
4618 * Strips a text string of wikitext for use in a section anchor
4620 * Accepts a text string and then removes all wikitext from the
4621 * string and leaves only the resultant text (i.e. the result of
4622 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4623 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4624 * to create valid section anchors by mimicing the output of the
4625 * parser when headings are parsed.
4627 * @param $text string Text string to be stripped of wikitext
4628 * for use in a Section anchor
4629 * @return Filtered text string
4631 public function stripSectionName( $text ) {
4632 # Strip internal link markup
4633 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4634 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4636 # Strip external link markup (FIXME: Not Tolerant to blank link text
4637 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4638 # on how many empty links there are on the page - need to figure that out.
4639 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4641 # Parse wikitext quotes (italics & bold)
4642 $text = $this->doQuotes($text);
4645 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4649 function srvus( $text ) {
4650 return $this->testSrvus( $text, $this->mOutputType
);
4654 * strip/replaceVariables/unstrip for preprocessor regression testing
4656 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4657 $this->clearState();
4658 if ( ! ( $title instanceof Title
) ) {
4659 $title = Title
::newFromText( $title );
4661 $this->mTitle
= $title;
4662 $this->mOptions
= $options;
4663 $this->setOutputType( $outputType );
4664 $text = $this->replaceVariables( $text );
4665 $text = $this->mStripState
->unstripBoth( $text );
4666 $text = Sanitizer
::removeHTMLtags( $text );
4670 function testPst( $text, $title, $options ) {
4672 if ( ! ( $title instanceof Title
) ) {
4673 $title = Title
::newFromText( $title );
4675 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4678 function testPreprocess( $text, $title, $options ) {
4679 if ( ! ( $title instanceof Title
) ) {
4680 $title = Title
::newFromText( $title );
4682 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4685 function markerSkipCallback( $s, $callback ) {
4688 while ( $i < strlen( $s ) ) {
4689 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4690 if ( $markerStart === false ) {
4691 $out .= call_user_func( $callback, substr( $s, $i ) );
4694 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4695 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4696 if ( $markerEnd === false ) {
4697 $out .= substr( $s, $markerStart );
4700 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4701 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4711 * @todo document, briefly.
4715 var $general, $nowiki;
4717 function __construct() {
4718 $this->general
= new ReplacementArray
;
4719 $this->nowiki
= new ReplacementArray
;
4722 function unstripGeneral( $text ) {
4723 wfProfileIn( __METHOD__
);
4726 $text = $this->general
->replace( $text );
4727 } while ( $text !== $oldText );
4728 wfProfileOut( __METHOD__
);
4732 function unstripNoWiki( $text ) {
4733 wfProfileIn( __METHOD__
);
4736 $text = $this->nowiki
->replace( $text );
4737 } while ( $text !== $oldText );
4738 wfProfileOut( __METHOD__
);
4742 function unstripBoth( $text ) {
4743 wfProfileIn( __METHOD__
);
4746 $text = $this->general
->replace( $text );
4747 $text = $this->nowiki
->replace( $text );
4748 } while ( $text !== $oldText );
4749 wfProfileOut( __METHOD__
);
4755 * @todo document, briefly.
4758 class OnlyIncludeReplacer
{
4761 function replace( $matches ) {
4762 if ( substr( $matches[1], -1 ) === "\n" ) {
4763 $this->output
.= substr( $matches[1], 0, -1 );
4765 $this->output
.= $matches[1];