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, $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->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
133 $this->mVarCache
= array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass
= $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'dom' ) ) {
137 $this->mPreprocessorClass
= 'Preprocessor_DOM';
139 $this->mPreprocessorClass
= 'Preprocessor_Hash';
141 $this->mMarkerIndex
= 0;
142 $this->mFirstCall
= true;
146 * Do various kinds of initialisation on the first call of the parser
148 function firstCallInit() {
149 if ( !$this->mFirstCall
) {
152 $this->mFirstCall
= false;
154 wfProfileIn( __METHOD__
);
156 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
157 CoreParserFunctions
::register( $this );
158 $this->initialiseVariables();
160 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
161 wfProfileOut( __METHOD__
);
169 function clearState() {
170 wfProfileIn( __METHOD__
);
171 if ( $this->mFirstCall
) {
172 $this->firstCallInit();
174 $this->mOutput
= new ParserOutput
;
175 $this->mAutonumber
= 0;
176 $this->mLastSection
= '';
177 $this->mDTopen
= false;
178 $this->mIncludeCount
= array();
179 $this->mStripState
= new StripState
;
180 $this->mArgStack
= false;
181 $this->mInPre
= false;
182 $this->mLinkHolders
= new LinkHolderArray( $this );
184 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
187 * Prefix for temporary replacement strings for the multipass parser.
188 * \x07 should never appear in input as it's disallowed in XML.
189 * Using it at the front also gives us a little extra robustness
190 * since it shouldn't match when butted up against identifier-like
193 * Must not consist of all title characters, or else it will change
194 * the behaviour of <nowiki> in a link.
196 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
197 # Changed to \x7f to allow XML double-parsing -- TS
198 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
201 # Clear these on every parse, bug 4549
202 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
204 $this->mShowToc
= true;
205 $this->mForceTocPosition
= false;
206 $this->mIncludeSizes
= array(
210 $this->mPPNodeCount
= 0;
211 $this->mDefaultSort
= false;
212 $this->mHeadings
= array();
213 $this->mDoubleUnderscores
= array();
214 $this->mExpensiveFunctionCount
= 0;
217 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
218 $this->mPreprocessor
= null;
221 wfRunHooks( 'ParserClearState', array( &$this ) );
222 wfProfileOut( __METHOD__
);
225 function setOutputType( $ot ) {
226 $this->mOutputType
= $ot;
229 'html' => $ot == self
::OT_HTML
,
230 'wiki' => $ot == self
::OT_WIKI
,
231 'pre' => $ot == self
::OT_PREPROCESS
,
236 * Set the context title
238 function setTitle( $t ) {
239 if ( !$t ||
$t instanceof FakeTitle
) {
240 $t = Title
::newFromText( 'NO TITLE' );
242 if ( strval( $t->getFragment() ) !== '' ) {
243 # Strip the fragment to avoid various odd effects
244 $this->mTitle
= clone $t;
245 $this->mTitle
->setFragment( '' );
252 * Accessor for mUniqPrefix.
256 function uniqPrefix() {
257 if( !isset( $this->mUniqPrefix
) ) {
258 // @fixme this is probably *horribly wrong*
259 // LanguageConverter seems to want $wgParser's uniqPrefix, however
260 // if this is called for a parser cache hit, the parser may not
261 // have ever been initialized in the first place.
262 // Not really sure what the heck is supposed to be going on here.
264 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
266 return $this->mUniqPrefix
;
270 * Convert wikitext to HTML
271 * Do not call this function recursively.
273 * @param $text String: text we want to parse
274 * @param $title A title object
275 * @param $options ParserOptions
276 * @param $linestart boolean
277 * @param $clearState boolean
278 * @param $revid Int: number to pass in {{REVISIONID}}
279 * @return ParserOutput a ParserOutput
281 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
283 * First pass--just handle <nowiki> sections, pass the rest off
284 * to internalParse() which does all the real work.
287 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
288 $fname = __METHOD__
.'-' . wfGetCaller();
289 wfProfileIn( __METHOD__
);
290 wfProfileIn( $fname );
296 $this->mOptions
= $options;
297 $this->setTitle( $title );
298 $oldRevisionId = $this->mRevisionId
;
299 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
300 if( $revid !== null ) {
301 $this->mRevisionId
= $revid;
302 $this->mRevisionTimestamp
= null;
304 $this->setOutputType( self
::OT_HTML
);
305 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
307 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
308 $text = $this->internalParse( $text );
309 $text = $this->mStripState
->unstripGeneral( $text );
311 # Clean up special characters, only run once, next-to-last before doBlockLevels
313 # french spaces, last one Guillemet-left
314 # only if there is something before the space
315 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
316 # french spaces, Guillemet-right
317 '/(\\302\\253) /' => '\\1 ',
318 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
320 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
322 $text = $this->doBlockLevels( $text, $linestart );
324 $this->replaceLinkHolders( $text );
326 # the position of the parserConvert() call should not be changed. it
327 # assumes that the links are all replaced and the only thing left
328 # is the <nowiki> mark.
329 # Side-effects: this calls $this->mOutput->setTitleText()
330 $text = $wgContLang->parserConvert( $text, $this );
332 $text = $this->mStripState
->unstripNoWiki( $text );
334 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
336 //!JF Move to its own function
338 $uniq_prefix = $this->mUniqPrefix
;
340 $elements = array_keys( $this->mTransparentTagHooks
);
341 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
343 foreach( $matches as $marker => $data ) {
344 list( $element, $content, $params, $tag ) = $data;
345 $tagName = strtolower( $element );
346 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
347 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
348 array( $content, $params, $this ) );
352 $this->mStripState
->general
->setPair( $marker, $output );
354 $text = $this->mStripState
->unstripGeneral( $text );
356 $text = Sanitizer
::normalizeCharReferences( $text );
358 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
359 $text = self
::tidy($text);
361 # attempt to sanitize at least some nesting problems
362 # (bug #2702 and quite a few others)
364 # ''Something [http://www.cool.com cool''] -->
365 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
366 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
367 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
368 # fix up an anchor inside another anchor, only
369 # at least for a single single nested link (bug 3695)
370 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
371 '\\1\\2</a>\\3</a>\\1\\4</a>',
372 # fix div inside inline elements- doBlockLevels won't wrap a line which
373 # contains a div, so fix it up here; replace
374 # div with escaped text
375 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
376 '\\1\\3<div\\5>\\6</div>\\8\\9',
377 # remove empty italic or bold tag pairs, some
378 # introduced by rules above
379 '/<([bi])><\/\\1>/' => '',
382 $text = preg_replace(
383 array_keys( $tidyregs ),
384 array_values( $tidyregs ),
387 global $wgExpensiveParserFunctionLimit;
388 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
389 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
392 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
394 # Information on include size limits, for the benefit of users who try to skirt them
395 if ( $this->mOptions
->getEnableLimitReport() ) {
396 global $wgExpensiveParserFunctionLimit;
397 $max = $this->mOptions
->getMaxIncludeSize();
398 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
400 "NewPP limit report\n" .
401 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
402 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
403 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
405 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
406 $text .= "\n<!-- \n$limitReport-->\n";
408 $this->mOutput
->setText( $text );
409 $this->mRevisionId
= $oldRevisionId;
410 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
411 wfProfileOut( $fname );
412 wfProfileOut( __METHOD__
);
414 return $this->mOutput
;
418 * Recursive parser entry point that can be called from an extension tag
421 function recursiveTagParse( $text ) {
422 wfProfileIn( __METHOD__
);
423 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
424 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
425 $text = $this->internalParse( $text );
426 wfProfileOut( __METHOD__
);
431 * Expand templates and variables in the text, producing valid, static wikitext.
432 * Also removes comments.
434 function preprocess( $text, $title, $options, $revid = null ) {
435 wfProfileIn( __METHOD__
);
437 $this->setOutputType( self
::OT_PREPROCESS
);
438 $this->mOptions
= $options;
439 $this->setTitle( $title );
440 if( $revid !== null ) {
441 $this->mRevisionId
= $revid;
443 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
444 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
445 $text = $this->replaceVariables( $text );
446 $text = $this->mStripState
->unstripBoth( $text );
447 wfProfileOut( __METHOD__
);
452 * Get a random string
457 function getRandomString() {
458 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
461 function &getTitle() { return $this->mTitle
; }
462 function getOptions() { return $this->mOptions
; }
463 function getRevisionId() { return $this->mRevisionId
; }
464 function getOutput() { return $this->mOutput
; }
465 function nextLinkID() { return $this->mLinkID++
; }
467 function getFunctionLang() {
468 global $wgLang, $wgContLang;
470 $target = $this->mOptions
->getTargetLanguage();
471 if ( $target !== null ) {
474 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
479 * Get a preprocessor object
481 function getPreprocessor() {
482 if ( !isset( $this->mPreprocessor
) ) {
483 $class = $this->mPreprocessorClass
;
484 $this->mPreprocessor
= new $class( $this );
486 return $this->mPreprocessor
;
490 * Replaces all occurrences of HTML-style comments and the given tags
491 * in the text with a random marker and returns the next text. The output
492 * parameter $matches will be an associative array filled with data in
494 * 'UNIQ-xxxxx' => array(
497 * array( 'param' => 'x' ),
498 * '<element param="x">tag content</element>' ) )
500 * @param $elements list of element names. Comments are always extracted.
501 * @param $text Source text string.
502 * @param $uniq_prefix
507 static function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
512 $taglist = implode( '|', $elements );
513 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
515 while ( '' != $text ) {
516 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
518 if( count( $p ) < 5 ) {
521 if( count( $p ) > 5 ) {
535 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
536 $stripped .= $marker;
538 if ( $close === '/>' ) {
539 // Empty element tag, <tag />
544 if( $element === '!--' ) {
547 $end = "/(<\\/$element\\s*>)/i";
549 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
551 if( count( $q ) < 3 ) {
552 # No end tag -- let it run out to the end of the text.
561 $matches[$marker] = array( $element,
563 Sanitizer
::decodeTagAttributes( $attributes ),
564 "<$element$attributes$close$content$tail" );
570 * Get a list of strippable XML-like elements
572 function getStripList() {
574 $elements = $this->mStripList
;
576 $elements[] = 'html';
578 if( $this->mOptions
->getUseTeX() ) {
579 $elements[] = 'math';
585 * @deprecated use replaceVariables
587 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
592 * Restores pre, math, and other extensions removed by strip()
594 * always call unstripNoWiki() after this one
596 * @deprecated use $this->mStripState->unstrip()
598 function unstrip( $text, $state ) {
599 return $state->unstripGeneral( $text );
603 * Always call this after unstrip() to preserve the order
606 * @deprecated use $this->mStripState->unstrip()
608 function unstripNoWiki( $text, $state ) {
609 return $state->unstripNoWiki( $text );
613 * @deprecated use $this->mStripState->unstripBoth()
615 function unstripForHTML( $text ) {
616 return $this->mStripState
->unstripBoth( $text );
620 * Add an item to the strip state
621 * Returns the unique tag which must be inserted into the stripped text
622 * The tag will be replaced with the original text in unstrip()
626 function insertStripItem( $text ) {
627 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
628 $this->mMarkerIndex++
;
629 $this->mStripState
->general
->setPair( $rnd, $text );
634 * Interface with html tidy, used if $wgUseTidy = true.
635 * If tidy isn't able to correct the markup, the original will be
636 * returned in all its glory with a warning comment appended.
638 * Either the external tidy program or the in-process tidy extension
639 * will be used depending on availability. Override the default
640 * $wgTidyInternal setting to disable the internal if it's not working.
642 * @param string $text Hideous HTML input
643 * @return string Corrected HTML output
647 static function tidy( $text ) {
648 global $wgTidyInternal;
649 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
650 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
651 '<head><title>test</title></head><body>'.$text.'</body></html>';
652 if( $wgTidyInternal ) {
653 $correctedtext = self
::internalTidy( $wrappedtext );
655 $correctedtext = self
::externalTidy( $wrappedtext );
657 if( is_null( $correctedtext ) ) {
658 wfDebug( "Tidy error detected!\n" );
659 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
661 return $correctedtext;
665 * Spawn an external HTML tidy process and get corrected markup back from it.
670 static function externalTidy( $text ) {
671 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
672 wfProfileIn( __METHOD__
);
677 $descriptorspec = array(
678 0 => array('pipe', 'r'),
679 1 => array('pipe', 'w'),
680 2 => array('file', wfGetNull(), 'a')
683 if( function_exists('proc_open') ) {
684 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
685 if (is_resource($process)) {
686 // Theoretically, this style of communication could cause a deadlock
687 // here. If the stdout buffer fills up, then writes to stdin could
688 // block. This doesn't appear to happen with tidy, because tidy only
689 // writes to stdout after it's finished reading from stdin. Search
690 // for tidyParseStdin and tidySaveStdout in console/tidy.c
691 fwrite($pipes[0], $text);
693 while (!feof($pipes[1])) {
694 $cleansource .= fgets($pipes[1], 1024);
697 proc_close($process);
701 wfProfileOut( __METHOD__
);
703 if( $cleansource == '' && $text != '') {
704 // Some kind of error happened, so we couldn't get the corrected text.
705 // Just give up; we'll use the source text and append a warning.
713 * Use the HTML tidy PECL extension to use the tidy library in-process,
714 * saving the overhead of spawning a new process.
716 * 'pear install tidy' should be able to compile the extension module.
721 static function internalTidy( $text ) {
722 global $wgTidyConf, $IP, $wgDebugTidy;
723 wfProfileIn( __METHOD__
);
726 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
727 $tidy->cleanRepair();
728 if( $tidy->getStatus() == 2 ) {
729 // 2 is magic number for fatal error
730 // http://www.php.net/manual/en/function.tidy-get-status.php
733 $cleansource = tidy_get_output( $tidy );
735 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
736 $cleansource .= "<!--\nTidy reports:\n" .
737 str_replace( '-->', '-->', $tidy->errorBuffer
) .
741 wfProfileOut( __METHOD__
);
746 * parse the wiki syntax used to render tables
750 function doTableStuff ( $text ) {
751 wfProfileIn( __METHOD__
);
753 $lines = StringUtils
::explode( "\n", $text );
755 $td_history = array (); // Is currently a td tag open?
756 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
757 $tr_history = array (); // Is currently a tr tag open?
758 $tr_attributes = array (); // history of tr attributes
759 $has_opened_tr = array(); // Did this table open a <tr> element?
760 $indent_level = 0; // indent level of the table
762 foreach ( $lines as $outLine ) {
763 $line = trim( $outLine );
765 if( $line == '' ) { // empty line, go to next line
769 $first_character = $line[0];
772 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
773 // First check if we are starting a new table
774 $indent_level = strlen( $matches[1] );
776 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
777 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
779 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
780 array_push ( $td_history , false );
781 array_push ( $last_tag_history , '' );
782 array_push ( $tr_history , false );
783 array_push ( $tr_attributes , '' );
784 array_push ( $has_opened_tr , false );
785 } else if ( count ( $td_history ) == 0 ) {
786 // Don't do any of the following
787 $out .= $outLine."\n";
789 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
790 // We are ending a table
791 $line = '</table>' . substr ( $line , 2 );
792 $last_tag = array_pop ( $last_tag_history );
794 if ( !array_pop ( $has_opened_tr ) ) {
795 $line = "<tr><td></td></tr>{$line}";
798 if ( array_pop ( $tr_history ) ) {
799 $line = "</tr>{$line}";
802 if ( array_pop ( $td_history ) ) {
803 $line = "</{$last_tag}>{$line}";
805 array_pop ( $tr_attributes );
806 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
807 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
808 // Now we have a table row
809 $line = preg_replace( '#^\|-+#', '', $line );
811 // Whats after the tag is now only attributes
812 $attributes = $this->mStripState
->unstripBoth( $line );
813 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
814 array_pop ( $tr_attributes );
815 array_push ( $tr_attributes , $attributes );
818 $last_tag = array_pop ( $last_tag_history );
819 array_pop ( $has_opened_tr );
820 array_push ( $has_opened_tr , true );
822 if ( array_pop ( $tr_history ) ) {
826 if ( array_pop ( $td_history ) ) {
827 $line = "</{$last_tag}>{$line}";
831 array_push ( $tr_history , false );
832 array_push ( $td_history , false );
833 array_push ( $last_tag_history , '' );
835 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
836 // This might be cell elements, td, th or captions
837 if ( substr ( $line , 0 , 2 ) === '|+' ) {
838 $first_character = '+';
839 $line = substr ( $line , 1 );
842 $line = substr ( $line , 1 );
844 if ( $first_character === '!' ) {
845 $line = str_replace ( '!!' , '||' , $line );
848 // Split up multiple cells on the same line.
849 // FIXME : This can result in improper nesting of tags processed
850 // by earlier parser steps, but should avoid splitting up eg
851 // attribute values containing literal "||".
852 $cells = StringUtils
::explodeMarkup( '||' , $line );
856 // Loop through each table cell
857 foreach ( $cells as $cell )
860 if ( $first_character !== '+' )
862 $tr_after = array_pop ( $tr_attributes );
863 if ( !array_pop ( $tr_history ) ) {
864 $previous = "<tr{$tr_after}>\n";
866 array_push ( $tr_history , true );
867 array_push ( $tr_attributes , '' );
868 array_pop ( $has_opened_tr );
869 array_push ( $has_opened_tr , true );
872 $last_tag = array_pop ( $last_tag_history );
874 if ( array_pop ( $td_history ) ) {
875 $previous = "</{$last_tag}>{$previous}";
878 if ( $first_character === '|' ) {
880 } else if ( $first_character === '!' ) {
882 } else if ( $first_character === '+' ) {
883 $last_tag = 'caption';
888 array_push ( $last_tag_history , $last_tag );
890 // A cell could contain both parameters and data
891 $cell_data = explode ( '|' , $cell , 2 );
893 // Bug 553: Note that a '|' inside an invalid link should not
894 // be mistaken as delimiting cell parameters
895 if ( strpos( $cell_data[0], '[[' ) !== false ) {
896 $cell = "{$previous}<{$last_tag}>{$cell}";
897 } else if ( count ( $cell_data ) == 1 )
898 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
900 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
901 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
902 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
906 array_push ( $td_history , true );
909 $out .= $outLine . "\n";
912 // Closing open td, tr && table
913 while ( count ( $td_history ) > 0 )
915 if ( array_pop ( $td_history ) ) {
918 if ( array_pop ( $tr_history ) ) {
921 if ( !array_pop ( $has_opened_tr ) ) {
922 $out .= "<tr><td></td></tr>\n" ;
925 $out .= "</table>\n";
928 // Remove trailing line-ending (b/c)
929 if ( substr( $out, -1 ) === "\n" ) {
930 $out = substr( $out, 0, -1 );
933 // special case: don't return empty table
934 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
938 wfProfileOut( __METHOD__
);
944 * Helper function for parse() that transforms wiki markup into
945 * HTML. Only called for $mOutputType == self::OT_HTML.
949 function internalParse( $text ) {
951 wfProfileIn( __METHOD__
);
953 # Hook to suspend the parser in this state
954 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
955 wfProfileOut( __METHOD__
);
959 $text = $this->replaceVariables( $text );
960 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
961 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
963 // Tables need to come after variable replacement for things to work
964 // properly; putting them before other transformations should keep
965 // exciting things like link expansions from showing up in surprising
967 $text = $this->doTableStuff( $text );
969 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
971 $text = $this->doDoubleUnderscore( $text );
972 $text = $this->doHeadings( $text );
973 if($this->mOptions
->getUseDynamicDates()) {
974 $df = DateFormatter
::getInstance();
975 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
977 $text = $this->doAllQuotes( $text );
978 $text = $this->replaceInternalLinks( $text );
979 $text = $this->replaceExternalLinks( $text );
981 # replaceInternalLinks may sometimes leave behind
982 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
983 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
985 $text = $this->doMagicLinks( $text );
986 $text = $this->formatHeadings( $text, $isMain );
988 wfProfileOut( __METHOD__
);
993 * Replace special strings like "ISBN xxx" and "RFC xxx" with
994 * magic external links.
998 function doMagicLinks( $text ) {
999 wfProfileIn( __METHOD__
);
1000 $text = preg_replace_callback(
1002 <a.*?</a> | # Skip link text
1003 <.*?> | # Skip stuff inside HTML elements
1004 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1005 ISBN\s+(\b # ISBN, capture number as m[2]
1006 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1007 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1008 [0-9Xx] # check digit
1010 )!x', array( &$this, 'magicLinkCallback' ), $text );
1011 wfProfileOut( __METHOD__
);
1015 function magicLinkCallback( $m ) {
1016 if ( substr( $m[0], 0, 1 ) === '<' ) {
1019 } elseif ( substr( $m[0], 0, 4 ) === 'ISBN' ) {
1021 $num = strtr( $isbn, array(
1026 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1027 $text = '<a href="' .
1028 $titleObj->escapeLocalUrl() .
1029 "\" class=\"internal\">ISBN $isbn</a>";
1031 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1035 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1037 $urlmsg = 'pubmedurl';
1040 throw new MWException( __METHOD__
.': unrecognised match type "' .
1041 substr($m[0], 0, 20 ) . '"' );
1044 $url = wfMsg( $urlmsg, $id);
1045 $sk = $this->mOptions
->getSkin();
1046 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1047 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1053 * Parse headers and return html
1057 static function doHeadings( $text ) {
1058 wfProfileIn( __METHOD__
);
1059 for ( $i = 6; $i >= 1; --$i ) {
1060 $h = str_repeat( '=', $i );
1061 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1062 "<h$i>\\1</h$i>", $text );
1064 wfProfileOut( __METHOD__
);
1069 * Replace single quotes with HTML markup
1071 * @return string the altered text
1073 static function doAllQuotes( $text ) {
1074 wfProfileIn( __METHOD__
);
1076 $lines = StringUtils
::explode( "\n", $text );
1077 foreach ( $lines as $line ) {
1078 $outtext .= self
::doQuotes( $line ) . "\n";
1080 $outtext = substr($outtext, 0,-1);
1081 wfProfileOut( __METHOD__
);
1086 * Helper function for doAllQuotes()
1088 public static function doQuotes( $text ) {
1089 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1090 if ( count( $arr ) == 1 )
1094 # First, do some preliminary work. This may shift some apostrophes from
1095 # being mark-up to being text. It also counts the number of occurrences
1096 # of bold and italics mark-ups.
1100 foreach ( $arr as $r )
1102 if ( ( $i %
2 ) == 1 )
1104 # If there are ever four apostrophes, assume the first is supposed to
1105 # be text, and the remaining three constitute mark-up for bold text.
1106 if ( strlen( $arr[$i] ) == 4 )
1111 # If there are more than 5 apostrophes in a row, assume they're all
1112 # text except for the last 5.
1113 else if ( strlen( $arr[$i] ) > 5 )
1115 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1118 # Count the number of occurrences of bold and italics mark-ups.
1119 # We are not counting sequences of five apostrophes.
1120 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1121 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1122 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1127 # If there is an odd number of both bold and italics, it is likely
1128 # that one of the bold ones was meant to be an apostrophe followed
1129 # by italics. Which one we cannot know for certain, but it is more
1130 # likely to be one that has a single-letter word before it.
1131 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1134 $firstsingleletterword = -1;
1135 $firstmultiletterword = -1;
1137 foreach ( $arr as $r )
1139 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1141 $x1 = substr ($arr[$i-1], -1);
1142 $x2 = substr ($arr[$i-1], -2, 1);
1144 if ($firstspace == -1) $firstspace = $i;
1145 } else if ($x2 === ' ') {
1146 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1148 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1154 # If there is a single-letter word, use it!
1155 if ($firstsingleletterword > -1)
1157 $arr [ $firstsingleletterword ] = "''";
1158 $arr [ $firstsingleletterword-1 ] .= "'";
1160 # If not, but there's a multi-letter word, use that one.
1161 else if ($firstmultiletterword > -1)
1163 $arr [ $firstmultiletterword ] = "''";
1164 $arr [ $firstmultiletterword-1 ] .= "'";
1166 # ... otherwise use the first one that has neither.
1167 # (notice that it is possible for all three to be -1 if, for example,
1168 # there is only one pentuple-apostrophe in the line)
1169 else if ($firstspace > -1)
1171 $arr [ $firstspace ] = "''";
1172 $arr [ $firstspace-1 ] .= "'";
1176 # Now let's actually convert our apostrophic mush to HTML!
1181 foreach ($arr as $r)
1185 if ($state === 'both')
1192 if (strlen ($r) == 2)
1195 { $output .= '</i>'; $state = ''; }
1196 else if ($state === 'bi')
1197 { $output .= '</i>'; $state = 'b'; }
1198 else if ($state === 'ib')
1199 { $output .= '</b></i><b>'; $state = 'b'; }
1200 else if ($state === 'both')
1201 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1202 else # $state can be 'b' or ''
1203 { $output .= '<i>'; $state .= 'i'; }
1205 else if (strlen ($r) == 3)
1208 { $output .= '</b>'; $state = ''; }
1209 else if ($state === 'bi')
1210 { $output .= '</i></b><i>'; $state = 'i'; }
1211 else if ($state === 'ib')
1212 { $output .= '</b>'; $state = 'i'; }
1213 else if ($state === 'both')
1214 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1215 else # $state can be 'i' or ''
1216 { $output .= '<b>'; $state .= 'b'; }
1218 else if (strlen ($r) == 5)
1221 { $output .= '</b><i>'; $state = 'i'; }
1222 else if ($state === 'i')
1223 { $output .= '</i><b>'; $state = 'b'; }
1224 else if ($state === 'bi')
1225 { $output .= '</i></b>'; $state = ''; }
1226 else if ($state === 'ib')
1227 { $output .= '</b></i>'; $state = ''; }
1228 else if ($state === 'both')
1229 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1230 else # ($state == '')
1231 { $buffer = ''; $state = 'both'; }
1236 # Now close all remaining tags. Notice that the order is important.
1237 if ($state === 'b' ||
$state === 'ib')
1239 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1241 if ($state === 'bi')
1243 # There might be lonely ''''', so make sure we have a buffer
1244 if ($state === 'both' && $buffer)
1245 $output .= '<b><i>'.$buffer.'</i></b>';
1251 * Replace external links
1253 * Note: this is all very hackish and the order of execution matters a lot.
1254 * Make sure to run maintenance/parserTests.php if you change this code.
1258 function replaceExternalLinks( $text ) {
1260 wfProfileIn( __METHOD__
);
1262 $sk = $this->mOptions
->getSkin();
1264 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1266 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1269 while ( $i<count( $bits ) ) {
1271 $protocol = $bits[$i++
];
1272 $text = $bits[$i++
];
1273 $trail = $bits[$i++
];
1275 # The characters '<' and '>' (which were escaped by
1276 # removeHTMLtags()) should not be included in
1277 # URLs, per RFC 2396.
1279 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1280 $text = substr($url, $m2[0][1]) . ' ' . $text;
1281 $url = substr($url, 0, $m2[0][1]);
1284 # If the link text is an image URL, replace it with an <img> tag
1285 # This happened by accident in the original parser, but some people used it extensively
1286 $img = $this->maybeMakeExternalImage( $text );
1287 if ( $img !== false ) {
1293 # Set linktype for CSS - if URL==text, link is essentially free
1294 $linktype = ($text === $url) ?
'free' : 'text';
1296 # No link text, e.g. [http://domain.tld/some.link]
1297 if ( $text == '' ) {
1298 # Autonumber if allowed. See bug #5918
1299 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1300 $text = '[' . ++
$this->mAutonumber
. ']';
1301 $linktype = 'autonumber';
1303 # Otherwise just use the URL
1304 $text = htmlspecialchars( $url );
1308 # Have link text, e.g. [http://domain.tld/some.link text]s
1310 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1313 $text = $wgContLang->markNoConversion($text);
1315 $url = Sanitizer
::cleanUrl( $url );
1317 # Process the trail (i.e. everything after this link up until start of the next link),
1318 # replacing any non-bracketed links
1319 $trail = $this->replaceFreeExternalLinks( $trail );
1321 # Use the encoded URL
1322 # This means that users can paste URLs directly into the text
1323 # Funny characters like ö aren't valid in URLs anyway
1324 # This was changed in August 2004
1325 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1327 # Register link in the output object.
1328 # Replace unnecessary URL escape codes with the referenced character
1329 # This prevents spammers from hiding links from the filters
1330 $pasteurized = self
::replaceUnusualEscapes( $url );
1331 $this->mOutput
->addExternalLink( $pasteurized );
1334 wfProfileOut( __METHOD__
);
1339 * Replace anything that looks like a URL with a link
1342 function replaceFreeExternalLinks( $text ) {
1344 wfProfileIn( __METHOD__
);
1346 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1347 $s = array_shift( $bits );
1350 $sk = $this->mOptions
->getSkin();
1352 while ( $i < count( $bits ) ){
1353 $protocol = $bits[$i++
];
1354 $remainder = $bits[$i++
];
1357 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1358 # Found some characters after the protocol that look promising
1359 $url = $protocol . $m[1];
1362 # special case: handle urls as url args:
1363 # http://www.example.com/foo?=http://www.example.com/bar
1364 if(strlen($trail) == 0 &&
1366 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1367 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1370 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1375 # The characters '<' and '>' (which were escaped by
1376 # removeHTMLtags()) should not be included in
1377 # URLs, per RFC 2396.
1379 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1380 $trail = substr($url, $m2[0][1]) . $trail;
1381 $url = substr($url, 0, $m2[0][1]);
1384 # Move trailing punctuation to $trail
1386 # If there is no left bracket, then consider right brackets fair game too
1387 if ( strpos( $url, '(' ) === false ) {
1391 $numSepChars = strspn( strrev( $url ), $sep );
1392 if ( $numSepChars ) {
1393 $trail = substr( $url, -$numSepChars ) . $trail;
1394 $url = substr( $url, 0, -$numSepChars );
1397 $url = Sanitizer
::cleanUrl( $url );
1399 # Is this an external image?
1400 $text = $this->maybeMakeExternalImage( $url );
1401 if ( $text === false ) {
1402 # Not an image, make a link
1403 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1404 # Register it in the output object...
1405 # Replace unnecessary URL escape codes with their equivalent characters
1406 $pasteurized = self
::replaceUnusualEscapes( $url );
1407 $this->mOutput
->addExternalLink( $pasteurized );
1409 $s .= $text . $trail;
1411 $s .= $protocol . $remainder;
1414 wfProfileOut( __METHOD__
);
1419 * Replace unusual URL escape codes with their equivalent characters
1423 * @todo This can merge genuinely required bits in the path or query string,
1424 * breaking legit URLs. A proper fix would treat the various parts of
1425 * the URL differently; as a workaround, just use the output for
1426 * statistical records, not for actual linking/output.
1428 static function replaceUnusualEscapes( $url ) {
1429 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1430 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1434 * Callback function used in replaceUnusualEscapes().
1435 * Replaces unusual URL escape codes with their equivalent character
1439 private static function replaceUnusualEscapesCallback( $matches ) {
1440 $char = urldecode( $matches[0] );
1441 $ord = ord( $char );
1442 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1443 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1444 // No, shouldn't be escaped
1447 // Yes, leave it escaped
1453 * make an image if it's allowed, either through the global
1454 * option or through the exception
1457 function maybeMakeExternalImage( $url ) {
1458 $sk = $this->mOptions
->getSkin();
1459 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1460 $imagesexception = !empty($imagesfrom);
1462 if ( $this->mOptions
->getAllowExternalImages()
1463 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1464 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1466 $text = $sk->makeExternalImage( $url );
1473 * Process [[ ]] wikilinks
1474 * @return processed text
1478 function replaceInternalLinks( $s ) {
1479 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1484 * Process [[ ]] wikilinks
1485 * @return LinkHolderArray
1489 function replaceInternalLinks2( &$s ) {
1492 wfProfileIn( __METHOD__
);
1494 wfProfileIn( __METHOD__
.'-setup' );
1495 static $tc = FALSE, $e1, $e1_img;
1496 # the % is needed to support urlencoded titles as well
1498 $tc = Title
::legalChars() . '#%';
1499 # Match a link having the form [[namespace:link|alternate]]trail
1500 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1501 # Match cases where there is no "]]", which might still be images
1502 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1505 $sk = $this->mOptions
->getSkin();
1506 $holders = new LinkHolderArray( $this );
1508 #split the entire text string on occurences of [[
1509 $a = StringUtils
::explode( '[[', ' ' . $s );
1510 #get the first element (all text up to first [[), and remove the space we added
1513 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1514 $s = substr( $s, 1 );
1516 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1518 if ( $useLinkPrefixExtension ) {
1519 # Match the end of a line for a word that's not followed by whitespace,
1520 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1521 $e2 = wfMsgForContent( 'linkprefix' );
1524 if( is_null( $this->mTitle
) ) {
1525 wfProfileOut( __METHOD__
.'-setup' );
1526 wfProfileOut( __METHOD__
);
1527 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1529 $nottalk = !$this->mTitle
->isTalkPage();
1531 if ( $useLinkPrefixExtension ) {
1533 if ( preg_match( $e2, $s, $m ) ) {
1534 $first_prefix = $m[2];
1536 $first_prefix = false;
1542 if($wgContLang->hasVariants()) {
1543 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1545 $selflink = array($this->mTitle
->getPrefixedText());
1547 $useSubpages = $this->areSubpagesAllowed();
1548 wfProfileOut( __METHOD__
.'-setup' );
1550 # Loop for each link
1551 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1552 # Check for excessive memory usage
1553 if ( $holders->isBig() ) {
1555 # Do the existence check, replace the link holders and clear the array
1556 $holders->replace( $s );
1560 if ( $useLinkPrefixExtension ) {
1561 wfProfileIn( __METHOD__
.'-prefixhandling' );
1562 if ( preg_match( $e2, $s, $m ) ) {
1570 $prefix = $first_prefix;
1571 $first_prefix = false;
1573 wfProfileOut( __METHOD__
.'-prefixhandling' );
1576 $might_be_img = false;
1578 wfProfileIn( __METHOD__
."-e1" );
1579 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1581 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1582 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1583 # the real problem is with the $e1 regex
1586 # Still some problems for cases where the ] is meant to be outside punctuation,
1587 # and no image is in sight. See bug 2095.
1590 substr( $m[3], 0, 1 ) === ']' &&
1591 strpos($text, '[') !== false
1594 $text .= ']'; # so that replaceExternalLinks($text) works later
1595 $m[3] = substr( $m[3], 1 );
1597 # fix up urlencoded title texts
1598 if( strpos( $m[1], '%' ) !== false ) {
1599 # Should anchors '#' also be rejected?
1600 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1603 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1604 $might_be_img = true;
1606 if ( strpos( $m[1], '%' ) !== false ) {
1607 $m[1] = urldecode($m[1]);
1610 } else { # Invalid form; output directly
1611 $s .= $prefix . '[[' . $line ;
1612 wfProfileOut( __METHOD__
."-e1" );
1615 wfProfileOut( __METHOD__
."-e1" );
1616 wfProfileIn( __METHOD__
."-misc" );
1618 # Don't allow internal links to pages containing
1619 # PROTO: where PROTO is a valid URL protocol; these
1620 # should be external links.
1621 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1622 $s .= $prefix . '[[' . $line ;
1623 wfProfileOut( __METHOD__
."-misc" );
1627 # Make subpage if necessary
1628 if( $useSubpages ) {
1629 $link = $this->maybeDoSubpageLink( $m[1], $text );
1634 $noforce = (substr($m[1], 0, 1) !== ':');
1636 # Strip off leading ':'
1637 $link = substr($link, 1);
1640 wfProfileOut( __METHOD__
."-misc" );
1641 wfProfileIn( __METHOD__
."-title" );
1642 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1644 $s .= $prefix . '[[' . $line;
1645 wfProfileOut( __METHOD__
."-title" );
1649 $ns = $nt->getNamespace();
1650 $iw = $nt->getInterWiki();
1651 wfProfileOut( __METHOD__
."-title" );
1653 if ($might_be_img) { # if this is actually an invalid link
1654 wfProfileIn( __METHOD__
."-might_be_img" );
1655 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1658 #look at the next 'line' to see if we can close it there
1660 $next_line = $a->current();
1661 if ( $next_line === false ||
$next_line === null ) {
1664 $m = explode( ']]', $next_line, 3 );
1665 if ( count( $m ) == 3 ) {
1666 # the first ]] closes the inner link, the second the image
1668 $text .= "[[{$m[0]}]]{$m[1]}";
1671 } elseif ( count( $m ) == 2 ) {
1672 #if there's exactly one ]] that's fine, we'll keep looking
1673 $text .= "[[{$m[0]}]]{$m[1]}";
1675 #if $next_line is invalid too, we need look no further
1676 $text .= '[[' . $next_line;
1681 # we couldn't find the end of this imageLink, so output it raw
1682 #but don't ignore what might be perfectly normal links in the text we've examined
1683 $holders->merge( $this->replaceInternalLinks2( $text ) );
1684 $s .= "{$prefix}[[$link|$text";
1685 # note: no $trail, because without an end, there *is* no trail
1686 wfProfileOut( __METHOD__
."-might_be_img" );
1689 } else { #it's not an image, so output it raw
1690 $s .= "{$prefix}[[$link|$text";
1691 # note: no $trail, because without an end, there *is* no trail
1692 wfProfileOut( __METHOD__
."-might_be_img" );
1695 wfProfileOut( __METHOD__
."-might_be_img" );
1698 $wasblank = ( '' == $text );
1699 if( $wasblank ) $text = $link;
1701 # Link not escaped by : , create the various objects
1705 wfProfileIn( __METHOD__
."-interwiki" );
1706 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1707 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1708 $s = rtrim($s . $prefix);
1709 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1710 wfProfileOut( __METHOD__
."-interwiki" );
1713 wfProfileOut( __METHOD__
."-interwiki" );
1715 if ( $ns == NS_IMAGE
) {
1716 wfProfileIn( __METHOD__
."-image" );
1717 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1718 # recursively parse links inside the image caption
1719 # actually, this will parse them in any other parameters, too,
1720 # but it might be hard to fix that, and it doesn't matter ATM
1721 $text = $this->replaceExternalLinks($text);
1722 $holders->merge( $this->replaceInternalLinks2( $text ) );
1724 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1725 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1727 $this->mOutput
->addImage( $nt->getDBkey() );
1728 wfProfileOut( __METHOD__
."-image" );
1733 if ( $ns == NS_CATEGORY
) {
1734 wfProfileIn( __METHOD__
."-category" );
1735 $s = rtrim($s . "\n"); # bug 87
1738 $sortkey = $this->getDefaultSort();
1742 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1743 $sortkey = str_replace( "\n", '', $sortkey );
1744 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1745 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1748 * Strip the whitespace Category links produce, see bug 87
1749 * @todo We might want to use trim($tmp, "\n") here.
1751 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1753 wfProfileOut( __METHOD__
."-category" );
1758 # Self-link checking
1759 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1760 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1761 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1766 # Special and Media are pseudo-namespaces; no pages actually exist in them
1767 if( $ns == NS_MEDIA
) {
1768 # Give extensions a chance to select the file revision for us
1769 $skip = $time = false;
1770 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1772 $link = $sk->link( $nt );
1774 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1776 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1777 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1778 $this->mOutput
->addImage( $nt->getDBkey() );
1780 } elseif( $ns == NS_SPECIAL
) {
1781 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1782 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1784 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1787 } elseif( $ns == NS_IMAGE
) {
1788 $img = wfFindFile( $nt );
1790 // Force a blue link if the file exists; may be a remote
1791 // upload on the shared repository, and we want to see its
1792 // auto-generated page.
1793 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1794 $this->mOutput
->addLink( $nt );
1798 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1800 wfProfileOut( __METHOD__
);
1805 * Make a link placeholder. The text returned can be later resolved to a real link with
1806 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1807 * parsing of interwiki links, and secondly to allow all existence checks and
1808 * article length checks (for stub links) to be bundled into a single query.
1812 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1813 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1817 * Render a forced-blue link inline; protect against double expansion of
1818 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1819 * Since this little disaster has to split off the trail text to avoid
1820 * breaking URLs in the following text without breaking trails on the
1821 * wiki links, it's been made into a horrible function.
1824 * @param string $text
1825 * @param string $query
1826 * @param string $trail
1827 * @param string $prefix
1828 * @return string HTML-wikitext mix oh yuck
1830 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1831 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1832 $sk = $this->mOptions
->getSkin();
1833 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1834 return $this->armorLinks( $link ) . $trail;
1838 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1839 * going to go through further parsing steps before inline URL expansion.
1841 * In particular this is important when using action=render, which causes
1842 * full URLs to be included.
1844 * Oh man I hate our multi-layer parser!
1846 * @param string more-or-less HTML
1847 * @return string less-or-more HTML with NOPARSE bits
1849 function armorLinks( $text ) {
1850 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1851 "{$this->mUniqPrefix}NOPARSE$1", $text );
1855 * Return true if subpage links should be expanded on this page.
1858 function areSubpagesAllowed() {
1859 # Some namespaces don't allow subpages
1860 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1864 * Handle link to subpage if necessary
1865 * @param string $target the source of the link
1866 * @param string &$text the link text, modified as necessary
1867 * @return string the full name of the link
1870 function maybeDoSubpageLink($target, &$text) {
1873 # :Foobar -- override special treatment of prefix (images, language links)
1874 # /Foobar -- convert to CurrentPage/Foobar
1875 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1876 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1877 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1879 wfProfileIn( __METHOD__
);
1880 $ret = $target; # default return value is no change
1882 # Some namespaces don't allow subpages,
1883 # so only perform processing if subpages are allowed
1884 if( $this->areSubpagesAllowed() ) {
1885 $hash = strpos( $target, '#' );
1886 if( $hash !== false ) {
1887 $suffix = substr( $target, $hash );
1888 $target = substr( $target, 0, $hash );
1893 $target = trim( $target );
1894 # Look at the first character
1895 if( $target != '' && $target{0} === '/' ) {
1896 # / at end means we don't want the slash to be shown
1898 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1899 if( $trailingSlashes ) {
1900 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1902 $noslash = substr( $target, 1 );
1905 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1906 if( '' === $text ) {
1907 $text = $target . $suffix;
1908 } # this might be changed for ugliness reasons
1910 # check for .. subpage backlinks
1912 $nodotdot = $target;
1913 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1915 $nodotdot = substr( $nodotdot, 3 );
1917 if($dotdotcount > 0) {
1918 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1919 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1920 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1921 # / at the end means don't show full path
1922 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1923 $nodotdot = substr( $nodotdot, 0, -1 );
1924 if( '' === $text ) {
1925 $text = $nodotdot . $suffix;
1928 $nodotdot = trim( $nodotdot );
1929 if( $nodotdot != '' ) {
1930 $ret .= '/' . $nodotdot;
1938 wfProfileOut( __METHOD__
);
1943 * Used by doBlockLevels()
1946 /* private */ function closeParagraph() {
1948 if ( '' != $this->mLastSection
) {
1949 $result = '</' . $this->mLastSection
. ">\n";
1951 $this->mInPre
= false;
1952 $this->mLastSection
= '';
1955 # getCommon() returns the length of the longest common substring
1956 # of both arguments, starting at the beginning of both.
1958 /* private */ static function getCommon( $st1, $st2 ) {
1959 $fl = strlen( $st1 );
1960 $shorter = strlen( $st2 );
1961 if ( $fl < $shorter ) { $shorter = $fl; }
1963 for ( $i = 0; $i < $shorter; ++
$i ) {
1964 if ( $st1{$i} != $st2{$i} ) { break; }
1968 # These next three functions open, continue, and close the list
1969 # element appropriate to the prefix character passed into them.
1971 /* private */ function openList( $char ) {
1972 $result = $this->closeParagraph();
1974 if ( '*' === $char ) { $result .= '<ul><li>'; }
1975 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1976 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1977 else if ( ';' === $char ) {
1978 $result .= '<dl><dt>';
1979 $this->mDTopen
= true;
1981 else { $result = '<!-- ERR 1 -->'; }
1986 /* private */ function nextItem( $char ) {
1987 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1988 else if ( ':' === $char ||
';' === $char ) {
1990 if ( $this->mDTopen
) { $close = '</dt>'; }
1991 if ( ';' === $char ) {
1992 $this->mDTopen
= true;
1993 return $close . '<dt>';
1995 $this->mDTopen
= false;
1996 return $close . '<dd>';
1999 return '<!-- ERR 2 -->';
2002 /* private */ function closeList( $char ) {
2003 if ( '*' === $char ) { $text = '</li></ul>'; }
2004 else if ( '#' === $char ) { $text = '</li></ol>'; }
2005 else if ( ':' === $char ) {
2006 if ( $this->mDTopen
) {
2007 $this->mDTopen
= false;
2008 $text = '</dt></dl>';
2010 $text = '</dd></dl>';
2013 else { return '<!-- ERR 3 -->'; }
2019 * Make lists from lines starting with ':', '*', '#', etc.
2022 * @return string the lists rendered as HTML
2024 function doBlockLevels( $text, $linestart ) {
2025 wfProfileIn( __METHOD__
);
2027 # Parsing through the text line by line. The main thing
2028 # happening here is handling of block-level elements p, pre,
2029 # and making lists from lines starting with * # : etc.
2031 $textLines = StringUtils
::explode( "\n", $text );
2033 $lastPrefix = $output = '';
2034 $this->mDTopen
= $inBlockElem = false;
2036 $paragraphStack = false;
2038 foreach ( $textLines as $oLine ) {
2040 if ( !$linestart ) {
2046 $lastPrefixLength = strlen( $lastPrefix );
2047 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2048 $preOpenMatch = preg_match('/<pre/i', $oLine );
2049 if ( !$this->mInPre
) {
2050 # Multiple prefixes may abut each other for nested lists.
2051 $prefixLength = strspn( $oLine, '*#:;' );
2052 $prefix = substr( $oLine, 0, $prefixLength );
2055 $prefix2 = str_replace( ';', ':', $prefix );
2056 $t = substr( $oLine, $prefixLength );
2057 $this->mInPre
= (bool)$preOpenMatch;
2059 # Don't interpret any other prefixes in preformatted text
2061 $prefix = $prefix2 = '';
2066 if( $prefixLength && $lastPrefix === $prefix2 ) {
2067 # Same as the last item, so no need to deal with nesting or opening stuff
2068 $output .= $this->nextItem( substr( $prefix, -1 ) );
2069 $paragraphStack = false;
2071 if ( substr( $prefix, -1 ) === ';') {
2072 # The one nasty exception: definition lists work like this:
2073 # ; title : definition text
2074 # So we check for : in the remainder text to split up the
2075 # title and definition, without b0rking links.
2077 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2079 $output .= $term . $this->nextItem( ':' );
2082 } elseif( $prefixLength ||
$lastPrefixLength ) {
2083 # Either open or close a level...
2084 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2085 $paragraphStack = false;
2087 while( $commonPrefixLength < $lastPrefixLength ) {
2088 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2089 --$lastPrefixLength;
2091 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2092 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2094 while ( $prefixLength > $commonPrefixLength ) {
2095 $char = substr( $prefix, $commonPrefixLength, 1 );
2096 $output .= $this->openList( $char );
2098 if ( ';' === $char ) {
2099 # FIXME: This is dupe of code above
2100 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2102 $output .= $term . $this->nextItem( ':' );
2105 ++
$commonPrefixLength;
2107 $lastPrefix = $prefix2;
2109 if( 0 == $prefixLength ) {
2110 wfProfileIn( __METHOD__
."-paragraph" );
2111 # No prefix (not in list)--go to paragraph mode
2112 // XXX: use a stack for nestable elements like span, table and div
2113 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2114 $closematch = preg_match(
2115 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2116 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2117 if ( $openmatch or $closematch ) {
2118 $paragraphStack = false;
2119 #Â TODO bug 5718: paragraph closed
2120 $output .= $this->closeParagraph();
2121 if ( $preOpenMatch and !$preCloseMatch ) {
2122 $this->mInPre
= true;
2124 if ( $closematch ) {
2125 $inBlockElem = false;
2127 $inBlockElem = true;
2129 } else if ( !$inBlockElem && !$this->mInPre
) {
2130 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2132 if ($this->mLastSection
!== 'pre') {
2133 $paragraphStack = false;
2134 $output .= $this->closeParagraph().'<pre>';
2135 $this->mLastSection
= 'pre';
2137 $t = substr( $t, 1 );
2140 if ( '' == trim($t) ) {
2141 if ( $paragraphStack ) {
2142 $output .= $paragraphStack.'<br />';
2143 $paragraphStack = false;
2144 $this->mLastSection
= 'p';
2146 if ($this->mLastSection
!== 'p' ) {
2147 $output .= $this->closeParagraph();
2148 $this->mLastSection
= '';
2149 $paragraphStack = '<p>';
2151 $paragraphStack = '</p><p>';
2155 if ( $paragraphStack ) {
2156 $output .= $paragraphStack;
2157 $paragraphStack = false;
2158 $this->mLastSection
= 'p';
2159 } else if ($this->mLastSection
!== 'p') {
2160 $output .= $this->closeParagraph().'<p>';
2161 $this->mLastSection
= 'p';
2166 wfProfileOut( __METHOD__
."-paragraph" );
2168 // somewhere above we forget to get out of pre block (bug 785)
2169 if($preCloseMatch && $this->mInPre
) {
2170 $this->mInPre
= false;
2172 if ($paragraphStack === false) {
2176 while ( $prefixLength ) {
2177 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2180 if ( '' != $this->mLastSection
) {
2181 $output .= '</' . $this->mLastSection
. '>';
2182 $this->mLastSection
= '';
2185 wfProfileOut( __METHOD__
);
2190 * Split up a string on ':', ignoring any occurences inside tags
2191 * to prevent illegal overlapping.
2192 * @param string $str the string to split
2193 * @param string &$before set to everything before the ':'
2194 * @param string &$after set to everything after the ':'
2195 * return string the position of the ':', or false if none found
2197 static function findColonNoLinks($str, &$before, &$after) {
2198 wfProfileIn( __METHOD__
);
2200 $pos = strpos( $str, ':' );
2201 if( $pos === false ) {
2203 wfProfileOut( __METHOD__
);
2207 $lt = strpos( $str, '<' );
2208 if( $lt === false ||
$lt > $pos ) {
2209 // Easy; no tag nesting to worry about
2210 $before = substr( $str, 0, $pos );
2211 $after = substr( $str, $pos+
1 );
2212 wfProfileOut( __METHOD__
);
2216 // Ugly state machine to walk through avoiding tags.
2217 $state = self
::COLON_STATE_TEXT
;
2219 $len = strlen( $str );
2220 for( $i = 0; $i < $len; $i++
) {
2224 // (Using the number is a performance hack for common cases)
2225 case 0: // self::COLON_STATE_TEXT:
2228 // Could be either a <start> tag or an </end> tag
2229 $state = self
::COLON_STATE_TAGSTART
;
2234 $before = substr( $str, 0, $i );
2235 $after = substr( $str, $i +
1 );
2236 wfProfileOut( __METHOD__
);
2239 // Embedded in a tag; don't break it.
2242 // Skip ahead looking for something interesting
2243 $colon = strpos( $str, ':', $i );
2244 if( $colon === false ) {
2245 // Nothing else interesting
2246 wfProfileOut( __METHOD__
);
2249 $lt = strpos( $str, '<', $i );
2250 if( $stack === 0 ) {
2251 if( $lt === false ||
$colon < $lt ) {
2253 $before = substr( $str, 0, $colon );
2254 $after = substr( $str, $colon +
1 );
2255 wfProfileOut( __METHOD__
);
2259 if( $lt === false ) {
2260 // Nothing else interesting to find; abort!
2261 // We're nested, but there's no close tags left. Abort!
2264 // Skip ahead to next tag start
2266 $state = self
::COLON_STATE_TAGSTART
;
2269 case 1: // self::COLON_STATE_TAG:
2274 $state = self
::COLON_STATE_TEXT
;
2277 // Slash may be followed by >?
2278 $state = self
::COLON_STATE_TAGSLASH
;
2284 case 2: // self::COLON_STATE_TAGSTART:
2287 $state = self
::COLON_STATE_CLOSETAG
;
2290 $state = self
::COLON_STATE_COMMENT
;
2293 // Illegal early close? This shouldn't happen D:
2294 $state = self
::COLON_STATE_TEXT
;
2297 $state = self
::COLON_STATE_TAG
;
2300 case 3: // self::COLON_STATE_CLOSETAG:
2305 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2306 wfProfileOut( __METHOD__
);
2309 $state = self
::COLON_STATE_TEXT
;
2312 case self
::COLON_STATE_TAGSLASH
:
2314 // Yes, a self-closed tag <blah/>
2315 $state = self
::COLON_STATE_TEXT
;
2317 // Probably we're jumping the gun, and this is an attribute
2318 $state = self
::COLON_STATE_TAG
;
2321 case 5: // self::COLON_STATE_COMMENT:
2323 $state = self
::COLON_STATE_COMMENTDASH
;
2326 case self
::COLON_STATE_COMMENTDASH
:
2328 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2330 $state = self
::COLON_STATE_COMMENT
;
2333 case self
::COLON_STATE_COMMENTDASHDASH
:
2335 $state = self
::COLON_STATE_TEXT
;
2337 $state = self
::COLON_STATE_COMMENT
;
2341 throw new MWException( "State machine error in " . __METHOD__
);
2345 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2348 wfProfileOut( __METHOD__
);
2353 * Return value of a magic variable (like PAGENAME)
2357 function getVariableValue( $index ) {
2358 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2361 * Some of these require message or data lookups and can be
2362 * expensive to check many times.
2364 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2365 if ( isset( $this->mVarCache
[$index] ) ) {
2366 return $this->mVarCache
[$index];
2370 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2371 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2374 global $wgLocaltimezone;
2375 if ( isset( $wgLocaltimezone ) ) {
2376 $oldtz = getenv( 'TZ' );
2377 putenv( 'TZ='.$wgLocaltimezone );
2380 wfSuppressWarnings(); // E_STRICT system time bitching
2381 $localTimestamp = date( 'YmdHis', $ts );
2382 $localMonth = date( 'm', $ts );
2383 $localMonthName = date( 'n', $ts );
2384 $localDay = date( 'j', $ts );
2385 $localDay2 = date( 'd', $ts );
2386 $localDayOfWeek = date( 'w', $ts );
2387 $localWeek = date( 'W', $ts );
2388 $localYear = date( 'Y', $ts );
2389 $localHour = date( 'H', $ts );
2390 if ( isset( $wgLocaltimezone ) ) {
2391 putenv( 'TZ='.$oldtz );
2393 wfRestoreWarnings();
2396 case 'currentmonth':
2397 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2398 case 'currentmonthname':
2399 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2400 case 'currentmonthnamegen':
2401 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2402 case 'currentmonthabbrev':
2403 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2405 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2407 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2409 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2410 case 'localmonthname':
2411 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2412 case 'localmonthnamegen':
2413 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2414 case 'localmonthabbrev':
2415 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2417 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2419 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2421 return wfEscapeWikiText( $this->mTitle
->getText() );
2423 return $this->mTitle
->getPartialURL();
2424 case 'fullpagename':
2425 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2426 case 'fullpagenamee':
2427 return $this->mTitle
->getPrefixedURL();
2429 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2430 case 'subpagenamee':
2431 return $this->mTitle
->getSubpageUrlForm();
2432 case 'basepagename':
2433 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2434 case 'basepagenamee':
2435 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2436 case 'talkpagename':
2437 if( $this->mTitle
->canTalk() ) {
2438 $talkPage = $this->mTitle
->getTalkPage();
2439 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2443 case 'talkpagenamee':
2444 if( $this->mTitle
->canTalk() ) {
2445 $talkPage = $this->mTitle
->getTalkPage();
2446 return $talkPage->getPrefixedUrl();
2450 case 'subjectpagename':
2451 $subjPage = $this->mTitle
->getSubjectPage();
2452 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2453 case 'subjectpagenamee':
2454 $subjPage = $this->mTitle
->getSubjectPage();
2455 return $subjPage->getPrefixedUrl();
2457 // Let the edit saving system know we should parse the page
2458 // *after* a revision ID has been assigned.
2459 $this->mOutput
->setFlag( 'vary-revision' );
2460 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2461 return $this->mRevisionId
;
2463 // Let the edit saving system know we should parse the page
2464 // *after* a revision ID has been assigned. This is for null edits.
2465 $this->mOutput
->setFlag( 'vary-revision' );
2466 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2467 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2468 case 'revisionday2':
2469 // Let the edit saving system know we should parse the page
2470 // *after* a revision ID has been assigned. This is for null edits.
2471 $this->mOutput
->setFlag( 'vary-revision' );
2472 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2473 return substr( $this->getRevisionTimestamp(), 6, 2 );
2474 case 'revisionmonth':
2475 // Let the edit saving system know we should parse the page
2476 // *after* a revision ID has been assigned. This is for null edits.
2477 $this->mOutput
->setFlag( 'vary-revision' );
2478 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2479 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2480 case 'revisionyear':
2481 // Let the edit saving system know we should parse the page
2482 // *after* a revision ID has been assigned. This is for null edits.
2483 $this->mOutput
->setFlag( 'vary-revision' );
2484 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2485 return substr( $this->getRevisionTimestamp(), 0, 4 );
2486 case 'revisiontimestamp':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput
->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2491 return $this->getRevisionTimestamp();
2493 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2495 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2497 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2499 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2500 case 'subjectspace':
2501 return $this->mTitle
->getSubjectNsText();
2502 case 'subjectspacee':
2503 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2504 case 'currentdayname':
2505 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2507 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2509 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2511 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2513 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2514 // int to remove the padding
2515 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2517 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2518 case 'localdayname':
2519 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2521 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2523 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2525 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2527 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2528 // int to remove the padding
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2531 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2532 case 'numberofarticles':
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2534 case 'numberoffiles':
2535 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2536 case 'numberofusers':
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2538 case 'numberofpages':
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2540 case 'numberofadmins':
2541 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2542 case 'numberofedits':
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2544 case 'currenttimestamp':
2545 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2546 case 'localtimestamp':
2547 return $this->mVarCache
[$index] = $localTimestamp;
2548 case 'currentversion':
2549 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2555 return $wgServerName;
2557 return $wgScriptPath;
2558 case 'directionmark':
2559 return $wgContLang->getDirMark();
2560 case 'contentlanguage':
2561 global $wgContLanguageCode;
2562 return $wgContLanguageCode;
2565 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2573 * initialise the magic variables (like CURRENTMONTHNAME)
2577 function initialiseVariables() {
2578 wfProfileIn( __METHOD__
);
2579 $variableIDs = MagicWord
::getVariableIDs();
2581 $this->mVariables
= new MagicWordArray( $variableIDs );
2582 wfProfileOut( __METHOD__
);
2586 * Preprocess some wikitext and return the document tree.
2587 * This is the ghost of replace_variables().
2589 * @param string $text The text to parse
2590 * @param integer flags Bitwise combination of:
2591 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2592 * included. Default is to assume a direct page view.
2594 * The generated DOM tree must depend only on the input text and the flags.
2595 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2597 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2598 * change in the DOM tree for a given text, must be passed through the section identifier
2599 * in the section edit link and thus back to extractSections().
2601 * The output of this function is currently only cached in process memory, but a persistent
2602 * cache may be implemented at a later date which takes further advantage of these strict
2603 * dependency requirements.
2607 function preprocessToDom ( $text, $flags = 0 ) {
2608 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2613 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2615 public static function splitWhitespace( $s ) {
2616 $ltrimmed = ltrim( $s );
2617 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2618 $trimmed = rtrim( $ltrimmed );
2619 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2621 $w2 = substr( $ltrimmed, -$diff );
2625 return array( $w1, $trimmed, $w2 );
2629 * Replace magic variables, templates, and template arguments
2630 * with the appropriate text. Templates are substituted recursively,
2631 * taking care to avoid infinite loops.
2633 * Note that the substitution depends on value of $mOutputType:
2634 * self::OT_WIKI: only {{subst:}} templates
2635 * self::OT_PREPROCESS: templates but not extension tags
2636 * self::OT_HTML: all templates and extension tags
2638 * @param string $tex The text to transform
2639 * @param PPFrame $frame Object describing the arguments passed to the template.
2640 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2641 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2642 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2645 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2646 # Prevent too big inclusions
2647 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2651 wfProfileIn( __METHOD__
);
2653 if ( $frame === false ) {
2654 $frame = $this->getPreprocessor()->newFrame();
2655 } elseif ( !( $frame instanceof PPFrame
) ) {
2656 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2657 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2660 $dom = $this->preprocessToDom( $text );
2661 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2662 $text = $frame->expand( $dom, $flags );
2664 wfProfileOut( __METHOD__
);
2668 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2669 static function createAssocArgs( $args ) {
2670 $assocArgs = array();
2672 foreach( $args as $arg ) {
2673 $eqpos = strpos( $arg, '=' );
2674 if ( $eqpos === false ) {
2675 $assocArgs[$index++
] = $arg;
2677 $name = trim( substr( $arg, 0, $eqpos ) );
2678 $value = trim( substr( $arg, $eqpos+
1 ) );
2679 if ( $value === false ) {
2682 if ( $name !== false ) {
2683 $assocArgs[$name] = $value;
2692 * Warn the user when a parser limitation is reached
2693 * Will warn at most once the user per limitation type
2695 * @param string $limitationType, should be one of:
2696 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2697 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2698 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2699 * @params int $current, $max When an explicit limit has been
2700 * exceeded, provide the values (optional)
2702 function limitationWarn( $limitationType, $current=null, $max=null) {
2703 $msgName = $limitationType . '-warning';
2704 //does no harm if $current and $max are present but are unnecessary for the message
2705 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2706 $this->mOutput
->addWarning( $warning );
2707 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2709 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2714 * Return the text of a template, after recursively
2715 * replacing any variables or templates within the template.
2717 * @param array $piece The parts of the template
2718 * $piece['title']: the title, i.e. the part before the |
2719 * $piece['parts']: the parameter array
2720 * $piece['lineStart']: whether the brace was at the start of a line
2721 * @param PPFrame The current frame, contains template arguments
2722 * @return string the text of the template
2725 function braceSubstitution( $piece, $frame ) {
2726 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2727 wfProfileIn( __METHOD__
);
2728 wfProfileIn( __METHOD__
.'-setup' );
2731 $found = false; # $text has been filled
2732 $nowiki = false; # wiki markup in $text should be escaped
2733 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2734 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2735 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2736 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2738 # Title object, where $text came from
2741 # $part1 is the bit before the first |, and must contain only title characters.
2742 # Various prefixes will be stripped from it later.
2743 $titleWithSpaces = $frame->expand( $piece['title'] );
2744 $part1 = trim( $titleWithSpaces );
2747 # Original title text preserved for various purposes
2748 $originalTitle = $part1;
2750 # $args is a list of argument nodes, starting from index 0, not including $part1
2751 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2752 wfProfileOut( __METHOD__
.'-setup' );
2755 wfProfileIn( __METHOD__
.'-modifiers' );
2757 $mwSubst = MagicWord
::get( 'subst' );
2758 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2759 # One of two possibilities is true:
2760 # 1) Found SUBST but not in the PST phase
2761 # 2) Didn't find SUBST and in the PST phase
2762 # In either case, return without further processing
2763 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2770 if ( !$found && $args->getLength() == 0 ) {
2771 $id = $this->mVariables
->matchStartToEnd( $part1 );
2772 if ( $id !== false ) {
2773 $text = $this->getVariableValue( $id );
2774 if (MagicWord
::getCacheTTL($id)>-1)
2775 $this->mOutput
->mContainsOldMagic
= true;
2780 # MSG, MSGNW and RAW
2783 $mwMsgnw = MagicWord
::get( 'msgnw' );
2784 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2787 # Remove obsolete MSG:
2788 $mwMsg = MagicWord
::get( 'msg' );
2789 $mwMsg->matchStartAndRemove( $part1 );
2793 $mwRaw = MagicWord
::get( 'raw' );
2794 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2795 $forceRawInterwiki = true;
2798 wfProfileOut( __METHOD__
.'-modifiers' );
2802 wfProfileIn( __METHOD__
. '-pfunc' );
2804 $colonPos = strpos( $part1, ':' );
2805 if ( $colonPos !== false ) {
2806 # Case sensitive functions
2807 $function = substr( $part1, 0, $colonPos );
2808 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2809 $function = $this->mFunctionSynonyms
[1][$function];
2811 # Case insensitive functions
2812 $function = strtolower( $function );
2813 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2814 $function = $this->mFunctionSynonyms
[0][$function];
2820 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2821 $initialArgs = array( &$this );
2822 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2823 if ( $flags & SFH_OBJECT_ARGS
) {
2824 # Add a frame parameter, and pass the arguments as an array
2825 $allArgs = $initialArgs;
2826 $allArgs[] = $frame;
2827 for ( $i = 0; $i < $args->getLength(); $i++
) {
2828 $funcArgs[] = $args->item( $i );
2830 $allArgs[] = $funcArgs;
2832 # Convert arguments to plain text
2833 for ( $i = 0; $i < $args->getLength(); $i++
) {
2834 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2836 $allArgs = array_merge( $initialArgs, $funcArgs );
2839 # Workaround for PHP bug 35229 and similar
2840 if ( !is_callable( $callback ) ) {
2841 throw new MWException( "Tag hook for $name is not callable\n" );
2843 $result = call_user_func_array( $callback, $allArgs );
2846 $preprocessFlags = 0;
2848 if ( is_array( $result ) ) {
2849 if ( isset( $result[0] ) ) {
2851 unset( $result[0] );
2854 // Extract flags into the local scope
2855 // This allows callers to set flags such as nowiki, found, etc.
2861 $text = $this->preprocessToDom( $text, $preprocessFlags );
2866 wfProfileOut( __METHOD__
. '-pfunc' );
2869 # Finish mangling title and then check for loops.
2870 # Set $title to a Title object and $titleText to the PDBK
2873 # Split the title into page and subpage
2875 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2876 if ($subpage !== '') {
2877 $ns = $this->mTitle
->getNamespace();
2879 $title = Title
::newFromText( $part1, $ns );
2881 $titleText = $title->getPrefixedText();
2882 # Check for language variants if the template is not found
2883 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2884 $wgContLang->findVariantLink($part1, $title);
2886 # Do infinite loop check
2887 if ( !$frame->loopCheck( $title ) ) {
2889 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2890 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2892 # Do recursion depth check
2893 $limit = $this->mOptions
->getMaxTemplateDepth();
2894 if ( $frame->depth
>= $limit ) {
2896 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2901 # Load from database
2902 if ( !$found && $title ) {
2903 wfProfileIn( __METHOD__
. '-loadtpl' );
2904 if ( !$title->isExternal() ) {
2905 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2906 $text = SpecialPage
::capturePath( $title );
2907 if ( is_string( $text ) ) {
2910 $this->disableCache();
2912 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2913 $found = false; //access denied
2914 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2916 list( $text, $title ) = $this->getTemplateDom( $title );
2917 if ( $text !== false ) {
2923 # If the title is valid but undisplayable, make a link to it
2924 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2925 $text = "[[:$titleText]]";
2928 } elseif ( $title->isTrans() ) {
2929 // Interwiki transclusion
2930 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2931 $text = $this->interwikiTransclude( $title, 'render' );
2934 $text = $this->interwikiTransclude( $title, 'raw' );
2935 // Preprocess it like a template
2936 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2941 wfProfileOut( __METHOD__
. '-loadtpl' );
2944 # If we haven't found text to substitute by now, we're done
2945 # Recover the source wikitext and return it
2947 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2948 wfProfileOut( __METHOD__
);
2949 return array( 'object' => $text );
2952 # Expand DOM-style return values in a child frame
2953 if ( $isChildObj ) {
2954 # Clean up argument array
2955 $newFrame = $frame->newChild( $args, $title );
2958 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2959 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2960 # Expansion is eligible for the empty-frame cache
2961 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2962 $text = $this->mTplExpandCache
[$titleText];
2964 $text = $newFrame->expand( $text );
2965 $this->mTplExpandCache
[$titleText] = $text;
2968 # Uncached expansion
2969 $text = $newFrame->expand( $text );
2972 if ( $isLocalObj && $nowiki ) {
2973 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2974 $isLocalObj = false;
2977 # Replace raw HTML by a placeholder
2978 # Add a blank line preceding, to prevent it from mucking up
2979 # immediately preceding headings
2981 $text = "\n\n" . $this->insertStripItem( $text );
2983 # Escape nowiki-style return values
2984 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2985 $text = wfEscapeWikiText( $text );
2987 # Bug 529: if the template begins with a table or block-level
2988 # element, it should be treated as beginning a new line.
2989 # This behaviour is somewhat controversial.
2990 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2991 $text = "\n" . $text;
2994 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2995 # Error, oversize inclusion
2996 $text = "[[$originalTitle]]" .
2997 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2998 $this->limitationWarn( 'post-expand-template-inclusion' );
3001 if ( $isLocalObj ) {
3002 $ret = array( 'object' => $text );
3004 $ret = array( 'text' => $text );
3007 wfProfileOut( __METHOD__
);
3012 * Get the semi-parsed DOM representation of a template with a given title,
3013 * and its redirect destination title. Cached.
3015 function getTemplateDom( $title ) {
3016 $cacheTitle = $title;
3017 $titleText = $title->getPrefixedDBkey();
3019 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3020 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3021 $title = Title
::makeTitle( $ns, $dbk );
3022 $titleText = $title->getPrefixedDBkey();
3024 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3025 return array( $this->mTplDomCache
[$titleText], $title );
3028 // Cache miss, go to the database
3029 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3031 if ( $text === false ) {
3032 $this->mTplDomCache
[$titleText] = false;
3033 return array( false, $title );
3036 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3037 $this->mTplDomCache
[ $titleText ] = $dom;
3039 if (! $title->equals($cacheTitle)) {
3040 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3041 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3044 return array( $dom, $title );
3048 * Fetch the unparsed text of a template and register a reference to it.
3050 function fetchTemplateAndTitle( $title ) {
3051 $templateCb = $this->mOptions
->getTemplateCallback();
3052 $stuff = call_user_func( $templateCb, $title, $this );
3053 $text = $stuff['text'];
3054 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3055 if ( isset( $stuff['deps'] ) ) {
3056 foreach ( $stuff['deps'] as $dep ) {
3057 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3060 return array($text,$finalTitle);
3063 function fetchTemplate( $title ) {
3064 $rv = $this->fetchTemplateAndTitle($title);
3069 * Static function to get a template
3070 * Can be overridden via ParserOptions::setTemplateCallback().
3072 static function statelessFetchTemplate( $title, $parser=false ) {
3073 $text = $skip = false;
3074 $finalTitle = $title;
3077 // Loop to fetch the article, with up to 1 redirect
3078 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3079 # Give extensions a chance to select the revision instead
3080 $id = false; // Assume current
3081 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3087 'page_id' => $title->getArticleID(),
3091 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3092 $rev_id = $rev ?
$rev->getId() : 0;
3093 // If there is no current revision, there is no page
3094 if( $id === false && !$rev ) {
3095 $linkCache = LinkCache
::singleton();
3096 $linkCache->addBadLinkObj( $title );
3101 'page_id' => $title->getArticleID(),
3102 'rev_id' => $rev_id );
3105 $text = $rev->getText();
3106 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3108 $message = $wgLang->lcfirst( $title->getText() );
3109 $text = wfMsgForContentNoTrans( $message );
3110 if( wfEmptyMsg( $message, $text ) ) {
3117 if ( $text === false ) {
3121 $finalTitle = $title;
3122 $title = Title
::newFromRedirect( $text );
3126 'finalTitle' => $finalTitle,
3131 * Transclude an interwiki link.
3133 function interwikiTransclude( $title, $action ) {
3134 global $wgEnableScaryTranscluding;
3136 if (!$wgEnableScaryTranscluding)
3137 return wfMsg('scarytranscludedisabled');
3139 $url = $title->getFullUrl( "action=$action" );
3141 if (strlen($url) > 255)
3142 return wfMsg('scarytranscludetoolong');
3143 return $this->fetchScaryTemplateMaybeFromCache($url);
3146 static function fetchScaryTemplateMaybeFromCache($url) {
3147 global $wgTranscludeCacheExpiry;
3148 $dbr = wfGetDB(DB_SLAVE
);
3149 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3150 array('tc_url' => $url));
3152 $time = $obj->tc_time
;
3153 $text = $obj->tc_contents
;
3154 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3159 $text = Http
::get($url);
3161 return wfMsg('scarytranscludefailed', $url);
3163 $dbw = wfGetDB(DB_MASTER
);
3164 $dbw->replace('transcache', array('tc_url'), array(
3166 'tc_time' => time(),
3167 'tc_contents' => $text));
3173 * Triple brace replacement -- used for template arguments
3176 function argSubstitution( $piece, $frame ) {
3177 wfProfileIn( __METHOD__
);
3180 $parts = $piece['parts'];
3181 $nameWithSpaces = $frame->expand( $piece['title'] );
3182 $argName = trim( $nameWithSpaces );
3184 $text = $frame->getArgument( $argName );
3185 if ( $text === false && $parts->getLength() > 0
3189 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3192 # No match in frame, use the supplied default
3193 $object = $parts->item( 0 )->getChildren();
3195 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3196 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3197 $this->limitationWarn( 'post-expand-template-argument' );
3200 if ( $text === false && $object === false ) {
3202 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3204 if ( $error !== false ) {
3207 if ( $object !== false ) {
3208 $ret = array( 'object' => $object );
3210 $ret = array( 'text' => $text );
3213 wfProfileOut( __METHOD__
);
3218 * Return the text to be used for a given extension tag.
3219 * This is the ghost of strip().
3221 * @param array $params Associative array of parameters:
3222 * name PPNode for the tag name
3223 * attr PPNode for unparsed text where tag attributes are thought to be
3224 * attributes Optional associative array of parsed attributes
3225 * inner Contents of extension element
3226 * noClose Original text did not have a close tag
3227 * @param PPFrame $frame
3229 function extensionSubstitution( $params, $frame ) {
3230 global $wgRawHtml, $wgContLang;
3232 $name = $frame->expand( $params['name'] );
3233 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3234 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3236 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3238 if ( $this->ot
['html'] ) {
3239 $name = strtolower( $name );
3241 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3242 if ( isset( $params['attributes'] ) ) {
3243 $attributes = $attributes +
$params['attributes'];
3251 throw new MWException( '<html> extension tag encountered unexpectedly' );
3254 $output = Xml
::escapeTagsOnly( $content );
3257 $output = $wgContLang->armourMath(
3258 MathRenderer
::renderMath( $content, $attributes ) );
3261 $output = $this->renderImageGallery( $content, $attributes );
3264 if( isset( $this->mTagHooks
[$name] ) ) {
3265 # Workaround for PHP bug 35229 and similar
3266 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3267 throw new MWException( "Tag hook for $name is not callable\n" );
3269 $output = call_user_func_array( $this->mTagHooks
[$name],
3270 array( $content, $attributes, $this ) );
3272 $output = '<span class="error">Invalid tag extension name: ' .
3273 htmlspecialchars( $name ) . '</span>';
3277 if ( is_null( $attrText ) ) {
3280 if ( isset( $params['attributes'] ) ) {
3281 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3282 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3283 htmlspecialchars( $attrValue ) . '"';
3286 if ( $content === null ) {
3287 $output = "<$name$attrText/>";
3289 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3290 $output = "<$name$attrText>$content$close";
3294 if ( $name === 'html' ||
$name === 'nowiki' ) {
3295 $this->mStripState
->nowiki
->setPair( $marker, $output );
3297 $this->mStripState
->general
->setPair( $marker, $output );
3303 * Increment an include size counter
3305 * @param string $type The type of expansion
3306 * @param integer $size The size of the text
3307 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3309 function incrementIncludeSize( $type, $size ) {
3310 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3313 $this->mIncludeSizes
[$type] +
= $size;
3319 * Increment the expensive function count
3321 * @return boolean False if the limit has been exceeded
3323 function incrementExpensiveFunctionCount() {
3324 global $wgExpensiveParserFunctionLimit;
3325 $this->mExpensiveFunctionCount++
;
3326 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3333 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3334 * Fills $this->mDoubleUnderscores, returns the modified text
3336 function doDoubleUnderscore( $text ) {
3337 // The position of __TOC__ needs to be recorded
3338 $mw = MagicWord
::get( 'toc' );
3339 if( $mw->match( $text ) ) {
3340 $this->mShowToc
= true;
3341 $this->mForceTocPosition
= true;
3343 // Set a placeholder. At the end we'll fill it in with the TOC.
3344 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3346 // Only keep the first one.
3347 $text = $mw->replace( '', $text );
3350 // Now match and remove the rest of them
3351 $mwa = MagicWord
::getDoubleUnderscoreArray();
3352 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3354 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3355 $this->mOutput
->mNoGallery
= true;
3357 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3358 $this->mShowToc
= false;
3360 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3361 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3363 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3364 if ( $containerCategory ) {
3365 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3367 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3370 # (bug 8068) Allow control over whether robots index a page.
3372 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3373 # is not desirable, the last one on the page should win.
3374 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3375 $this->mOutput
->setIndexPolicy( 'noindex' );
3376 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3377 $this->mOutput
->setIndexPolicy( 'index' );
3384 * This function accomplishes several tasks:
3385 * 1) Auto-number headings if that option is enabled
3386 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3387 * 3) Add a Table of contents on the top for users who have enabled the option
3388 * 4) Auto-anchor headings
3390 * It loops through all headlines, collects the necessary data, then splits up the
3391 * string and re-inserts the newly formatted headlines.
3393 * @param string $text
3394 * @param boolean $isMain
3397 function formatHeadings( $text, $isMain=true ) {
3398 global $wgMaxTocLevel, $wgContLang;
3400 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3401 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3404 $showEditLink = $this->mOptions
->getEditSection();
3407 # Inhibit editsection links if requested in the page
3408 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3412 # Get all headlines for numbering them and adding funky stuff like [edit]
3413 # links - this is for later, but we need the number of headlines right now
3415 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3417 # if there are fewer than 4 headlines in the article, do not show TOC
3418 # unless it's been explicitly enabled.
3419 $enoughToc = $this->mShowToc
&&
3420 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3422 # Allow user to stipulate that a page should have a "new section"
3423 # link added via __NEWSECTIONLINK__
3424 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3425 $this->mOutput
->setNewSection( true );
3428 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3429 # override above conditions and always show TOC above first header
3430 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3431 $this->mShowToc
= true;
3435 # We need this to perform operations on the HTML
3436 $sk = $this->mOptions
->getSkin();
3442 # Ugh .. the TOC should have neat indentation levels which can be
3443 # passed to the skin functions. These are determined here
3447 $sublevelCount = array();
3448 $levelCount = array();
3454 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3455 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3458 foreach( $matches[3] as $headline ) {
3459 $isTemplate = false;
3461 $sectionIndex = false;
3463 $markerMatches = array();
3464 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3465 $serial = $markerMatches[1];
3466 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3467 $isTemplate = ($titleText != $baseTitleText);
3468 $headline = preg_replace("/^$markerRegex/", "", $headline);
3472 $prevlevel = $level;
3473 $prevtoclevel = $toclevel;
3475 $level = $matches[1][$headlineCount];
3477 if( $doNumberHeadings ||
$enoughToc ) {
3479 if ( $level > $prevlevel ) {
3480 # Increase TOC level
3482 $sublevelCount[$toclevel] = 0;
3483 if( $toclevel<$wgMaxTocLevel ) {
3484 $prevtoclevel = $toclevel;
3485 $toc .= $sk->tocIndent();
3489 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3490 # Decrease TOC level, find level to jump to
3492 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3493 # Can only go down to level 1
3496 for ($i = $toclevel; $i > 0; $i--) {
3497 if ( $levelCount[$i] == $level ) {
3498 # Found last matching level
3502 elseif ( $levelCount[$i] < $level ) {
3503 # Found first matching level below current level
3509 if( $toclevel<$wgMaxTocLevel ) {
3510 if($prevtoclevel < $wgMaxTocLevel) {
3511 # Unindent only if the previous toc level was shown :p
3512 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3513 $prevtoclevel = $toclevel;
3515 $toc .= $sk->tocLineEnd();
3520 # No change in level, end TOC line
3521 if( $toclevel<$wgMaxTocLevel ) {
3522 $toc .= $sk->tocLineEnd();
3526 $levelCount[$toclevel] = $level;
3528 # count number of headlines for each level
3529 @$sublevelCount[$toclevel]++
;
3531 for( $i = 1; $i <= $toclevel; $i++
) {
3532 if( !empty( $sublevelCount[$i] ) ) {
3536 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3542 # The safe header is a version of the header text safe to use for links
3543 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3544 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3546 # Remove link placeholders by the link text.
3547 # <!--LINK number-->
3549 # link text with suffix
3550 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3552 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3553 $tocline = preg_replace(
3554 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3558 $tocline = trim( $tocline );
3560 # For the anchor, strip out HTML-y stuff period
3561 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3562 $safeHeadline = trim( $safeHeadline );
3564 # Save headline for section edit hint before it's escaped
3565 $headlineHint = $safeHeadline;
3566 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3567 # HTML names must be case-insensitively unique (bug 10721)
3568 $arrayKey = strtolower( $safeHeadline );
3570 # count how many in assoc. array so we can track dupes in anchors
3571 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3572 $refcount[$headlineCount] = $refers[$arrayKey];
3574 # Don't number the heading if it is the only one (looks silly)
3575 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3576 # the two are different if the line contains a link
3577 $headline=$numbering . ' ' . $headline;
3580 # Create the anchor for linking from the TOC to the section
3581 $anchor = $safeHeadline;
3582 if($refcount[$headlineCount] > 1 ) {
3583 $anchor .= '_' . $refcount[$headlineCount];
3585 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3586 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3587 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3589 # give headline the correct <h#> tag
3590 if( $showEditLink && $sectionIndex !== false ) {
3592 # Put a T flag in the section identifier, to indicate to extractSections()
3593 # that sections inside <includeonly> should be counted.
3594 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3596 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3601 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3606 $this->mOutput
->setSections( $tocraw );
3608 # Never ever show TOC if no headers
3609 if( $numVisible < 1 ) {
3614 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3615 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3617 $toc = $sk->tocList( $toc );
3620 # split up and insert constructed headlines
3622 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3625 foreach( $blocks as $block ) {
3626 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3627 # This is the [edit] link that appears for the top block of text when
3628 # section editing is enabled
3630 # Disabled because it broke block formatting
3631 # For example, a bullet point in the top line
3632 # $full .= $sk->editSectionLink(0);
3635 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3636 # Top anchor now in skin
3640 if( !empty( $head[$i] ) ) {
3645 if( $this->mForceTocPosition
) {
3646 return str_replace( '<!--MWTOC-->', $toc, $full );
3653 * Transform wiki markup when saving a page by doing \r\n -> \n
3654 * conversion, substitting signatures, {{subst:}} templates, etc.
3656 * @param string $text the text to transform
3657 * @param Title &$title the Title object for the current article
3658 * @param User &$user the User object describing the current user
3659 * @param ParserOptions $options parsing options
3660 * @param bool $clearState whether to clear the parser state first
3661 * @return string the altered wiki markup
3664 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3665 $this->mOptions
= $options;
3666 $this->setTitle( $title );
3667 $this->setOutputType( self
::OT_WIKI
);
3669 if ( $clearState ) {
3670 $this->clearState();
3676 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3677 $text = $this->pstPass2( $text, $user );
3678 $text = $this->mStripState
->unstripBoth( $text );
3683 * Pre-save transform helper function
3686 function pstPass2( $text, $user ) {
3687 global $wgContLang, $wgLocaltimezone;
3689 /* Note: This is the timestamp saved as hardcoded wikitext to
3690 * the database, we use $wgContLang here in order to give
3691 * everyone the same signature and use the default one rather
3692 * than the one selected in each user's preferences.
3694 * (see also bug 12815)
3696 $ts = $this->mOptions
->getTimestamp();
3697 $tz = wfMsgForContent( 'timezone-utc' );
3698 if ( isset( $wgLocaltimezone ) ) {
3699 $unixts = wfTimestamp( TS_UNIX
, $ts );
3700 $oldtz = getenv( 'TZ' );
3701 putenv( 'TZ='.$wgLocaltimezone );
3702 $ts = date( 'YmdHis', $unixts );
3703 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3704 putenv( 'TZ='.$oldtz );
3707 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3709 # Variable replacement
3710 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3711 $text = $this->replaceVariables( $text );
3714 $sigText = $this->getUserSig( $user );
3715 $text = strtr( $text, array(
3717 '~~~~' => "$sigText $d",
3721 # Context links: [[|name]] and [[name (context)|]]
3723 global $wgLegalTitleChars;
3724 $tc = "[$wgLegalTitleChars]";
3725 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3727 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3728 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3729 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3731 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3732 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3733 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3735 $t = $this->mTitle
->getText();
3737 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3738 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3739 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3740 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3742 # if there's no context, don't bother duplicating the title
3743 $text = preg_replace( $p2, '[[\\1]]', $text );
3746 # Trim trailing whitespace
3747 $text = rtrim( $text );
3753 * Fetch the user's signature text, if any, and normalize to
3754 * validated, ready-to-insert wikitext.
3760 function getUserSig( &$user ) {
3761 global $wgMaxSigChars;
3763 $username = $user->getName();
3764 $nickname = $user->getOption( 'nickname' );
3765 $nickname = $nickname === '' ?
$username : $nickname;
3767 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3768 $nickname = $username;
3769 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3770 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3771 # Sig. might contain markup; validate this
3772 if( $this->validateSig( $nickname ) !== false ) {
3773 # Validated; clean up (if needed) and return it
3774 return $this->cleanSig( $nickname, true );
3776 # Failed to validate; fall back to the default
3777 $nickname = $username;
3778 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3782 // Make sure nickname doesnt get a sig in a sig
3783 $nickname = $this->cleanSigInSig( $nickname );
3785 # If we're still here, make it a link to the user page
3786 $userText = wfEscapeWikiText( $username );
3787 $nickText = wfEscapeWikiText( $nickname );
3788 if ( $user->isAnon() ) {
3789 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3791 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3796 * Check that the user's signature contains no bad XML
3798 * @param string $text
3799 * @return mixed An expanded string, or false if invalid.
3801 static function validateSig( $text ) {
3802 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3806 * Clean up signature text
3808 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3809 * 2) Substitute all transclusions
3811 * @param string $text
3812 * @param $parsing Whether we're cleaning (preferences save) or parsing
3813 * @return string Signature text
3815 function cleanSig( $text, $parsing = false ) {
3818 $this->clearState();
3819 $this->setTitle( $wgTitle );
3820 $this->mOptions
= new ParserOptions
;
3821 $this->setOutputType
= self
::OT_PREPROCESS
;
3824 # Option to disable this feature
3825 if ( !$this->mOptions
->getCleanSignatures() ) {
3829 # FIXME: regex doesn't respect extension tags or nowiki
3830 # => Move this logic to braceSubstitution()
3831 $substWord = MagicWord
::get( 'subst' );
3832 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3833 $substText = '{{' . $substWord->getSynonym( 0 );
3835 $text = preg_replace( $substRegex, $substText, $text );
3836 $text = $this->cleanSigInSig( $text );
3837 $dom = $this->preprocessToDom( $text );
3838 $frame = $this->getPreprocessor()->newFrame();
3839 $text = $frame->expand( $dom );
3842 $text = $this->mStripState
->unstripBoth( $text );
3849 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3850 * @param string $text
3851 * @return string Signature text with /~{3,5}/ removed
3853 static function cleanSigInSig( $text ) {
3854 $text = preg_replace( '/~{3,5}/', '', $text );
3859 * Set up some variables which are usually set up in parse()
3860 * so that an external function can call some class members with confidence
3863 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3864 $this->setTitle( $title );
3865 $this->mOptions
= $options;
3866 $this->setOutputType( $outputType );
3867 if ( $clearState ) {
3868 $this->clearState();
3873 * Wrapper for preprocess()
3875 * @param string $text the text to preprocess
3876 * @param ParserOptions $options options
3880 function transformMsg( $text, $options ) {
3882 static $executing = false;
3884 # Guard against infinite recursion
3890 wfProfileIn(__METHOD__
);
3891 $text = $this->preprocess( $text, $wgTitle, $options );
3894 wfProfileOut(__METHOD__
);
3899 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3900 * The callback should have the following form:
3901 * function myParserHook( $text, $params, &$parser ) { ... }
3903 * Transform and return $text. Use $parser for any required context, e.g. use
3904 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3908 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3909 * @param mixed $callback The callback function (and object) to use for the tag
3911 * @return The old value of the mTagHooks array associated with the hook
3913 function setHook( $tag, $callback ) {
3914 $tag = strtolower( $tag );
3915 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3916 $this->mTagHooks
[$tag] = $callback;
3917 if( !in_array( $tag, $this->mStripList
) ) {
3918 $this->mStripList
[] = $tag;
3924 function setTransparentTagHook( $tag, $callback ) {
3925 $tag = strtolower( $tag );
3926 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3927 $this->mTransparentTagHooks
[$tag] = $callback;
3933 * Remove all tag hooks
3935 function clearTagHooks() {
3936 $this->mTagHooks
= array();
3937 $this->mStripList
= $this->mDefaultStripList
;
3941 * Create a function, e.g. {{sum:1|2|3}}
3942 * The callback function should have the form:
3943 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3945 * Or with SFH_OBJECT_ARGS:
3946 * function myParserFunction( $parser, $frame, $args ) { ... }
3948 * The callback may either return the text result of the function, or an array with the text
3949 * in element 0, and a number of flags in the other elements. The names of the flags are
3950 * specified in the keys. Valid flags are:
3951 * found The text returned is valid, stop processing the template. This
3953 * nowiki Wiki markup in the return value should be escaped
3954 * isHTML The returned text is HTML, armour it against wikitext transformation
3958 * @param string $id The magic word ID
3959 * @param mixed $callback The callback function (and object) to use
3960 * @param integer $flags a combination of the following flags:
3961 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3963 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3964 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3965 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3966 * the arguments, and to control the way they are expanded.
3968 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3969 * arguments, for instance:
3970 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3972 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3973 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3974 * working if/when this is changed.
3976 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3979 * Please read the documentation in includes/parser/Preprocessor.php for more information
3980 * about the methods available in PPFrame and PPNode.
3982 * @return The old callback function for this name, if any
3984 function setFunctionHook( $id, $callback, $flags = 0 ) {
3985 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3986 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3988 # Add to function cache
3989 $mw = MagicWord
::get( $id );
3991 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
3993 $synonyms = $mw->getSynonyms();
3994 $sensitive = intval( $mw->isCaseSensitive() );
3996 foreach ( $synonyms as $syn ) {
3998 if ( !$sensitive ) {
3999 $syn = strtolower( $syn );
4002 if ( !( $flags & SFH_NO_HASH
) ) {
4005 # Remove trailing colon
4006 if ( substr( $syn, -1, 1 ) === ':' ) {
4007 $syn = substr( $syn, 0, -1 );
4009 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4015 * Get all registered function hook identifiers
4019 function getFunctionHooks() {
4020 return array_keys( $this->mFunctionHooks
);
4024 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4025 * Placeholders created in Skin::makeLinkObj()
4026 * Returns an array of link CSS classes, indexed by PDBK.
4028 function replaceLinkHolders( &$text, $options = 0 ) {
4029 return $this->mLinkHolders
->replace( $text );
4033 * Replace <!--LINK--> link placeholders with plain text of links
4034 * (not HTML-formatted).
4035 * @param string $text
4038 function replaceLinkHoldersText( $text ) {
4039 return $this->mLinkHolders
->replaceText( $text );
4043 * Tag hook handler for 'pre'.
4045 static function renderPreTag( $text, $attribs ) {
4046 // Backwards-compatibility hack
4047 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4049 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4050 return wfOpenElement( 'pre', $attribs ) .
4051 Xml
::escapeTagsOnly( $content ) .
4056 * Renders an image gallery from a text with one line per image.
4057 * text labels may be given by using |-style alternative text. E.g.
4058 * Image:one.jpg|The number "1"
4059 * Image:tree.jpg|A tree
4060 * given as text will return the HTML of a gallery with two images,
4061 * labeled 'The number "1"' and
4064 function renderImageGallery( $text, $params ) {
4065 $ig = new ImageGallery();
4066 $ig->setContextTitle( $this->mTitle
);
4067 $ig->setShowBytes( false );
4068 $ig->setShowFilename( false );
4069 $ig->setParser( $this );
4070 $ig->setHideBadImages();
4071 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4072 $ig->useSkin( $this->mOptions
->getSkin() );
4073 $ig->mRevisionId
= $this->mRevisionId
;
4075 if( isset( $params['caption'] ) ) {
4076 $caption = $params['caption'];
4077 $caption = htmlspecialchars( $caption );
4078 $caption = $this->replaceInternalLinks( $caption );
4079 $ig->setCaptionHtml( $caption );
4081 if( isset( $params['perrow'] ) ) {
4082 $ig->setPerRow( $params['perrow'] );
4084 if( isset( $params['widths'] ) ) {
4085 $ig->setWidths( $params['widths'] );
4087 if( isset( $params['heights'] ) ) {
4088 $ig->setHeights( $params['heights'] );
4091 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4093 $lines = StringUtils
::explode( "\n", $text );
4094 foreach ( $lines as $line ) {
4095 # match lines like these:
4096 # Image:someimage.jpg|This is some image
4098 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4100 if ( count( $matches ) == 0 ) {
4104 if ( strpos( $matches[0], '%' ) !== false )
4105 $matches[1] = urldecode( $matches[1] );
4106 $tp = Title
::newFromText( $matches[1], NS_IMAGE
);
4108 if( is_null( $nt ) ) {
4109 # Bogus title. Ignore these so we don't bomb out later.
4112 if ( isset( $matches[3] ) ) {
4113 $label = $matches[3];
4118 $html = $this->recursiveTagParse( trim( $label ) );
4120 $ig->add( $nt, $html );
4122 # Only add real images (bug #5586)
4123 if ( $nt->getNamespace() == NS_IMAGE
) {
4124 $this->mOutput
->addImage( $nt->getDBkey() );
4127 return $ig->toHTML();
4130 function getImageParams( $handler ) {
4132 $handlerClass = get_class( $handler );
4136 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4137 // Initialise static lists
4138 static $internalParamNames = array(
4139 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4140 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4141 'bottom', 'text-bottom' ),
4142 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4143 'upright', 'border' ),
4145 static $internalParamMap;
4146 if ( !$internalParamMap ) {
4147 $internalParamMap = array();
4148 foreach ( $internalParamNames as $type => $names ) {
4149 foreach ( $names as $name ) {
4150 $magicName = str_replace( '-', '_', "img_$name" );
4151 $internalParamMap[$magicName] = array( $type, $name );
4156 // Add handler params
4157 $paramMap = $internalParamMap;
4159 $handlerParamMap = $handler->getParamMap();
4160 foreach ( $handlerParamMap as $magic => $paramName ) {
4161 $paramMap[$magic] = array( 'handler', $paramName );
4164 $this->mImageParams
[$handlerClass] = $paramMap;
4165 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4167 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4171 * Parse image options text and use it to make an image
4172 * @param Title $title
4173 * @param string $options
4174 * @param LinkHolderArray $holders
4176 function makeImage( $title, $options, $holders = false ) {
4177 # Check if the options text is of the form "options|alt text"
4179 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4180 # * left no resizing, just left align. label is used for alt= only
4181 # * right same, but right aligned
4182 # * none same, but not aligned
4183 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4184 # * center center the image
4185 # * framed Keep original image size, no magnify-button.
4186 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4187 # * upright reduce width for upright images, rounded to full __0 px
4188 # * border draw a 1px border around the image
4189 # vertical-align values (no % or length right now):
4199 $parts = StringUtils
::explode( "|", $options );
4200 $sk = $this->mOptions
->getSkin();
4202 # Give extensions a chance to select the file revision for us
4203 $skip = $time = $descQuery = false;
4204 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4207 return $sk->link( $title );
4211 $file = wfFindFile( $title, $time );
4212 $handler = $file ?
$file->getHandler() : false;
4214 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4216 # Process the input parameters
4218 $params = array( 'frame' => array(), 'handler' => array(),
4219 'horizAlign' => array(), 'vertAlign' => array() );
4220 foreach( $parts as $part ) {
4221 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4223 if( isset( $paramMap[$magicName] ) ) {
4224 list( $type, $paramName ) = $paramMap[$magicName];
4226 // Special case; width and height come in one variable together
4227 if( $type === 'handler' && $paramName === 'width' ) {
4229 # (bug 13500) In both cases (width/height and width only),
4230 # permit trailing "px" for backward compatibility.
4231 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4232 $width = intval( $m[1] );
4233 $height = intval( $m[2] );
4234 if ( $handler->validateParam( 'width', $width ) ) {
4235 $params[$type]['width'] = $width;
4238 if ( $handler->validateParam( 'height', $height ) ) {
4239 $params[$type]['height'] = $height;
4242 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4243 $width = intval( $value );
4244 if ( $handler->validateParam( 'width', $width ) ) {
4245 $params[$type]['width'] = $width;
4248 } // else no validation -- bug 13436
4250 if ( $type === 'handler' ) {
4251 # Validate handler parameter
4252 $validated = $handler->validateParam( $paramName, $value );
4254 # Validate internal parameters
4255 switch( $paramName ) {
4257 /// @fixme - possibly check validity here?
4258 /// downstream behavior seems odd with missing manual thumbs.
4262 // Most other things appear to be empty or numeric...
4263 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4268 $params[$type][$paramName] = $value;
4272 if ( !$validated ) {
4277 # Process alignment parameters
4278 if ( $params['horizAlign'] ) {
4279 $params['frame']['align'] = key( $params['horizAlign'] );
4281 if ( $params['vertAlign'] ) {
4282 $params['frame']['valign'] = key( $params['vertAlign'] );
4285 # Strip bad stuff out of the alt text
4286 # We can't just use replaceLinkHoldersText() here, because if this function
4287 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4289 $alt = $holders->replaceText( $caption );
4291 $alt = $this->replaceLinkHoldersText( $caption );
4294 # make sure there are no placeholders in thumbnail attributes
4295 # that are later expanded to html- so expand them now and
4297 $alt = $this->mStripState
->unstripBoth( $alt );
4298 $alt = Sanitizer
::stripAllTags( $alt );
4300 $params['frame']['alt'] = $alt;
4301 $params['frame']['caption'] = $caption;
4303 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4305 # Linker does the rest
4306 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4308 # Give the handler a chance to modify the parser object
4310 $handler->parserTransformHook( $this, $file );
4317 * Set a flag in the output object indicating that the content is dynamic and
4318 * shouldn't be cached.
4320 function disableCache() {
4321 wfDebug( "Parser output marked as uncacheable.\n" );
4322 $this->mOutput
->mCacheTime
= -1;
4326 * Callback from the Sanitizer for expanding items found in HTML attribute
4327 * values, so they can be safely tested and escaped.
4328 * @param string $text
4329 * @param PPFrame $frame
4333 function attributeStripCallback( &$text, $frame = false ) {
4334 $text = $this->replaceVariables( $text, $frame );
4335 $text = $this->mStripState
->unstripBoth( $text );
4344 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4345 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4346 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4352 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4357 * Break wikitext input into sections, and either pull or replace
4358 * some particular section's text.
4360 * External callers should use the getSection and replaceSection methods.
4362 * @param string $text Page wikitext
4363 * @param string $section A section identifier string of the form:
4364 * <flag1> - <flag2> - ... - <section number>
4366 * Currently the only recognised flag is "T", which means the target section number
4367 * was derived during a template inclusion parse, in other words this is a template
4368 * section edit link. If no flags are given, it was an ordinary section edit link.
4369 * This flag is required to avoid a section numbering mismatch when a section is
4370 * enclosed by <includeonly> (bug 6563).
4372 * The section number 0 pulls the text before the first heading; other numbers will
4373 * pull the given section along with its lower-level subsections. If the section is
4374 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4376 * @param string $mode One of "get" or "replace"
4377 * @param string $newText Replacement text for section data.
4378 * @return string for "get", the extracted section text.
4379 * for "replace", the whole page with the section replaced.
4381 private function extractSections( $text, $section, $mode, $newText='' ) {
4383 $this->clearState();
4384 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4385 $this->mOptions
= new ParserOptions
;
4386 $this->setOutputType( self
::OT_WIKI
);
4388 $frame = $this->getPreprocessor()->newFrame();
4390 // Process section extraction flags
4392 $sectionParts = explode( '-', $section );
4393 $sectionIndex = array_pop( $sectionParts );
4394 foreach ( $sectionParts as $part ) {
4395 if ( $part === 'T' ) {
4396 $flags |
= self
::PTD_FOR_INCLUSION
;
4399 // Preprocess the text
4400 $root = $this->preprocessToDom( $text, $flags );
4402 // <h> nodes indicate section breaks
4403 // They can only occur at the top level, so we can find them by iterating the root's children
4404 $node = $root->getFirstChild();
4406 // Find the target section
4407 if ( $sectionIndex == 0 ) {
4408 // Section zero doesn't nest, level=big
4409 $targetLevel = 1000;
4412 if ( $node->getName() === 'h' ) {
4413 $bits = $node->splitHeading();
4414 if ( $bits['i'] == $sectionIndex ) {
4415 $targetLevel = $bits['level'];
4419 if ( $mode === 'replace' ) {
4420 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4422 $node = $node->getNextSibling();
4428 if ( $mode === 'get' ) {
4435 // Find the end of the section, including nested sections
4437 if ( $node->getName() === 'h' ) {
4438 $bits = $node->splitHeading();
4439 $curLevel = $bits['level'];
4440 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4444 if ( $mode === 'get' ) {
4445 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4447 $node = $node->getNextSibling();
4450 // Write out the remainder (in replace mode only)
4451 if ( $mode === 'replace' ) {
4452 // Output the replacement text
4453 // Add two newlines on -- trailing whitespace in $newText is conventionally
4454 // stripped by the editor, so we need both newlines to restore the paragraph gap
4455 $outText .= $newText . "\n\n";
4457 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4458 $node = $node->getNextSibling();
4462 if ( is_string( $outText ) ) {
4463 // Re-insert stripped tags
4464 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4471 * This function returns the text of a section, specified by a number ($section).
4472 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4473 * the first section before any such heading (section 0).
4475 * If a section contains subsections, these are also returned.
4477 * @param string $text text to look in
4478 * @param string $section section identifier
4479 * @param string $deftext default to return if section is not found
4480 * @return string text of the requested section
4482 public function getSection( $text, $section, $deftext='' ) {
4483 return $this->extractSections( $text, $section, "get", $deftext );
4486 public function replaceSection( $oldtext, $section, $text ) {
4487 return $this->extractSections( $oldtext, $section, "replace", $text );
4491 * Get the timestamp associated with the current revision, adjusted for
4492 * the default server-local timestamp
4494 function getRevisionTimestamp() {
4495 if ( is_null( $this->mRevisionTimestamp
) ) {
4496 wfProfileIn( __METHOD__
);
4498 $dbr = wfGetDB( DB_SLAVE
);
4499 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4500 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4502 // Normalize timestamp to internal MW format for timezone processing.
4503 // This has the added side-effect of replacing a null value with
4504 // the current time, which gives us more sensible behavior for
4506 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4508 // The cryptic '' timezone parameter tells to use the site-default
4509 // timezone offset instead of the user settings.
4511 // Since this value will be saved into the parser cache, served
4512 // to other users, and potentially even used inside links and such,
4513 // it needs to be consistent for all visitors.
4514 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4516 wfProfileOut( __METHOD__
);
4518 return $this->mRevisionTimestamp
;
4522 * Mutator for $mDefaultSort
4524 * @param $sort New value
4526 public function setDefaultSort( $sort ) {
4527 $this->mDefaultSort
= $sort;
4531 * Accessor for $mDefaultSort
4532 * Will use the title/prefixed title if none is set
4536 public function getDefaultSort() {
4537 global $wgCategoryPrefixedDefaultSortkey;
4538 if( $this->mDefaultSort
!== false ) {
4539 return $this->mDefaultSort
;
4540 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4541 !$wgCategoryPrefixedDefaultSortkey) {
4542 return $this->mTitle
->getText();
4544 return $this->mTitle
->getPrefixedText();
4549 * Try to guess the section anchor name based on a wikitext fragment
4550 * presumably extracted from a heading, for example "Header" from
4553 public function guessSectionNameFromWikiText( $text ) {
4554 # Strip out wikitext links(they break the anchor)
4555 $text = $this->stripSectionName( $text );
4556 $headline = Sanitizer
::decodeCharReferences( $text );
4558 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4559 $headline = trim( $headline );
4560 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4561 $replacearray = array(
4566 array_keys( $replacearray ),
4567 array_values( $replacearray ),
4572 * Strips a text string of wikitext for use in a section anchor
4574 * Accepts a text string and then removes all wikitext from the
4575 * string and leaves only the resultant text (i.e. the result of
4576 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4577 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4578 * to create valid section anchors by mimicing the output of the
4579 * parser when headings are parsed.
4581 * @param $text string Text string to be stripped of wikitext
4582 * for use in a Section anchor
4583 * @return Filtered text string
4585 public function stripSectionName( $text ) {
4586 # Strip internal link markup
4587 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4588 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4590 # Strip external link markup (FIXME: Not Tolerant to blank link text
4591 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4592 # on how many empty links there are on the page - need to figure that out.
4593 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4595 # Parse wikitext quotes (italics & bold)
4596 $text = $this->doQuotes($text);
4599 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4603 function srvus( $text ) {
4604 return $this->testSrvus( $text, $this->mOutputType
);
4608 * strip/replaceVariables/unstrip for preprocessor regression testing
4610 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4611 $this->clearState();
4612 if ( ! ( $title instanceof Title
) ) {
4613 $title = Title
::newFromText( $title );
4615 $this->mTitle
= $title;
4616 $this->mOptions
= $options;
4617 $this->setOutputType( $outputType );
4618 $text = $this->replaceVariables( $text );
4619 $text = $this->mStripState
->unstripBoth( $text );
4620 $text = Sanitizer
::removeHTMLtags( $text );
4624 function testPst( $text, $title, $options ) {
4626 if ( ! ( $title instanceof Title
) ) {
4627 $title = Title
::newFromText( $title );
4629 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4632 function testPreprocess( $text, $title, $options ) {
4633 if ( ! ( $title instanceof Title
) ) {
4634 $title = Title
::newFromText( $title );
4636 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4639 function markerSkipCallback( $s, $callback ) {
4642 while ( $i < strlen( $s ) ) {
4643 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4644 if ( $markerStart === false ) {
4645 $out .= call_user_func( $callback, substr( $s, $i ) );
4648 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4649 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4650 if ( $markerEnd === false ) {
4651 $out .= substr( $s, $markerStart );
4654 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4655 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4665 * @todo document, briefly.
4669 var $general, $nowiki;
4671 function __construct() {
4672 $this->general
= new ReplacementArray
;
4673 $this->nowiki
= new ReplacementArray
;
4676 function unstripGeneral( $text ) {
4677 wfProfileIn( __METHOD__
);
4680 $text = $this->general
->replace( $text );
4681 } while ( $text != $oldText );
4682 wfProfileOut( __METHOD__
);
4686 function unstripNoWiki( $text ) {
4687 wfProfileIn( __METHOD__
);
4690 $text = $this->nowiki
->replace( $text );
4691 } while ( $text != $oldText );
4692 wfProfileOut( __METHOD__
);
4696 function unstripBoth( $text ) {
4697 wfProfileIn( __METHOD__
);
4700 $text = $this->general
->replace( $text );
4701 $text = $this->nowiki
->replace( $text );
4702 } while ( $text != $oldText );
4703 wfProfileOut( __METHOD__
);
4709 * @todo document, briefly.
4712 class OnlyIncludeReplacer
{
4715 function replace( $matches ) {
4716 if ( substr( $matches[1], -1 ) === "\n" ) {
4717 $this->output
.= substr( $matches[1], 0, -1 );
4719 $this->output
.= $matches[1];