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 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 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 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 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 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 function doAllQuotes( $text ) {
1074 wfProfileIn( __METHOD__
);
1076 $lines = StringUtils
::explode( "\n", $text );
1077 foreach ( $lines as $line ) {
1078 $outtext .= $this->doQuotes( $line ) . "\n";
1080 $outtext = substr($outtext, 0,-1);
1081 wfProfileOut( __METHOD__
);
1086 * Helper function for doAllQuotes()
1088 public 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')
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__
);
1526 wfProfileOut( __METHOD__
.'-setup' );
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 wfProfileOut( __METHOD__
."-image" );
1729 $this->mOutput
->addImage( $nt->getDBkey() );
1730 wfProfileOut( __METHOD__
."-image" );
1735 if ( $ns == NS_CATEGORY
) {
1736 wfProfileIn( __METHOD__
."-category" );
1737 $s = rtrim($s . "\n"); # bug 87
1740 $sortkey = $this->getDefaultSort();
1744 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1745 $sortkey = str_replace( "\n", '', $sortkey );
1746 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1747 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1750 * Strip the whitespace Category links produce, see bug 87
1751 * @todo We might want to use trim($tmp, "\n") here.
1753 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1755 wfProfileOut( __METHOD__
."-category" );
1760 # Self-link checking
1761 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1762 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1763 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1768 # Special and Media are pseudo-namespaces; no pages actually exist in them
1769 if( $ns == NS_MEDIA
) {
1770 # Give extensions a chance to select the file revision for us
1771 $skip = $time = false;
1772 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1774 $link = $sk->link( $nt );
1776 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1778 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1779 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1780 $this->mOutput
->addImage( $nt->getDBkey() );
1782 } elseif( $ns == NS_SPECIAL
) {
1783 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1786 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1789 } elseif( $ns == NS_IMAGE
) {
1790 $img = wfFindFile( $nt );
1792 // Force a blue link if the file exists; may be a remote
1793 // upload on the shared repository, and we want to see its
1794 // auto-generated page.
1795 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1796 $this->mOutput
->addLink( $nt );
1800 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1802 wfProfileOut( __METHOD__
);
1807 * Make a link placeholder. The text returned can be later resolved to a real link with
1808 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1809 * parsing of interwiki links, and secondly to allow all existence checks and
1810 * article length checks (for stub links) to be bundled into a single query.
1814 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1815 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1819 * Render a forced-blue link inline; protect against double expansion of
1820 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1821 * Since this little disaster has to split off the trail text to avoid
1822 * breaking URLs in the following text without breaking trails on the
1823 * wiki links, it's been made into a horrible function.
1826 * @param string $text
1827 * @param string $query
1828 * @param string $trail
1829 * @param string $prefix
1830 * @return string HTML-wikitext mix oh yuck
1832 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1833 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1834 $sk = $this->mOptions
->getSkin();
1835 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1836 return $this->armorLinks( $link ) . $trail;
1840 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1841 * going to go through further parsing steps before inline URL expansion.
1843 * In particular this is important when using action=render, which causes
1844 * full URLs to be included.
1846 * Oh man I hate our multi-layer parser!
1848 * @param string more-or-less HTML
1849 * @return string less-or-more HTML with NOPARSE bits
1851 function armorLinks( $text ) {
1852 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1853 "{$this->mUniqPrefix}NOPARSE$1", $text );
1857 * Return true if subpage links should be expanded on this page.
1860 function areSubpagesAllowed() {
1861 # Some namespaces don't allow subpages
1862 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1866 * Handle link to subpage if necessary
1867 * @param string $target the source of the link
1868 * @param string &$text the link text, modified as necessary
1869 * @return string the full name of the link
1872 function maybeDoSubpageLink($target, &$text) {
1875 # :Foobar -- override special treatment of prefix (images, language links)
1876 # /Foobar -- convert to CurrentPage/Foobar
1877 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1878 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1879 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1881 wfProfileIn( __METHOD__
);
1882 $ret = $target; # default return value is no change
1884 # Some namespaces don't allow subpages,
1885 # so only perform processing if subpages are allowed
1886 if( $this->areSubpagesAllowed() ) {
1887 $hash = strpos( $target, '#' );
1888 if( $hash !== false ) {
1889 $suffix = substr( $target, $hash );
1890 $target = substr( $target, 0, $hash );
1895 $target = trim( $target );
1896 # Look at the first character
1897 if( $target != '' && $target{0} == '/' ) {
1898 # / at end means we don't want the slash to be shown
1900 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1901 if( $trailingSlashes ) {
1902 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1904 $noslash = substr( $target, 1 );
1907 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1908 if( '' === $text ) {
1909 $text = $target . $suffix;
1910 } # this might be changed for ugliness reasons
1912 # check for .. subpage backlinks
1914 $nodotdot = $target;
1915 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1917 $nodotdot = substr( $nodotdot, 3 );
1919 if($dotdotcount > 0) {
1920 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1921 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1922 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1923 # / at the end means don't show full path
1924 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1925 $nodotdot = substr( $nodotdot, 0, -1 );
1926 if( '' === $text ) {
1927 $text = $nodotdot . $suffix;
1930 $nodotdot = trim( $nodotdot );
1931 if( $nodotdot != '' ) {
1932 $ret .= '/' . $nodotdot;
1940 wfProfileOut( __METHOD__
);
1945 * Used by doBlockLevels()
1948 /* private */ function closeParagraph() {
1950 if ( '' != $this->mLastSection
) {
1951 $result = '</' . $this->mLastSection
. ">\n";
1953 $this->mInPre
= false;
1954 $this->mLastSection
= '';
1957 # getCommon() returns the length of the longest common substring
1958 # of both arguments, starting at the beginning of both.
1960 /* private */ function getCommon( $st1, $st2 ) {
1961 $fl = strlen( $st1 );
1962 $shorter = strlen( $st2 );
1963 if ( $fl < $shorter ) { $shorter = $fl; }
1965 for ( $i = 0; $i < $shorter; ++
$i ) {
1966 if ( $st1{$i} != $st2{$i} ) { break; }
1970 # These next three functions open, continue, and close the list
1971 # element appropriate to the prefix character passed into them.
1973 /* private */ function openList( $char ) {
1974 $result = $this->closeParagraph();
1976 if ( '*' == $char ) { $result .= '<ul><li>'; }
1977 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1978 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1979 else if ( ';' == $char ) {
1980 $result .= '<dl><dt>';
1981 $this->mDTopen
= true;
1983 else { $result = '<!-- ERR 1 -->'; }
1988 /* private */ function nextItem( $char ) {
1989 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1990 else if ( ':' == $char ||
';' == $char ) {
1992 if ( $this->mDTopen
) { $close = '</dt>'; }
1993 if ( ';' == $char ) {
1994 $this->mDTopen
= true;
1995 return $close . '<dt>';
1997 $this->mDTopen
= false;
1998 return $close . '<dd>';
2001 return '<!-- ERR 2 -->';
2004 /* private */ function closeList( $char ) {
2005 if ( '*' == $char ) { $text = '</li></ul>'; }
2006 else if ( '#' == $char ) { $text = '</li></ol>'; }
2007 else if ( ':' == $char ) {
2008 if ( $this->mDTopen
) {
2009 $this->mDTopen
= false;
2010 $text = '</dt></dl>';
2012 $text = '</dd></dl>';
2015 else { return '<!-- ERR 3 -->'; }
2021 * Make lists from lines starting with ':', '*', '#', etc.
2024 * @return string the lists rendered as HTML
2026 function doBlockLevels( $text, $linestart ) {
2027 wfProfileIn( __METHOD__
);
2029 # Parsing through the text line by line. The main thing
2030 # happening here is handling of block-level elements p, pre,
2031 # and making lists from lines starting with * # : etc.
2033 $textLines = StringUtils
::explode( "\n", $text );
2035 $lastPrefix = $output = '';
2036 $this->mDTopen
= $inBlockElem = false;
2038 $paragraphStack = false;
2040 foreach ( $textLines as $oLine ) {
2042 if ( !$linestart ) {
2048 $lastPrefixLength = strlen( $lastPrefix );
2049 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2050 $preOpenMatch = preg_match('/<pre/i', $oLine );
2051 if ( !$this->mInPre
) {
2052 # Multiple prefixes may abut each other for nested lists.
2053 $prefixLength = strspn( $oLine, '*#:;' );
2054 $prefix = substr( $oLine, 0, $prefixLength );
2057 $prefix2 = str_replace( ';', ':', $prefix );
2058 $t = substr( $oLine, $prefixLength );
2059 $this->mInPre
= (bool)$preOpenMatch;
2061 # Don't interpret any other prefixes in preformatted text
2063 $prefix = $prefix2 = '';
2068 if( $prefixLength && $lastPrefix === $prefix2 ) {
2069 # Same as the last item, so no need to deal with nesting or opening stuff
2070 $output .= $this->nextItem( substr( $prefix, -1 ) );
2071 $paragraphStack = false;
2073 if ( substr( $prefix, -1 ) == ';') {
2074 # The one nasty exception: definition lists work like this:
2075 # ; title : definition text
2076 # So we check for : in the remainder text to split up the
2077 # title and definition, without b0rking links.
2079 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2081 $output .= $term . $this->nextItem( ':' );
2084 } elseif( $prefixLength ||
$lastPrefixLength ) {
2085 # Either open or close a level...
2086 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2087 $paragraphStack = false;
2089 while( $commonPrefixLength < $lastPrefixLength ) {
2090 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2091 --$lastPrefixLength;
2093 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2094 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2096 while ( $prefixLength > $commonPrefixLength ) {
2097 $char = substr( $prefix, $commonPrefixLength, 1 );
2098 $output .= $this->openList( $char );
2100 if ( ';' == $char ) {
2101 # FIXME: This is dupe of code above
2102 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2104 $output .= $term . $this->nextItem( ':' );
2107 ++
$commonPrefixLength;
2109 $lastPrefix = $prefix2;
2111 if( 0 == $prefixLength ) {
2112 wfProfileIn( __METHOD__
."-paragraph" );
2113 # No prefix (not in list)--go to paragraph mode
2114 // XXX: use a stack for nestable elements like span, table and div
2115 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2116 $closematch = preg_match(
2117 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2118 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2119 if ( $openmatch or $closematch ) {
2120 $paragraphStack = false;
2121 #Â TODO bug 5718: paragraph closed
2122 $output .= $this->closeParagraph();
2123 if ( $preOpenMatch and !$preCloseMatch ) {
2124 $this->mInPre
= true;
2126 if ( $closematch ) {
2127 $inBlockElem = false;
2129 $inBlockElem = true;
2131 } else if ( !$inBlockElem && !$this->mInPre
) {
2132 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2134 if ($this->mLastSection
!= 'pre') {
2135 $paragraphStack = false;
2136 $output .= $this->closeParagraph().'<pre>';
2137 $this->mLastSection
= 'pre';
2139 $t = substr( $t, 1 );
2142 if ( '' == trim($t) ) {
2143 if ( $paragraphStack ) {
2144 $output .= $paragraphStack.'<br />';
2145 $paragraphStack = false;
2146 $this->mLastSection
= 'p';
2148 if ($this->mLastSection
!= 'p' ) {
2149 $output .= $this->closeParagraph();
2150 $this->mLastSection
= '';
2151 $paragraphStack = '<p>';
2153 $paragraphStack = '</p><p>';
2157 if ( $paragraphStack ) {
2158 $output .= $paragraphStack;
2159 $paragraphStack = false;
2160 $this->mLastSection
= 'p';
2161 } else if ($this->mLastSection
!= 'p') {
2162 $output .= $this->closeParagraph().'<p>';
2163 $this->mLastSection
= 'p';
2168 wfProfileOut( __METHOD__
."-paragraph" );
2170 // somewhere above we forget to get out of pre block (bug 785)
2171 if($preCloseMatch && $this->mInPre
) {
2172 $this->mInPre
= false;
2174 if ($paragraphStack === false) {
2178 while ( $prefixLength ) {
2179 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2182 if ( '' != $this->mLastSection
) {
2183 $output .= '</' . $this->mLastSection
. '>';
2184 $this->mLastSection
= '';
2187 wfProfileOut( __METHOD__
);
2192 * Split up a string on ':', ignoring any occurences inside tags
2193 * to prevent illegal overlapping.
2194 * @param string $str the string to split
2195 * @param string &$before set to everything before the ':'
2196 * @param string &$after set to everything after the ':'
2197 * return string the position of the ':', or false if none found
2199 function findColonNoLinks($str, &$before, &$after) {
2200 wfProfileIn( __METHOD__
);
2202 $pos = strpos( $str, ':' );
2203 if( $pos === false ) {
2205 wfProfileOut( __METHOD__
);
2209 $lt = strpos( $str, '<' );
2210 if( $lt === false ||
$lt > $pos ) {
2211 // Easy; no tag nesting to worry about
2212 $before = substr( $str, 0, $pos );
2213 $after = substr( $str, $pos+
1 );
2214 wfProfileOut( __METHOD__
);
2218 // Ugly state machine to walk through avoiding tags.
2219 $state = self
::COLON_STATE_TEXT
;
2221 $len = strlen( $str );
2222 for( $i = 0; $i < $len; $i++
) {
2226 // (Using the number is a performance hack for common cases)
2227 case 0: // self::COLON_STATE_TEXT:
2230 // Could be either a <start> tag or an </end> tag
2231 $state = self
::COLON_STATE_TAGSTART
;
2236 $before = substr( $str, 0, $i );
2237 $after = substr( $str, $i +
1 );
2238 wfProfileOut( __METHOD__
);
2241 // Embedded in a tag; don't break it.
2244 // Skip ahead looking for something interesting
2245 $colon = strpos( $str, ':', $i );
2246 if( $colon === false ) {
2247 // Nothing else interesting
2248 wfProfileOut( __METHOD__
);
2251 $lt = strpos( $str, '<', $i );
2252 if( $stack === 0 ) {
2253 if( $lt === false ||
$colon < $lt ) {
2255 $before = substr( $str, 0, $colon );
2256 $after = substr( $str, $colon +
1 );
2257 wfProfileOut( __METHOD__
);
2261 if( $lt === false ) {
2262 // Nothing else interesting to find; abort!
2263 // We're nested, but there's no close tags left. Abort!
2266 // Skip ahead to next tag start
2268 $state = self
::COLON_STATE_TAGSTART
;
2271 case 1: // self::COLON_STATE_TAG:
2276 $state = self
::COLON_STATE_TEXT
;
2279 // Slash may be followed by >?
2280 $state = self
::COLON_STATE_TAGSLASH
;
2286 case 2: // self::COLON_STATE_TAGSTART:
2289 $state = self
::COLON_STATE_CLOSETAG
;
2292 $state = self
::COLON_STATE_COMMENT
;
2295 // Illegal early close? This shouldn't happen D:
2296 $state = self
::COLON_STATE_TEXT
;
2299 $state = self
::COLON_STATE_TAG
;
2302 case 3: // self::COLON_STATE_CLOSETAG:
2307 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2308 wfProfileOut( __METHOD__
);
2311 $state = self
::COLON_STATE_TEXT
;
2314 case self
::COLON_STATE_TAGSLASH
:
2316 // Yes, a self-closed tag <blah/>
2317 $state = self
::COLON_STATE_TEXT
;
2319 // Probably we're jumping the gun, and this is an attribute
2320 $state = self
::COLON_STATE_TAG
;
2323 case 5: // self::COLON_STATE_COMMENT:
2325 $state = self
::COLON_STATE_COMMENTDASH
;
2328 case self
::COLON_STATE_COMMENTDASH
:
2330 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2332 $state = self
::COLON_STATE_COMMENT
;
2335 case self
::COLON_STATE_COMMENTDASHDASH
:
2337 $state = self
::COLON_STATE_TEXT
;
2339 $state = self
::COLON_STATE_COMMENT
;
2343 throw new MWException( "State machine error in " . __METHOD__
);
2347 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2350 wfProfileOut( __METHOD__
);
2355 * Return value of a magic variable (like PAGENAME)
2359 function getVariableValue( $index ) {
2360 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2363 * Some of these require message or data lookups and can be
2364 * expensive to check many times.
2366 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2367 if ( isset( $this->mVarCache
[$index] ) ) {
2368 return $this->mVarCache
[$index];
2372 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2373 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2376 global $wgLocaltimezone;
2377 if ( isset( $wgLocaltimezone ) ) {
2378 $oldtz = getenv( 'TZ' );
2379 putenv( 'TZ='.$wgLocaltimezone );
2382 wfSuppressWarnings(); // E_STRICT system time bitching
2383 $localTimestamp = date( 'YmdHis', $ts );
2384 $localMonth = date( 'm', $ts );
2385 $localMonthName = date( 'n', $ts );
2386 $localDay = date( 'j', $ts );
2387 $localDay2 = date( 'd', $ts );
2388 $localDayOfWeek = date( 'w', $ts );
2389 $localWeek = date( 'W', $ts );
2390 $localYear = date( 'Y', $ts );
2391 $localHour = date( 'H', $ts );
2392 if ( isset( $wgLocaltimezone ) ) {
2393 putenv( 'TZ='.$oldtz );
2395 wfRestoreWarnings();
2398 case 'currentmonth':
2399 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2400 case 'currentmonthname':
2401 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2402 case 'currentmonthnamegen':
2403 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2404 case 'currentmonthabbrev':
2405 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2407 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2409 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2411 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2412 case 'localmonthname':
2413 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2414 case 'localmonthnamegen':
2415 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2416 case 'localmonthabbrev':
2417 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2419 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2421 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2423 return wfEscapeWikiText( $this->mTitle
->getText() );
2425 return $this->mTitle
->getPartialURL();
2426 case 'fullpagename':
2427 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2428 case 'fullpagenamee':
2429 return $this->mTitle
->getPrefixedURL();
2431 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2432 case 'subpagenamee':
2433 return $this->mTitle
->getSubpageUrlForm();
2434 case 'basepagename':
2435 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2436 case 'basepagenamee':
2437 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2438 case 'talkpagename':
2439 if( $this->mTitle
->canTalk() ) {
2440 $talkPage = $this->mTitle
->getTalkPage();
2441 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2445 case 'talkpagenamee':
2446 if( $this->mTitle
->canTalk() ) {
2447 $talkPage = $this->mTitle
->getTalkPage();
2448 return $talkPage->getPrefixedUrl();
2452 case 'subjectpagename':
2453 $subjPage = $this->mTitle
->getSubjectPage();
2454 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2455 case 'subjectpagenamee':
2456 $subjPage = $this->mTitle
->getSubjectPage();
2457 return $subjPage->getPrefixedUrl();
2459 // Let the edit saving system know we should parse the page
2460 // *after* a revision ID has been assigned.
2461 $this->mOutput
->setFlag( 'vary-revision' );
2462 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2463 return $this->mRevisionId
;
2465 // Let the edit saving system know we should parse the page
2466 // *after* a revision ID has been assigned. This is for null edits.
2467 $this->mOutput
->setFlag( 'vary-revision' );
2468 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2469 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2470 case 'revisionday2':
2471 // Let the edit saving system know we should parse the page
2472 // *after* a revision ID has been assigned. This is for null edits.
2473 $this->mOutput
->setFlag( 'vary-revision' );
2474 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2475 return substr( $this->getRevisionTimestamp(), 6, 2 );
2476 case 'revisionmonth':
2477 // Let the edit saving system know we should parse the page
2478 // *after* a revision ID has been assigned. This is for null edits.
2479 $this->mOutput
->setFlag( 'vary-revision' );
2480 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2481 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2482 case 'revisionyear':
2483 // Let the edit saving system know we should parse the page
2484 // *after* a revision ID has been assigned. This is for null edits.
2485 $this->mOutput
->setFlag( 'vary-revision' );
2486 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2487 return substr( $this->getRevisionTimestamp(), 0, 4 );
2488 case 'revisiontimestamp':
2489 // Let the edit saving system know we should parse the page
2490 // *after* a revision ID has been assigned. This is for null edits.
2491 $this->mOutput
->setFlag( 'vary-revision' );
2492 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2493 return $this->getRevisionTimestamp();
2495 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2497 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2499 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2501 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2502 case 'subjectspace':
2503 return $this->mTitle
->getSubjectNsText();
2504 case 'subjectspacee':
2505 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2506 case 'currentdayname':
2507 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2509 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2511 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2513 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2515 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2516 // int to remove the padding
2517 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2519 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2520 case 'localdayname':
2521 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2523 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2525 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2527 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2529 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2530 // int to remove the padding
2531 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2534 case 'numberofarticles':
2535 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2536 case 'numberoffiles':
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2538 case 'numberofusers':
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2540 case 'numberofpages':
2541 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2542 case 'numberofadmins':
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2544 case 'numberofedits':
2545 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2546 case 'currenttimestamp':
2547 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2548 case 'localtimestamp':
2549 return $this->mVarCache
[$index] = $localTimestamp;
2550 case 'currentversion':
2551 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2557 return $wgServerName;
2559 return $wgScriptPath;
2560 case 'directionmark':
2561 return $wgContLang->getDirMark();
2562 case 'contentlanguage':
2563 global $wgContLanguageCode;
2564 return $wgContLanguageCode;
2567 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2575 * initialise the magic variables (like CURRENTMONTHNAME)
2579 function initialiseVariables() {
2580 wfProfileIn( __METHOD__
);
2581 $variableIDs = MagicWord
::getVariableIDs();
2583 $this->mVariables
= new MagicWordArray( $variableIDs );
2584 wfProfileOut( __METHOD__
);
2588 * Preprocess some wikitext and return the document tree.
2589 * This is the ghost of replace_variables().
2591 * @param string $text The text to parse
2592 * @param integer flags Bitwise combination of:
2593 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2594 * included. Default is to assume a direct page view.
2596 * The generated DOM tree must depend only on the input text and the flags.
2597 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2599 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2600 * change in the DOM tree for a given text, must be passed through the section identifier
2601 * in the section edit link and thus back to extractSections().
2603 * The output of this function is currently only cached in process memory, but a persistent
2604 * cache may be implemented at a later date which takes further advantage of these strict
2605 * dependency requirements.
2609 function preprocessToDom ( $text, $flags = 0 ) {
2610 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2615 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2617 public static function splitWhitespace( $s ) {
2618 $ltrimmed = ltrim( $s );
2619 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2620 $trimmed = rtrim( $ltrimmed );
2621 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2623 $w2 = substr( $ltrimmed, -$diff );
2627 return array( $w1, $trimmed, $w2 );
2631 * Replace magic variables, templates, and template arguments
2632 * with the appropriate text. Templates are substituted recursively,
2633 * taking care to avoid infinite loops.
2635 * Note that the substitution depends on value of $mOutputType:
2636 * self::OT_WIKI: only {{subst:}} templates
2637 * self::OT_PREPROCESS: templates but not extension tags
2638 * self::OT_HTML: all templates and extension tags
2640 * @param string $tex The text to transform
2641 * @param PPFrame $frame Object describing the arguments passed to the template.
2642 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2643 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2644 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2647 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2648 # Prevent too big inclusions
2649 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2653 wfProfileIn( __METHOD__
);
2655 if ( $frame === false ) {
2656 $frame = $this->getPreprocessor()->newFrame();
2657 } elseif ( !( $frame instanceof PPFrame
) ) {
2658 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2659 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2662 $dom = $this->preprocessToDom( $text );
2663 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2664 $text = $frame->expand( $dom, $flags );
2666 wfProfileOut( __METHOD__
);
2670 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2671 static function createAssocArgs( $args ) {
2672 $assocArgs = array();
2674 foreach( $args as $arg ) {
2675 $eqpos = strpos( $arg, '=' );
2676 if ( $eqpos === false ) {
2677 $assocArgs[$index++
] = $arg;
2679 $name = trim( substr( $arg, 0, $eqpos ) );
2680 $value = trim( substr( $arg, $eqpos+
1 ) );
2681 if ( $value === false ) {
2684 if ( $name !== false ) {
2685 $assocArgs[$name] = $value;
2694 * Warn the user when a parser limitation is reached
2695 * Will warn at most once the user per limitation type
2697 * @param string $limitationType, should be one of:
2698 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2699 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2700 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2701 * @params int $current, $max When an explicit limit has been
2702 * exceeded, provide the values (optional)
2704 function limitationWarn( $limitationType, $current=null, $max=null) {
2705 $msgName = $limitationType . '-warning';
2706 //does no harm if $current and $max are present but are unnecessary for the message
2707 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2708 $this->mOutput
->addWarning( $warning );
2709 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2711 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2716 * Return the text of a template, after recursively
2717 * replacing any variables or templates within the template.
2719 * @param array $piece The parts of the template
2720 * $piece['title']: the title, i.e. the part before the |
2721 * $piece['parts']: the parameter array
2722 * $piece['lineStart']: whether the brace was at the start of a line
2723 * @param PPFrame The current frame, contains template arguments
2724 * @return string the text of the template
2727 function braceSubstitution( $piece, $frame ) {
2728 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2729 wfProfileIn( __METHOD__
);
2730 wfProfileIn( __METHOD__
.'-setup' );
2733 $found = false; # $text has been filled
2734 $nowiki = false; # wiki markup in $text should be escaped
2735 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2736 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2737 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2738 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2740 # Title object, where $text came from
2743 # $part1 is the bit before the first |, and must contain only title characters.
2744 # Various prefixes will be stripped from it later.
2745 $titleWithSpaces = $frame->expand( $piece['title'] );
2746 $part1 = trim( $titleWithSpaces );
2749 # Original title text preserved for various purposes
2750 $originalTitle = $part1;
2752 # $args is a list of argument nodes, starting from index 0, not including $part1
2753 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2754 wfProfileOut( __METHOD__
.'-setup' );
2757 wfProfileIn( __METHOD__
.'-modifiers' );
2759 $mwSubst = MagicWord
::get( 'subst' );
2760 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2761 # One of two possibilities is true:
2762 # 1) Found SUBST but not in the PST phase
2763 # 2) Didn't find SUBST and in the PST phase
2764 # In either case, return without further processing
2765 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2772 if ( !$found && $args->getLength() == 0 ) {
2773 $id = $this->mVariables
->matchStartToEnd( $part1 );
2774 if ( $id !== false ) {
2775 $text = $this->getVariableValue( $id );
2776 if (MagicWord
::getCacheTTL($id)>-1)
2777 $this->mOutput
->mContainsOldMagic
= true;
2782 # MSG, MSGNW and RAW
2785 $mwMsgnw = MagicWord
::get( 'msgnw' );
2786 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2789 # Remove obsolete MSG:
2790 $mwMsg = MagicWord
::get( 'msg' );
2791 $mwMsg->matchStartAndRemove( $part1 );
2795 $mwRaw = MagicWord
::get( 'raw' );
2796 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2797 $forceRawInterwiki = true;
2800 wfProfileOut( __METHOD__
.'-modifiers' );
2804 wfProfileIn( __METHOD__
. '-pfunc' );
2806 $colonPos = strpos( $part1, ':' );
2807 if ( $colonPos !== false ) {
2808 # Case sensitive functions
2809 $function = substr( $part1, 0, $colonPos );
2810 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2811 $function = $this->mFunctionSynonyms
[1][$function];
2813 # Case insensitive functions
2814 $function = strtolower( $function );
2815 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2816 $function = $this->mFunctionSynonyms
[0][$function];
2822 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2823 $initialArgs = array( &$this );
2824 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2825 if ( $flags & SFH_OBJECT_ARGS
) {
2826 # Add a frame parameter, and pass the arguments as an array
2827 $allArgs = $initialArgs;
2828 $allArgs[] = $frame;
2829 for ( $i = 0; $i < $args->getLength(); $i++
) {
2830 $funcArgs[] = $args->item( $i );
2832 $allArgs[] = $funcArgs;
2834 # Convert arguments to plain text
2835 for ( $i = 0; $i < $args->getLength(); $i++
) {
2836 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2838 $allArgs = array_merge( $initialArgs, $funcArgs );
2841 # Workaround for PHP bug 35229 and similar
2842 if ( !is_callable( $callback ) ) {
2843 throw new MWException( "Tag hook for $name is not callable\n" );
2845 $result = call_user_func_array( $callback, $allArgs );
2848 $preprocessFlags = 0;
2850 if ( is_array( $result ) ) {
2851 if ( isset( $result[0] ) ) {
2853 unset( $result[0] );
2856 // Extract flags into the local scope
2857 // This allows callers to set flags such as nowiki, found, etc.
2863 $text = $this->preprocessToDom( $text, $preprocessFlags );
2868 wfProfileOut( __METHOD__
. '-pfunc' );
2871 # Finish mangling title and then check for loops.
2872 # Set $title to a Title object and $titleText to the PDBK
2875 # Split the title into page and subpage
2877 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2878 if ($subpage !== '') {
2879 $ns = $this->mTitle
->getNamespace();
2881 $title = Title
::newFromText( $part1, $ns );
2883 $titleText = $title->getPrefixedText();
2884 # Check for language variants if the template is not found
2885 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2886 $wgContLang->findVariantLink($part1, $title);
2888 # Do infinite loop check
2889 if ( !$frame->loopCheck( $title ) ) {
2891 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2892 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2894 # Do recursion depth check
2895 $limit = $this->mOptions
->getMaxTemplateDepth();
2896 if ( $frame->depth
>= $limit ) {
2898 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2903 # Load from database
2904 if ( !$found && $title ) {
2905 wfProfileIn( __METHOD__
. '-loadtpl' );
2906 if ( !$title->isExternal() ) {
2907 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2908 $text = SpecialPage
::capturePath( $title );
2909 if ( is_string( $text ) ) {
2912 $this->disableCache();
2914 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2915 $found = false; //access denied
2916 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2918 list( $text, $title ) = $this->getTemplateDom( $title );
2919 if ( $text !== false ) {
2925 # If the title is valid but undisplayable, make a link to it
2926 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2927 $text = "[[:$titleText]]";
2930 } elseif ( $title->isTrans() ) {
2931 // Interwiki transclusion
2932 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2933 $text = $this->interwikiTransclude( $title, 'render' );
2936 $text = $this->interwikiTransclude( $title, 'raw' );
2937 // Preprocess it like a template
2938 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2943 wfProfileOut( __METHOD__
. '-loadtpl' );
2946 # If we haven't found text to substitute by now, we're done
2947 # Recover the source wikitext and return it
2949 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2950 wfProfileOut( __METHOD__
);
2951 return array( 'object' => $text );
2954 # Expand DOM-style return values in a child frame
2955 if ( $isChildObj ) {
2956 # Clean up argument array
2957 $newFrame = $frame->newChild( $args, $title );
2960 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2961 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2962 # Expansion is eligible for the empty-frame cache
2963 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2964 $text = $this->mTplExpandCache
[$titleText];
2966 $text = $newFrame->expand( $text );
2967 $this->mTplExpandCache
[$titleText] = $text;
2970 # Uncached expansion
2971 $text = $newFrame->expand( $text );
2974 if ( $isLocalObj && $nowiki ) {
2975 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2976 $isLocalObj = false;
2979 # Replace raw HTML by a placeholder
2980 # Add a blank line preceding, to prevent it from mucking up
2981 # immediately preceding headings
2983 $text = "\n\n" . $this->insertStripItem( $text );
2985 # Escape nowiki-style return values
2986 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2987 $text = wfEscapeWikiText( $text );
2989 # Bug 529: if the template begins with a table or block-level
2990 # element, it should be treated as beginning a new line.
2991 # This behaviour is somewhat controversial.
2992 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2993 $text = "\n" . $text;
2996 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2997 # Error, oversize inclusion
2998 $text = "[[$originalTitle]]" .
2999 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3000 $this->limitationWarn( 'post-expand-template-inclusion' );
3003 if ( $isLocalObj ) {
3004 $ret = array( 'object' => $text );
3006 $ret = array( 'text' => $text );
3009 wfProfileOut( __METHOD__
);
3014 * Get the semi-parsed DOM representation of a template with a given title,
3015 * and its redirect destination title. Cached.
3017 function getTemplateDom( $title ) {
3018 $cacheTitle = $title;
3019 $titleText = $title->getPrefixedDBkey();
3021 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3022 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3023 $title = Title
::makeTitle( $ns, $dbk );
3024 $titleText = $title->getPrefixedDBkey();
3026 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3027 return array( $this->mTplDomCache
[$titleText], $title );
3030 // Cache miss, go to the database
3031 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3033 if ( $text === false ) {
3034 $this->mTplDomCache
[$titleText] = false;
3035 return array( false, $title );
3038 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3039 $this->mTplDomCache
[ $titleText ] = $dom;
3041 if (! $title->equals($cacheTitle)) {
3042 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3043 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3046 return array( $dom, $title );
3050 * Fetch the unparsed text of a template and register a reference to it.
3052 function fetchTemplateAndTitle( $title ) {
3053 $templateCb = $this->mOptions
->getTemplateCallback();
3054 $stuff = call_user_func( $templateCb, $title, $this );
3055 $text = $stuff['text'];
3056 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3057 if ( isset( $stuff['deps'] ) ) {
3058 foreach ( $stuff['deps'] as $dep ) {
3059 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3062 return array($text,$finalTitle);
3065 function fetchTemplate( $title ) {
3066 $rv = $this->fetchTemplateAndTitle($title);
3071 * Static function to get a template
3072 * Can be overridden via ParserOptions::setTemplateCallback().
3074 static function statelessFetchTemplate( $title, $parser=false ) {
3075 $text = $skip = false;
3076 $finalTitle = $title;
3079 // Loop to fetch the article, with up to 1 redirect
3080 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3081 # Give extensions a chance to select the revision instead
3082 $id = false; // Assume current
3083 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3089 'page_id' => $title->getArticleID(),
3093 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3094 $rev_id = $rev ?
$rev->getId() : 0;
3095 // If there is no current revision, there is no page
3096 if( $id === false && !$rev ) {
3097 $linkCache = LinkCache
::singleton();
3098 $linkCache->addBadLinkObj( $title );
3103 'page_id' => $title->getArticleID(),
3104 'rev_id' => $rev_id );
3107 $text = $rev->getText();
3108 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3110 $message = $wgLang->lcfirst( $title->getText() );
3111 $text = wfMsgForContentNoTrans( $message );
3112 if( wfEmptyMsg( $message, $text ) ) {
3119 if ( $text === false ) {
3123 $finalTitle = $title;
3124 $title = Title
::newFromRedirect( $text );
3128 'finalTitle' => $finalTitle,
3133 * Transclude an interwiki link.
3135 function interwikiTransclude( $title, $action ) {
3136 global $wgEnableScaryTranscluding;
3138 if (!$wgEnableScaryTranscluding)
3139 return wfMsg('scarytranscludedisabled');
3141 $url = $title->getFullUrl( "action=$action" );
3143 if (strlen($url) > 255)
3144 return wfMsg('scarytranscludetoolong');
3145 return $this->fetchScaryTemplateMaybeFromCache($url);
3148 function fetchScaryTemplateMaybeFromCache($url) {
3149 global $wgTranscludeCacheExpiry;
3150 $dbr = wfGetDB(DB_SLAVE
);
3151 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3152 array('tc_url' => $url));
3154 $time = $obj->tc_time
;
3155 $text = $obj->tc_contents
;
3156 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3161 $text = Http
::get($url);
3163 return wfMsg('scarytranscludefailed', $url);
3165 $dbw = wfGetDB(DB_MASTER
);
3166 $dbw->replace('transcache', array('tc_url'), array(
3168 'tc_time' => time(),
3169 'tc_contents' => $text));
3175 * Triple brace replacement -- used for template arguments
3178 function argSubstitution( $piece, $frame ) {
3179 wfProfileIn( __METHOD__
);
3182 $parts = $piece['parts'];
3183 $nameWithSpaces = $frame->expand( $piece['title'] );
3184 $argName = trim( $nameWithSpaces );
3186 $text = $frame->getArgument( $argName );
3187 if ( $text === false && $parts->getLength() > 0
3191 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3194 # No match in frame, use the supplied default
3195 $object = $parts->item( 0 )->getChildren();
3197 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3198 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3199 $this->limitationWarn( 'post-expand-template-argument' );
3202 if ( $text === false && $object === false ) {
3204 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3206 if ( $error !== false ) {
3209 if ( $object !== false ) {
3210 $ret = array( 'object' => $object );
3212 $ret = array( 'text' => $text );
3215 wfProfileOut( __METHOD__
);
3220 * Return the text to be used for a given extension tag.
3221 * This is the ghost of strip().
3223 * @param array $params Associative array of parameters:
3224 * name PPNode for the tag name
3225 * attr PPNode for unparsed text where tag attributes are thought to be
3226 * attributes Optional associative array of parsed attributes
3227 * inner Contents of extension element
3228 * noClose Original text did not have a close tag
3229 * @param PPFrame $frame
3231 function extensionSubstitution( $params, $frame ) {
3232 global $wgRawHtml, $wgContLang;
3234 $name = $frame->expand( $params['name'] );
3235 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3236 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3238 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3240 if ( $this->ot
['html'] ) {
3241 $name = strtolower( $name );
3243 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3244 if ( isset( $params['attributes'] ) ) {
3245 $attributes = $attributes +
$params['attributes'];
3253 throw new MWException( '<html> extension tag encountered unexpectedly' );
3256 $output = Xml
::escapeTagsOnly( $content );
3259 $output = $wgContLang->armourMath(
3260 MathRenderer
::renderMath( $content, $attributes ) );
3263 $output = $this->renderImageGallery( $content, $attributes );
3266 if( isset( $this->mTagHooks
[$name] ) ) {
3267 # Workaround for PHP bug 35229 and similar
3268 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3269 throw new MWException( "Tag hook for $name is not callable\n" );
3271 $output = call_user_func_array( $this->mTagHooks
[$name],
3272 array( $content, $attributes, $this ) );
3274 $output = '<span class="error">Invalid tag extension name: ' .
3275 htmlspecialchars( $name ) . '</span>';
3279 if ( is_null( $attrText ) ) {
3282 if ( isset( $params['attributes'] ) ) {
3283 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3284 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3285 htmlspecialchars( $attrValue ) . '"';
3288 if ( $content === null ) {
3289 $output = "<$name$attrText/>";
3291 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3292 $output = "<$name$attrText>$content$close";
3296 if ( $name == 'html' ||
$name == 'nowiki' ) {
3297 $this->mStripState
->nowiki
->setPair( $marker, $output );
3299 $this->mStripState
->general
->setPair( $marker, $output );
3305 * Increment an include size counter
3307 * @param string $type The type of expansion
3308 * @param integer $size The size of the text
3309 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3311 function incrementIncludeSize( $type, $size ) {
3312 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3315 $this->mIncludeSizes
[$type] +
= $size;
3321 * Increment the expensive function count
3323 * @return boolean False if the limit has been exceeded
3325 function incrementExpensiveFunctionCount() {
3326 global $wgExpensiveParserFunctionLimit;
3327 $this->mExpensiveFunctionCount++
;
3328 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3335 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3336 * Fills $this->mDoubleUnderscores, returns the modified text
3338 function doDoubleUnderscore( $text ) {
3339 // The position of __TOC__ needs to be recorded
3340 $mw = MagicWord
::get( 'toc' );
3341 if( $mw->match( $text ) ) {
3342 $this->mShowToc
= true;
3343 $this->mForceTocPosition
= true;
3345 // Set a placeholder. At the end we'll fill it in with the TOC.
3346 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3348 // Only keep the first one.
3349 $text = $mw->replace( '', $text );
3352 // Now match and remove the rest of them
3353 $mwa = MagicWord
::getDoubleUnderscoreArray();
3354 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3356 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3357 $this->mOutput
->mNoGallery
= true;
3359 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3360 $this->mShowToc
= false;
3362 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3363 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3365 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3366 if ( $containerCategory ) {
3367 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3369 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3372 # (bug 8068) Allow control over whether robots index a page.
3374 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3375 # is not desirable, the last one on the page should win.
3376 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3377 $this->mOutput
->setIndexPolicy( 'noindex' );
3378 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3379 $this->mOutput
->setIndexPolicy( 'index' );
3386 * This function accomplishes several tasks:
3387 * 1) Auto-number headings if that option is enabled
3388 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3389 * 3) Add a Table of contents on the top for users who have enabled the option
3390 * 4) Auto-anchor headings
3392 * It loops through all headlines, collects the necessary data, then splits up the
3393 * string and re-inserts the newly formatted headlines.
3395 * @param string $text
3396 * @param boolean $isMain
3399 function formatHeadings( $text, $isMain=true ) {
3400 global $wgMaxTocLevel, $wgContLang;
3402 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3403 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3406 $showEditLink = $this->mOptions
->getEditSection();
3409 # Inhibit editsection links if requested in the page
3410 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3414 # Get all headlines for numbering them and adding funky stuff like [edit]
3415 # links - this is for later, but we need the number of headlines right now
3417 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3419 # if there are fewer than 4 headlines in the article, do not show TOC
3420 # unless it's been explicitly enabled.
3421 $enoughToc = $this->mShowToc
&&
3422 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3424 # Allow user to stipulate that a page should have a "new section"
3425 # link added via __NEWSECTIONLINK__
3426 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3427 $this->mOutput
->setNewSection( true );
3430 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3431 # override above conditions and always show TOC above first header
3432 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3433 $this->mShowToc
= true;
3437 # We need this to perform operations on the HTML
3438 $sk = $this->mOptions
->getSkin();
3444 # Ugh .. the TOC should have neat indentation levels which can be
3445 # passed to the skin functions. These are determined here
3449 $sublevelCount = array();
3450 $levelCount = array();
3456 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3457 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3460 foreach( $matches[3] as $headline ) {
3461 $isTemplate = false;
3463 $sectionIndex = false;
3465 $markerMatches = array();
3466 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3467 $serial = $markerMatches[1];
3468 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3469 $isTemplate = ($titleText != $baseTitleText);
3470 $headline = preg_replace("/^$markerRegex/", "", $headline);
3474 $prevlevel = $level;
3475 $prevtoclevel = $toclevel;
3477 $level = $matches[1][$headlineCount];
3479 if( $doNumberHeadings ||
$enoughToc ) {
3481 if ( $level > $prevlevel ) {
3482 # Increase TOC level
3484 $sublevelCount[$toclevel] = 0;
3485 if( $toclevel<$wgMaxTocLevel ) {
3486 $prevtoclevel = $toclevel;
3487 $toc .= $sk->tocIndent();
3491 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3492 # Decrease TOC level, find level to jump to
3494 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3495 # Can only go down to level 1
3498 for ($i = $toclevel; $i > 0; $i--) {
3499 if ( $levelCount[$i] == $level ) {
3500 # Found last matching level
3504 elseif ( $levelCount[$i] < $level ) {
3505 # Found first matching level below current level
3511 if( $toclevel<$wgMaxTocLevel ) {
3512 if($prevtoclevel < $wgMaxTocLevel) {
3513 # Unindent only if the previous toc level was shown :p
3514 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3515 $prevtoclevel = $toclevel;
3517 $toc .= $sk->tocLineEnd();
3522 # No change in level, end TOC line
3523 if( $toclevel<$wgMaxTocLevel ) {
3524 $toc .= $sk->tocLineEnd();
3528 $levelCount[$toclevel] = $level;
3530 # count number of headlines for each level
3531 @$sublevelCount[$toclevel]++
;
3533 for( $i = 1; $i <= $toclevel; $i++
) {
3534 if( !empty( $sublevelCount[$i] ) ) {
3538 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3544 # The safe header is a version of the header text safe to use for links
3545 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3546 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3548 # Remove link placeholders by the link text.
3549 # <!--LINK number-->
3551 # link text with suffix
3552 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3554 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3555 $tocline = preg_replace(
3556 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3560 $tocline = trim( $tocline );
3562 # For the anchor, strip out HTML-y stuff period
3563 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3564 $safeHeadline = trim( $safeHeadline );
3566 # Save headline for section edit hint before it's escaped
3567 $headlineHint = $safeHeadline;
3568 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3569 # HTML names must be case-insensitively unique (bug 10721)
3570 $arrayKey = strtolower( $safeHeadline );
3572 # count how many in assoc. array so we can track dupes in anchors
3573 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3574 $refcount[$headlineCount] = $refers[$arrayKey];
3576 # Don't number the heading if it is the only one (looks silly)
3577 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3578 # the two are different if the line contains a link
3579 $headline=$numbering . ' ' . $headline;
3582 # Create the anchor for linking from the TOC to the section
3583 $anchor = $safeHeadline;
3584 if($refcount[$headlineCount] > 1 ) {
3585 $anchor .= '_' . $refcount[$headlineCount];
3587 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3588 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3589 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3591 # give headline the correct <h#> tag
3592 if( $showEditLink && $sectionIndex !== false ) {
3594 # Put a T flag in the section identifier, to indicate to extractSections()
3595 # that sections inside <includeonly> should be counted.
3596 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3598 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3603 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3608 $this->mOutput
->setSections( $tocraw );
3610 # Never ever show TOC if no headers
3611 if( $numVisible < 1 ) {
3616 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3617 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3619 $toc = $sk->tocList( $toc );
3622 # split up and insert constructed headlines
3624 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3627 foreach( $blocks as $block ) {
3628 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3629 # This is the [edit] link that appears for the top block of text when
3630 # section editing is enabled
3632 # Disabled because it broke block formatting
3633 # For example, a bullet point in the top line
3634 # $full .= $sk->editSectionLink(0);
3637 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3638 # Top anchor now in skin
3642 if( !empty( $head[$i] ) ) {
3647 if( $this->mForceTocPosition
) {
3648 return str_replace( '<!--MWTOC-->', $toc, $full );
3655 * Transform wiki markup when saving a page by doing \r\n -> \n
3656 * conversion, substitting signatures, {{subst:}} templates, etc.
3658 * @param string $text the text to transform
3659 * @param Title &$title the Title object for the current article
3660 * @param User &$user the User object describing the current user
3661 * @param ParserOptions $options parsing options
3662 * @param bool $clearState whether to clear the parser state first
3663 * @return string the altered wiki markup
3666 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3667 $this->mOptions
= $options;
3668 $this->setTitle( $title );
3669 $this->setOutputType( self
::OT_WIKI
);
3671 if ( $clearState ) {
3672 $this->clearState();
3678 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3679 $text = $this->pstPass2( $text, $user );
3680 $text = $this->mStripState
->unstripBoth( $text );
3685 * Pre-save transform helper function
3688 function pstPass2( $text, $user ) {
3689 global $wgContLang, $wgLocaltimezone;
3691 /* Note: This is the timestamp saved as hardcoded wikitext to
3692 * the database, we use $wgContLang here in order to give
3693 * everyone the same signature and use the default one rather
3694 * than the one selected in each user's preferences.
3696 * (see also bug 12815)
3698 $ts = $this->mOptions
->getTimestamp();
3699 $tz = wfMsgForContent( 'timezone-utc' );
3700 if ( isset( $wgLocaltimezone ) ) {
3701 $unixts = wfTimestamp( TS_UNIX
, $ts );
3702 $oldtz = getenv( 'TZ' );
3703 putenv( 'TZ='.$wgLocaltimezone );
3704 $ts = date( 'YmdHis', $unixts );
3705 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3706 putenv( 'TZ='.$oldtz );
3709 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3711 # Variable replacement
3712 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3713 $text = $this->replaceVariables( $text );
3716 $sigText = $this->getUserSig( $user );
3717 $text = strtr( $text, array(
3719 '~~~~' => "$sigText $d",
3723 # Context links: [[|name]] and [[name (context)|]]
3725 global $wgLegalTitleChars;
3726 $tc = "[$wgLegalTitleChars]";
3727 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3729 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3730 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3731 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3733 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3734 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3735 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3737 $t = $this->mTitle
->getText();
3739 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3740 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3741 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3742 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3744 # if there's no context, don't bother duplicating the title
3745 $text = preg_replace( $p2, '[[\\1]]', $text );
3748 # Trim trailing whitespace
3749 $text = rtrim( $text );
3755 * Fetch the user's signature text, if any, and normalize to
3756 * validated, ready-to-insert wikitext.
3762 function getUserSig( &$user ) {
3763 global $wgMaxSigChars;
3765 $username = $user->getName();
3766 $nickname = $user->getOption( 'nickname' );
3767 $nickname = $nickname === '' ?
$username : $nickname;
3769 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3770 $nickname = $username;
3771 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3772 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3773 # Sig. might contain markup; validate this
3774 if( $this->validateSig( $nickname ) !== false ) {
3775 # Validated; clean up (if needed) and return it
3776 return $this->cleanSig( $nickname, true );
3778 # Failed to validate; fall back to the default
3779 $nickname = $username;
3780 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3784 // Make sure nickname doesnt get a sig in a sig
3785 $nickname = $this->cleanSigInSig( $nickname );
3787 # If we're still here, make it a link to the user page
3788 $userText = wfEscapeWikiText( $username );
3789 $nickText = wfEscapeWikiText( $nickname );
3790 if ( $user->isAnon() ) {
3791 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3793 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3798 * Check that the user's signature contains no bad XML
3800 * @param string $text
3801 * @return mixed An expanded string, or false if invalid.
3803 function validateSig( $text ) {
3804 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3808 * Clean up signature text
3810 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3811 * 2) Substitute all transclusions
3813 * @param string $text
3814 * @param $parsing Whether we're cleaning (preferences save) or parsing
3815 * @return string Signature text
3817 function cleanSig( $text, $parsing = false ) {
3820 $this->clearState();
3821 $this->setTitle( $wgTitle );
3822 $this->mOptions
= new ParserOptions
;
3823 $this->setOutputType
= self
::OT_PREPROCESS
;
3826 # Option to disable this feature
3827 if ( !$this->mOptions
->getCleanSignatures() ) {
3831 # FIXME: regex doesn't respect extension tags or nowiki
3832 # => Move this logic to braceSubstitution()
3833 $substWord = MagicWord
::get( 'subst' );
3834 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3835 $substText = '{{' . $substWord->getSynonym( 0 );
3837 $text = preg_replace( $substRegex, $substText, $text );
3838 $text = $this->cleanSigInSig( $text );
3839 $dom = $this->preprocessToDom( $text );
3840 $frame = $this->getPreprocessor()->newFrame();
3841 $text = $frame->expand( $dom );
3844 $text = $this->mStripState
->unstripBoth( $text );
3851 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3852 * @param string $text
3853 * @return string Signature text with /~{3,5}/ removed
3855 function cleanSigInSig( $text ) {
3856 $text = preg_replace( '/~{3,5}/', '', $text );
3861 * Set up some variables which are usually set up in parse()
3862 * so that an external function can call some class members with confidence
3865 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3866 $this->setTitle( $title );
3867 $this->mOptions
= $options;
3868 $this->setOutputType( $outputType );
3869 if ( $clearState ) {
3870 $this->clearState();
3875 * Wrapper for preprocess()
3877 * @param string $text the text to preprocess
3878 * @param ParserOptions $options options
3882 function transformMsg( $text, $options ) {
3884 static $executing = false;
3886 # Guard against infinite recursion
3892 wfProfileIn(__METHOD__
);
3893 $text = $this->preprocess( $text, $wgTitle, $options );
3896 wfProfileOut(__METHOD__
);
3901 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3902 * The callback should have the following form:
3903 * function myParserHook( $text, $params, &$parser ) { ... }
3905 * Transform and return $text. Use $parser for any required context, e.g. use
3906 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3910 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3911 * @param mixed $callback The callback function (and object) to use for the tag
3913 * @return The old value of the mTagHooks array associated with the hook
3915 function setHook( $tag, $callback ) {
3916 $tag = strtolower( $tag );
3917 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3918 $this->mTagHooks
[$tag] = $callback;
3919 if( !in_array( $tag, $this->mStripList
) ) {
3920 $this->mStripList
[] = $tag;
3926 function setTransparentTagHook( $tag, $callback ) {
3927 $tag = strtolower( $tag );
3928 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3929 $this->mTransparentTagHooks
[$tag] = $callback;
3935 * Remove all tag hooks
3937 function clearTagHooks() {
3938 $this->mTagHooks
= array();
3939 $this->mStripList
= $this->mDefaultStripList
;
3943 * Create a function, e.g. {{sum:1|2|3}}
3944 * The callback function should have the form:
3945 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3947 * Or with SFH_OBJECT_ARGS:
3948 * function myParserFunction( $parser, $frame, $args ) { ... }
3950 * The callback may either return the text result of the function, or an array with the text
3951 * in element 0, and a number of flags in the other elements. The names of the flags are
3952 * specified in the keys. Valid flags are:
3953 * found The text returned is valid, stop processing the template. This
3955 * nowiki Wiki markup in the return value should be escaped
3956 * isHTML The returned text is HTML, armour it against wikitext transformation
3960 * @param string $id The magic word ID
3961 * @param mixed $callback The callback function (and object) to use
3962 * @param integer $flags a combination of the following flags:
3963 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3965 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3966 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3967 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3968 * the arguments, and to control the way they are expanded.
3970 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3971 * arguments, for instance:
3972 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3974 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3975 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3976 * working if/when this is changed.
3978 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3981 * Please read the documentation in includes/parser/Preprocessor.php for more information
3982 * about the methods available in PPFrame and PPNode.
3984 * @return The old callback function for this name, if any
3986 function setFunctionHook( $id, $callback, $flags = 0 ) {
3987 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3988 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3990 # Add to function cache
3991 $mw = MagicWord
::get( $id );
3993 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
3995 $synonyms = $mw->getSynonyms();
3996 $sensitive = intval( $mw->isCaseSensitive() );
3998 foreach ( $synonyms as $syn ) {
4000 if ( !$sensitive ) {
4001 $syn = strtolower( $syn );
4004 if ( !( $flags & SFH_NO_HASH
) ) {
4007 # Remove trailing colon
4008 if ( substr( $syn, -1, 1 ) == ':' ) {
4009 $syn = substr( $syn, 0, -1 );
4011 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4017 * Get all registered function hook identifiers
4021 function getFunctionHooks() {
4022 return array_keys( $this->mFunctionHooks
);
4026 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4027 * Placeholders created in Skin::makeLinkObj()
4028 * Returns an array of link CSS classes, indexed by PDBK.
4030 function replaceLinkHolders( &$text, $options = 0 ) {
4031 return $this->mLinkHolders
->replace( $text );
4035 * Replace <!--LINK--> link placeholders with plain text of links
4036 * (not HTML-formatted).
4037 * @param string $text
4040 function replaceLinkHoldersText( $text ) {
4041 return $this->mLinkHolders
->replaceText( $text );
4045 * Tag hook handler for 'pre'.
4047 function renderPreTag( $text, $attribs ) {
4048 // Backwards-compatibility hack
4049 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4051 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4052 return wfOpenElement( 'pre', $attribs ) .
4053 Xml
::escapeTagsOnly( $content ) .
4058 * Renders an image gallery from a text with one line per image.
4059 * text labels may be given by using |-style alternative text. E.g.
4060 * Image:one.jpg|The number "1"
4061 * Image:tree.jpg|A tree
4062 * given as text will return the HTML of a gallery with two images,
4063 * labeled 'The number "1"' and
4066 function renderImageGallery( $text, $params ) {
4067 $ig = new ImageGallery();
4068 $ig->setContextTitle( $this->mTitle
);
4069 $ig->setShowBytes( false );
4070 $ig->setShowFilename( false );
4071 $ig->setParser( $this );
4072 $ig->setHideBadImages();
4073 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4074 $ig->useSkin( $this->mOptions
->getSkin() );
4075 $ig->mRevisionId
= $this->mRevisionId
;
4077 if( isset( $params['caption'] ) ) {
4078 $caption = $params['caption'];
4079 $caption = htmlspecialchars( $caption );
4080 $caption = $this->replaceInternalLinks( $caption );
4081 $ig->setCaptionHtml( $caption );
4083 if( isset( $params['perrow'] ) ) {
4084 $ig->setPerRow( $params['perrow'] );
4086 if( isset( $params['widths'] ) ) {
4087 $ig->setWidths( $params['widths'] );
4089 if( isset( $params['heights'] ) ) {
4090 $ig->setHeights( $params['heights'] );
4093 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4095 $lines = StringUtils
::explode( "\n", $text );
4096 foreach ( $lines as $line ) {
4097 # match lines like these:
4098 # Image:someimage.jpg|This is some image
4100 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4102 if ( count( $matches ) == 0 ) {
4106 if ( strpos( $matches[0], '%' ) !== false )
4107 $matches[1] = urldecode( $matches[1] );
4108 $tp = Title
::newFromText( $matches[1], NS_IMAGE
);
4110 if( is_null( $nt ) ) {
4111 # Bogus title. Ignore these so we don't bomb out later.
4114 if ( isset( $matches[3] ) ) {
4115 $label = $matches[3];
4120 $html = $this->recursiveTagParse( trim( $label ) );
4122 $ig->add( $nt, $html );
4124 # Only add real images (bug #5586)
4125 if ( $nt->getNamespace() == NS_IMAGE
) {
4126 $this->mOutput
->addImage( $nt->getDBkey() );
4129 return $ig->toHTML();
4132 function getImageParams( $handler ) {
4134 $handlerClass = get_class( $handler );
4138 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4139 // Initialise static lists
4140 static $internalParamNames = array(
4141 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4142 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4143 'bottom', 'text-bottom' ),
4144 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4145 'upright', 'border' ),
4147 static $internalParamMap;
4148 if ( !$internalParamMap ) {
4149 $internalParamMap = array();
4150 foreach ( $internalParamNames as $type => $names ) {
4151 foreach ( $names as $name ) {
4152 $magicName = str_replace( '-', '_', "img_$name" );
4153 $internalParamMap[$magicName] = array( $type, $name );
4158 // Add handler params
4159 $paramMap = $internalParamMap;
4161 $handlerParamMap = $handler->getParamMap();
4162 foreach ( $handlerParamMap as $magic => $paramName ) {
4163 $paramMap[$magic] = array( 'handler', $paramName );
4166 $this->mImageParams
[$handlerClass] = $paramMap;
4167 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4169 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4173 * Parse image options text and use it to make an image
4174 * @param Title $title
4175 * @param string $options
4176 * @param LinkHolderArray $holders
4178 function makeImage( $title, $options, $holders = false ) {
4179 # Check if the options text is of the form "options|alt text"
4181 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4182 # * left no resizing, just left align. label is used for alt= only
4183 # * right same, but right aligned
4184 # * none same, but not aligned
4185 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4186 # * center center the image
4187 # * framed Keep original image size, no magnify-button.
4188 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4189 # * upright reduce width for upright images, rounded to full __0 px
4190 # * border draw a 1px border around the image
4191 # vertical-align values (no % or length right now):
4201 $parts = StringUtils
::explode( "|", $options );
4202 $sk = $this->mOptions
->getSkin();
4204 # Give extensions a chance to select the file revision for us
4205 $skip = $time = $descQuery = false;
4206 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4209 return $sk->link( $title );
4213 $file = wfFindFile( $title, $time );
4214 $handler = $file ?
$file->getHandler() : false;
4216 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4218 # Process the input parameters
4220 $params = array( 'frame' => array(), 'handler' => array(),
4221 'horizAlign' => array(), 'vertAlign' => array() );
4222 foreach( $parts as $part ) {
4223 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4225 if( isset( $paramMap[$magicName] ) ) {
4226 list( $type, $paramName ) = $paramMap[$magicName];
4228 // Special case; width and height come in one variable together
4229 if( $type == 'handler' && $paramName == 'width' ) {
4231 # (bug 13500) In both cases (width/height and width only),
4232 # permit trailing "px" for backward compatibility.
4233 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4234 $width = intval( $m[1] );
4235 $height = intval( $m[2] );
4236 if ( $handler->validateParam( 'width', $width ) ) {
4237 $params[$type]['width'] = $width;
4240 if ( $handler->validateParam( 'height', $height ) ) {
4241 $params[$type]['height'] = $height;
4244 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4245 $width = intval( $value );
4246 if ( $handler->validateParam( 'width', $width ) ) {
4247 $params[$type]['width'] = $width;
4250 } // else no validation -- bug 13436
4252 if ( $type == 'handler' ) {
4253 # Validate handler parameter
4254 $validated = $handler->validateParam( $paramName, $value );
4256 # Validate internal parameters
4257 switch( $paramName ) {
4259 /// @fixme - possibly check validity here?
4260 /// downstream behavior seems odd with missing manual thumbs.
4264 // Most other things appear to be empty or numeric...
4265 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4270 $params[$type][$paramName] = $value;
4274 if ( !$validated ) {
4279 # Process alignment parameters
4280 if ( $params['horizAlign'] ) {
4281 $params['frame']['align'] = key( $params['horizAlign'] );
4283 if ( $params['vertAlign'] ) {
4284 $params['frame']['valign'] = key( $params['vertAlign'] );
4287 # Strip bad stuff out of the alt text
4288 # We can't just use replaceLinkHoldersText() here, because if this function
4289 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4291 $alt = $holders->replaceText( $caption );
4293 $alt = $this->replaceLinkHoldersText( $caption );
4296 # make sure there are no placeholders in thumbnail attributes
4297 # that are later expanded to html- so expand them now and
4299 $alt = $this->mStripState
->unstripBoth( $alt );
4300 $alt = Sanitizer
::stripAllTags( $alt );
4302 $params['frame']['alt'] = $alt;
4303 $params['frame']['caption'] = $caption;
4305 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4307 # Linker does the rest
4308 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4310 # Give the handler a chance to modify the parser object
4312 $handler->parserTransformHook( $this, $file );
4319 * Set a flag in the output object indicating that the content is dynamic and
4320 * shouldn't be cached.
4322 function disableCache() {
4323 wfDebug( "Parser output marked as uncacheable.\n" );
4324 $this->mOutput
->mCacheTime
= -1;
4328 * Callback from the Sanitizer for expanding items found in HTML attribute
4329 * values, so they can be safely tested and escaped.
4330 * @param string $text
4331 * @param PPFrame $frame
4335 function attributeStripCallback( &$text, $frame = false ) {
4336 $text = $this->replaceVariables( $text, $frame );
4337 $text = $this->mStripState
->unstripBoth( $text );
4346 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4347 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4348 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4354 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4359 * Break wikitext input into sections, and either pull or replace
4360 * some particular section's text.
4362 * External callers should use the getSection and replaceSection methods.
4364 * @param string $text Page wikitext
4365 * @param string $section A section identifier string of the form:
4366 * <flag1> - <flag2> - ... - <section number>
4368 * Currently the only recognised flag is "T", which means the target section number
4369 * was derived during a template inclusion parse, in other words this is a template
4370 * section edit link. If no flags are given, it was an ordinary section edit link.
4371 * This flag is required to avoid a section numbering mismatch when a section is
4372 * enclosed by <includeonly> (bug 6563).
4374 * The section number 0 pulls the text before the first heading; other numbers will
4375 * pull the given section along with its lower-level subsections. If the section is
4376 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4378 * @param string $mode One of "get" or "replace"
4379 * @param string $newText Replacement text for section data.
4380 * @return string for "get", the extracted section text.
4381 * for "replace", the whole page with the section replaced.
4383 private function extractSections( $text, $section, $mode, $newText='' ) {
4385 $this->clearState();
4386 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4387 $this->mOptions
= new ParserOptions
;
4388 $this->setOutputType( self
::OT_WIKI
);
4390 $frame = $this->getPreprocessor()->newFrame();
4392 // Process section extraction flags
4394 $sectionParts = explode( '-', $section );
4395 $sectionIndex = array_pop( $sectionParts );
4396 foreach ( $sectionParts as $part ) {
4397 if ( $part == 'T' ) {
4398 $flags |
= self
::PTD_FOR_INCLUSION
;
4401 // Preprocess the text
4402 $root = $this->preprocessToDom( $text, $flags );
4404 // <h> nodes indicate section breaks
4405 // They can only occur at the top level, so we can find them by iterating the root's children
4406 $node = $root->getFirstChild();
4408 // Find the target section
4409 if ( $sectionIndex == 0 ) {
4410 // Section zero doesn't nest, level=big
4411 $targetLevel = 1000;
4414 if ( $node->getName() == 'h' ) {
4415 $bits = $node->splitHeading();
4416 if ( $bits['i'] == $sectionIndex ) {
4417 $targetLevel = $bits['level'];
4421 if ( $mode == 'replace' ) {
4422 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4424 $node = $node->getNextSibling();
4430 if ( $mode == 'get' ) {
4437 // Find the end of the section, including nested sections
4439 if ( $node->getName() == 'h' ) {
4440 $bits = $node->splitHeading();
4441 $curLevel = $bits['level'];
4442 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4446 if ( $mode == 'get' ) {
4447 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4449 $node = $node->getNextSibling();
4452 // Write out the remainder (in replace mode only)
4453 if ( $mode == 'replace' ) {
4454 // Output the replacement text
4455 // Add two newlines on -- trailing whitespace in $newText is conventionally
4456 // stripped by the editor, so we need both newlines to restore the paragraph gap
4457 $outText .= $newText . "\n\n";
4459 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4460 $node = $node->getNextSibling();
4464 if ( is_string( $outText ) ) {
4465 // Re-insert stripped tags
4466 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4473 * This function returns the text of a section, specified by a number ($section).
4474 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4475 * the first section before any such heading (section 0).
4477 * If a section contains subsections, these are also returned.
4479 * @param string $text text to look in
4480 * @param string $section section identifier
4481 * @param string $deftext default to return if section is not found
4482 * @return string text of the requested section
4484 public function getSection( $text, $section, $deftext='' ) {
4485 return $this->extractSections( $text, $section, "get", $deftext );
4488 public function replaceSection( $oldtext, $section, $text ) {
4489 return $this->extractSections( $oldtext, $section, "replace", $text );
4493 * Get the timestamp associated with the current revision, adjusted for
4494 * the default server-local timestamp
4496 function getRevisionTimestamp() {
4497 if ( is_null( $this->mRevisionTimestamp
) ) {
4498 wfProfileIn( __METHOD__
);
4500 $dbr = wfGetDB( DB_SLAVE
);
4501 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4502 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4504 // Normalize timestamp to internal MW format for timezone processing.
4505 // This has the added side-effect of replacing a null value with
4506 // the current time, which gives us more sensible behavior for
4508 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4510 // The cryptic '' timezone parameter tells to use the site-default
4511 // timezone offset instead of the user settings.
4513 // Since this value will be saved into the parser cache, served
4514 // to other users, and potentially even used inside links and such,
4515 // it needs to be consistent for all visitors.
4516 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4518 wfProfileOut( __METHOD__
);
4520 return $this->mRevisionTimestamp
;
4524 * Mutator for $mDefaultSort
4526 * @param $sort New value
4528 public function setDefaultSort( $sort ) {
4529 $this->mDefaultSort
= $sort;
4533 * Accessor for $mDefaultSort
4534 * Will use the title/prefixed title if none is set
4538 public function getDefaultSort() {
4539 global $wgCategoryPrefixedDefaultSortkey;
4540 if( $this->mDefaultSort
!== false ) {
4541 return $this->mDefaultSort
;
4542 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4543 !$wgCategoryPrefixedDefaultSortkey) {
4544 return $this->mTitle
->getText();
4546 return $this->mTitle
->getPrefixedText();
4551 * Try to guess the section anchor name based on a wikitext fragment
4552 * presumably extracted from a heading, for example "Header" from
4555 public function guessSectionNameFromWikiText( $text ) {
4556 # Strip out wikitext links(they break the anchor)
4557 $text = $this->stripSectionName( $text );
4558 $headline = Sanitizer
::decodeCharReferences( $text );
4560 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4561 $headline = trim( $headline );
4562 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4563 $replacearray = array(
4568 array_keys( $replacearray ),
4569 array_values( $replacearray ),
4574 * Strips a text string of wikitext for use in a section anchor
4576 * Accepts a text string and then removes all wikitext from the
4577 * string and leaves only the resultant text (i.e. the result of
4578 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4579 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4580 * to create valid section anchors by mimicing the output of the
4581 * parser when headings are parsed.
4583 * @param $text string Text string to be stripped of wikitext
4584 * for use in a Section anchor
4585 * @return Filtered text string
4587 public function stripSectionName( $text ) {
4588 # Strip internal link markup
4589 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4590 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4592 # Strip external link markup (FIXME: Not Tolerant to blank link text
4593 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4594 # on how many empty links there are on the page - need to figure that out.
4595 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4597 # Parse wikitext quotes (italics & bold)
4598 $text = $this->doQuotes($text);
4601 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4605 function srvus( $text ) {
4606 return $this->testSrvus( $text, $this->mOutputType
);
4610 * strip/replaceVariables/unstrip for preprocessor regression testing
4612 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4613 $this->clearState();
4614 if ( ! ( $title instanceof Title
) ) {
4615 $title = Title
::newFromText( $title );
4617 $this->mTitle
= $title;
4618 $this->mOptions
= $options;
4619 $this->setOutputType( $outputType );
4620 $text = $this->replaceVariables( $text );
4621 $text = $this->mStripState
->unstripBoth( $text );
4622 $text = Sanitizer
::removeHTMLtags( $text );
4626 function testPst( $text, $title, $options ) {
4628 if ( ! ( $title instanceof Title
) ) {
4629 $title = Title
::newFromText( $title );
4631 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4634 function testPreprocess( $text, $title, $options ) {
4635 if ( ! ( $title instanceof Title
) ) {
4636 $title = Title
::newFromText( $title );
4638 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4641 function markerSkipCallback( $s, $callback ) {
4644 while ( $i < strlen( $s ) ) {
4645 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4646 if ( $markerStart === false ) {
4647 $out .= call_user_func( $callback, substr( $s, $i ) );
4650 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4651 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4652 if ( $markerEnd === false ) {
4653 $out .= substr( $s, $markerStart );
4656 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4657 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4667 * @todo document, briefly.
4671 var $general, $nowiki;
4673 function __construct() {
4674 $this->general
= new ReplacementArray
;
4675 $this->nowiki
= new ReplacementArray
;
4678 function unstripGeneral( $text ) {
4679 wfProfileIn( __METHOD__
);
4682 $text = $this->general
->replace( $text );
4683 } while ( $text != $oldText );
4684 wfProfileOut( __METHOD__
);
4688 function unstripNoWiki( $text ) {
4689 wfProfileIn( __METHOD__
);
4692 $text = $this->nowiki
->replace( $text );
4693 } while ( $text != $oldText );
4694 wfProfileOut( __METHOD__
);
4698 function unstripBoth( $text ) {
4699 wfProfileIn( __METHOD__
);
4702 $text = $this->general
->replace( $text );
4703 $text = $this->nowiki
->replace( $text );
4704 } while ( $text != $oldText );
4705 wfProfileOut( __METHOD__
);
4711 * @todo document, briefly.
4714 class OnlyIncludeReplacer
{
4717 function replace( $matches ) {
4718 if ( substr( $matches[1], -1 ) == "\n" ) {
4719 $this->output
.= substr( $matches[1], 0, -1 );
4721 $this->output
.= $matches[1];