3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
124 function __construct( $conf = array() ) {
125 $this->mConf
= $conf;
126 $this->mTagHooks
= array();
127 $this->mTransparentTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
131 $this->mUrlProtocols
= wfUrlProtocols();
132 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
133 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
134 $this->mVarCache
= array();
135 if ( isset( $conf['preprocessorClass'] ) ) {
136 $this->mPreprocessorClass
= $conf['preprocessorClass'];
137 } elseif ( extension_loaded( 'dom' ) ) {
138 $this->mPreprocessorClass
= 'Preprocessor_DOM';
140 $this->mPreprocessorClass
= 'Preprocessor_Hash';
142 $this->mMarkerIndex
= 0;
143 $this->mFirstCall
= true;
147 * Reduce memory usage to reduce the impact of circular references
149 function __destruct() {
150 if ( isset( $this->mLinkHolders
) ) {
151 $this->mLinkHolders
->__destruct();
153 foreach ( $this as $name => $value ) {
154 unset( $this->$name );
159 * Do various kinds of initialisation on the first call of the parser
161 function firstCallInit() {
162 if ( !$this->mFirstCall
) {
165 $this->mFirstCall
= false;
167 wfProfileIn( __METHOD__
);
169 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
170 CoreParserFunctions
::register( $this );
171 $this->initialiseVariables();
173 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
174 wfProfileOut( __METHOD__
);
182 function clearState() {
183 wfProfileIn( __METHOD__
);
184 if ( $this->mFirstCall
) {
185 $this->firstCallInit();
187 $this->mOutput
= new ParserOutput
;
188 $this->mAutonumber
= 0;
189 $this->mLastSection
= '';
190 $this->mDTopen
= false;
191 $this->mIncludeCount
= array();
192 $this->mStripState
= new StripState
;
193 $this->mArgStack
= false;
194 $this->mInPre
= false;
195 $this->mLinkHolders
= new LinkHolderArray( $this );
197 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
200 * Prefix for temporary replacement strings for the multipass parser.
201 * \x07 should never appear in input as it's disallowed in XML.
202 * Using it at the front also gives us a little extra robustness
203 * since it shouldn't match when butted up against identifier-like
206 * Must not consist of all title characters, or else it will change
207 * the behaviour of <nowiki> in a link.
209 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
210 # Changed to \x7f to allow XML double-parsing -- TS
211 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
214 # Clear these on every parse, bug 4549
215 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
217 $this->mShowToc
= true;
218 $this->mForceTocPosition
= false;
219 $this->mIncludeSizes
= array(
223 $this->mPPNodeCount
= 0;
224 $this->mDefaultSort
= false;
225 $this->mHeadings
= array();
226 $this->mDoubleUnderscores
= array();
227 $this->mExpensiveFunctionCount
= 0;
230 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
231 $this->mPreprocessor
= null;
234 wfRunHooks( 'ParserClearState', array( &$this ) );
235 wfProfileOut( __METHOD__
);
238 function setOutputType( $ot ) {
239 $this->mOutputType
= $ot;
242 'html' => $ot == self
::OT_HTML
,
243 'wiki' => $ot == self
::OT_WIKI
,
244 'pre' => $ot == self
::OT_PREPROCESS
,
249 * Set the context title
251 function setTitle( $t ) {
252 if ( !$t ||
$t instanceof FakeTitle
) {
253 $t = Title
::newFromText( 'NO TITLE' );
255 if ( strval( $t->getFragment() ) !== '' ) {
256 # Strip the fragment to avoid various odd effects
257 $this->mTitle
= clone $t;
258 $this->mTitle
->setFragment( '' );
265 * Accessor for mUniqPrefix.
269 function uniqPrefix() {
270 if( !isset( $this->mUniqPrefix
) ) {
271 // @fixme this is probably *horribly wrong*
272 // LanguageConverter seems to want $wgParser's uniqPrefix, however
273 // if this is called for a parser cache hit, the parser may not
274 // have ever been initialized in the first place.
275 // Not really sure what the heck is supposed to be going on here.
277 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
279 return $this->mUniqPrefix
;
283 * Convert wikitext to HTML
284 * Do not call this function recursively.
286 * @param $text String: text we want to parse
287 * @param $title A title object
288 * @param $options ParserOptions
289 * @param $linestart boolean
290 * @param $clearState boolean
291 * @param $revid Int: number to pass in {{REVISIONID}}
292 * @return ParserOutput a ParserOutput
294 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
296 * First pass--just handle <nowiki> sections, pass the rest off
297 * to internalParse() which does all the real work.
300 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
301 $fname = __METHOD__
.'-' . wfGetCaller();
302 wfProfileIn( __METHOD__
);
303 wfProfileIn( $fname );
309 $this->mOptions
= $options;
310 $this->setTitle( $title );
311 $oldRevisionId = $this->mRevisionId
;
312 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
313 if( $revid !== null ) {
314 $this->mRevisionId
= $revid;
315 $this->mRevisionTimestamp
= null;
317 $this->setOutputType( self
::OT_HTML
);
318 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
320 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
321 $text = $this->internalParse( $text );
322 $text = $this->mStripState
->unstripGeneral( $text );
324 # Clean up special characters, only run once, next-to-last before doBlockLevels
326 # french spaces, last one Guillemet-left
327 # only if there is something before the space
328 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
329 # french spaces, Guillemet-right
330 '/(\\302\\253) /' => '\\1 ',
331 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
333 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
335 $text = $this->doBlockLevels( $text, $linestart );
337 $this->replaceLinkHolders( $text );
339 # the position of the parserConvert() call should not be changed. it
340 # assumes that the links are all replaced and the only thing left
341 # is the <nowiki> mark.
342 # Side-effects: this calls $this->mOutput->setTitleText()
343 $text = $wgContLang->parserConvert( $text, $this );
345 $text = $this->mStripState
->unstripNoWiki( $text );
347 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
349 //!JF Move to its own function
351 $uniq_prefix = $this->mUniqPrefix
;
353 $elements = array_keys( $this->mTransparentTagHooks
);
354 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
356 foreach( $matches as $marker => $data ) {
357 list( $element, $content, $params, $tag ) = $data;
358 $tagName = strtolower( $element );
359 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
360 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
361 array( $content, $params, $this ) );
365 $this->mStripState
->general
->setPair( $marker, $output );
367 $text = $this->mStripState
->unstripGeneral( $text );
369 $text = Sanitizer
::normalizeCharReferences( $text );
371 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
372 $text = self
::tidy($text);
374 # attempt to sanitize at least some nesting problems
375 # (bug #2702 and quite a few others)
377 # ''Something [http://www.cool.com cool''] -->
378 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
379 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
380 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
381 # fix up an anchor inside another anchor, only
382 # at least for a single single nested link (bug 3695)
383 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
384 '\\1\\2</a>\\3</a>\\1\\4</a>',
385 # fix div inside inline elements- doBlockLevels won't wrap a line which
386 # contains a div, so fix it up here; replace
387 # div with escaped text
388 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
389 '\\1\\3<div\\5>\\6</div>\\8\\9',
390 # remove empty italic or bold tag pairs, some
391 # introduced by rules above
392 '/<([bi])><\/\\1>/' => '',
395 $text = preg_replace(
396 array_keys( $tidyregs ),
397 array_values( $tidyregs ),
400 global $wgExpensiveParserFunctionLimit;
401 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
402 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
405 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
407 # Information on include size limits, for the benefit of users who try to skirt them
408 if ( $this->mOptions
->getEnableLimitReport() ) {
409 global $wgExpensiveParserFunctionLimit;
410 $max = $this->mOptions
->getMaxIncludeSize();
411 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
413 "NewPP limit report\n" .
414 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
415 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
416 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
418 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
419 $text .= "\n<!-- \n$limitReport-->\n";
421 $this->mOutput
->setText( $text );
422 $this->mRevisionId
= $oldRevisionId;
423 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
424 wfProfileOut( $fname );
425 wfProfileOut( __METHOD__
);
427 return $this->mOutput
;
431 * Recursive parser entry point that can be called from an extension tag
434 function recursiveTagParse( $text ) {
435 wfProfileIn( __METHOD__
);
436 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
437 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
438 $text = $this->internalParse( $text );
439 wfProfileOut( __METHOD__
);
444 * Expand templates and variables in the text, producing valid, static wikitext.
445 * Also removes comments.
447 function preprocess( $text, $title, $options, $revid = null ) {
448 wfProfileIn( __METHOD__
);
450 $this->setOutputType( self
::OT_PREPROCESS
);
451 $this->mOptions
= $options;
452 $this->setTitle( $title );
453 if( $revid !== null ) {
454 $this->mRevisionId
= $revid;
456 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
457 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
458 $text = $this->replaceVariables( $text );
459 $text = $this->mStripState
->unstripBoth( $text );
460 wfProfileOut( __METHOD__
);
465 * Get a random string
470 function getRandomString() {
471 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
474 function &getTitle() { return $this->mTitle
; }
475 function getOptions() { return $this->mOptions
; }
476 function getRevisionId() { return $this->mRevisionId
; }
477 function getOutput() { return $this->mOutput
; }
478 function nextLinkID() { return $this->mLinkID++
; }
480 function getFunctionLang() {
481 global $wgLang, $wgContLang;
483 $target = $this->mOptions
->getTargetLanguage();
484 if ( $target !== null ) {
487 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
492 * Get a preprocessor object
494 function getPreprocessor() {
495 if ( !isset( $this->mPreprocessor
) ) {
496 $class = $this->mPreprocessorClass
;
497 $this->mPreprocessor
= new $class( $this );
499 return $this->mPreprocessor
;
503 * Replaces all occurrences of HTML-style comments and the given tags
504 * in the text with a random marker and returns the next text. The output
505 * parameter $matches will be an associative array filled with data in
507 * 'UNIQ-xxxxx' => array(
510 * array( 'param' => 'x' ),
511 * '<element param="x">tag content</element>' ) )
513 * @param $elements list of element names. Comments are always extracted.
514 * @param $text Source text string.
515 * @param $uniq_prefix
520 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
525 $taglist = implode( '|', $elements );
526 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
528 while ( '' != $text ) {
529 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
531 if( count( $p ) < 5 ) {
534 if( count( $p ) > 5 ) {
548 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
549 $stripped .= $marker;
551 if ( $close === '/>' ) {
552 // Empty element tag, <tag />
557 if( $element === '!--' ) {
560 $end = "/(<\\/$element\\s*>)/i";
562 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
564 if( count( $q ) < 3 ) {
565 # No end tag -- let it run out to the end of the text.
574 $matches[$marker] = array( $element,
576 Sanitizer
::decodeTagAttributes( $attributes ),
577 "<$element$attributes$close$content$tail" );
583 * Get a list of strippable XML-like elements
585 function getStripList() {
587 $elements = $this->mStripList
;
589 $elements[] = 'html';
591 if( $this->mOptions
->getUseTeX() ) {
592 $elements[] = 'math';
598 * @deprecated use replaceVariables
600 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
605 * Restores pre, math, and other extensions removed by strip()
607 * always call unstripNoWiki() after this one
609 * @deprecated use $this->mStripState->unstrip()
611 function unstrip( $text, $state ) {
612 return $state->unstripGeneral( $text );
616 * Always call this after unstrip() to preserve the order
619 * @deprecated use $this->mStripState->unstrip()
621 function unstripNoWiki( $text, $state ) {
622 return $state->unstripNoWiki( $text );
626 * @deprecated use $this->mStripState->unstripBoth()
628 function unstripForHTML( $text ) {
629 return $this->mStripState
->unstripBoth( $text );
633 * Add an item to the strip state
634 * Returns the unique tag which must be inserted into the stripped text
635 * The tag will be replaced with the original text in unstrip()
639 function insertStripItem( $text ) {
640 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
641 $this->mMarkerIndex++
;
642 $this->mStripState
->general
->setPair( $rnd, $text );
647 * Interface with html tidy, used if $wgUseTidy = true.
648 * If tidy isn't able to correct the markup, the original will be
649 * returned in all its glory with a warning comment appended.
651 * Either the external tidy program or the in-process tidy extension
652 * will be used depending on availability. Override the default
653 * $wgTidyInternal setting to disable the internal if it's not working.
655 * @param string $text Hideous HTML input
656 * @return string Corrected HTML output
660 function tidy( $text ) {
661 global $wgTidyInternal;
662 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
663 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
664 '<head><title>test</title></head><body>'.$text.'</body></html>';
665 if( $wgTidyInternal ) {
666 $correctedtext = self
::internalTidy( $wrappedtext );
668 $correctedtext = self
::externalTidy( $wrappedtext );
670 if( is_null( $correctedtext ) ) {
671 wfDebug( "Tidy error detected!\n" );
672 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
674 return $correctedtext;
678 * Spawn an external HTML tidy process and get corrected markup back from it.
683 function externalTidy( $text ) {
684 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
685 wfProfileIn( __METHOD__
);
690 $descriptorspec = array(
691 0 => array('pipe', 'r'),
692 1 => array('pipe', 'w'),
693 2 => array('file', wfGetNull(), 'a')
696 if( function_exists('proc_open') ) {
697 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
698 if (is_resource($process)) {
699 // Theoretically, this style of communication could cause a deadlock
700 // here. If the stdout buffer fills up, then writes to stdin could
701 // block. This doesn't appear to happen with tidy, because tidy only
702 // writes to stdout after it's finished reading from stdin. Search
703 // for tidyParseStdin and tidySaveStdout in console/tidy.c
704 fwrite($pipes[0], $text);
706 while (!feof($pipes[1])) {
707 $cleansource .= fgets($pipes[1], 1024);
710 proc_close($process);
714 wfProfileOut( __METHOD__
);
716 if( $cleansource == '' && $text != '') {
717 // Some kind of error happened, so we couldn't get the corrected text.
718 // Just give up; we'll use the source text and append a warning.
726 * Use the HTML tidy PECL extension to use the tidy library in-process,
727 * saving the overhead of spawning a new process.
729 * 'pear install tidy' should be able to compile the extension module.
734 function internalTidy( $text ) {
735 global $wgTidyConf, $IP, $wgDebugTidy;
736 wfProfileIn( __METHOD__
);
739 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
740 $tidy->cleanRepair();
741 if( $tidy->getStatus() == 2 ) {
742 // 2 is magic number for fatal error
743 // http://www.php.net/manual/en/function.tidy-get-status.php
746 $cleansource = tidy_get_output( $tidy );
748 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
749 $cleansource .= "<!--\nTidy reports:\n" .
750 str_replace( '-->', '-->', $tidy->errorBuffer
) .
754 wfProfileOut( __METHOD__
);
759 * parse the wiki syntax used to render tables
763 function doTableStuff ( $text ) {
764 wfProfileIn( __METHOD__
);
766 $lines = StringUtils
::explode( "\n", $text );
768 $td_history = array (); // Is currently a td tag open?
769 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
770 $tr_history = array (); // Is currently a tr tag open?
771 $tr_attributes = array (); // history of tr attributes
772 $has_opened_tr = array(); // Did this table open a <tr> element?
773 $indent_level = 0; // indent level of the table
775 foreach ( $lines as $outLine ) {
776 $line = trim( $outLine );
778 if( $line == '' ) { // empty line, go to next line
779 $out .= $outLine."\n";
782 $first_character = $line[0];
785 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
786 // First check if we are starting a new table
787 $indent_level = strlen( $matches[1] );
789 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
790 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
792 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
793 array_push ( $td_history , false );
794 array_push ( $last_tag_history , '' );
795 array_push ( $tr_history , false );
796 array_push ( $tr_attributes , '' );
797 array_push ( $has_opened_tr , false );
798 } else if ( count ( $td_history ) == 0 ) {
799 // Don't do any of the following
800 $out .= $outLine."\n";
802 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
803 // We are ending a table
804 $line = '</table>' . substr ( $line , 2 );
805 $last_tag = array_pop ( $last_tag_history );
807 if ( !array_pop ( $has_opened_tr ) ) {
808 $line = "<tr><td></td></tr>{$line}";
811 if ( array_pop ( $tr_history ) ) {
812 $line = "</tr>{$line}";
815 if ( array_pop ( $td_history ) ) {
816 $line = "</{$last_tag}>{$line}";
818 array_pop ( $tr_attributes );
819 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
820 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
821 // Now we have a table row
822 $line = preg_replace( '#^\|-+#', '', $line );
824 // Whats after the tag is now only attributes
825 $attributes = $this->mStripState
->unstripBoth( $line );
826 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
827 array_pop ( $tr_attributes );
828 array_push ( $tr_attributes , $attributes );
831 $last_tag = array_pop ( $last_tag_history );
832 array_pop ( $has_opened_tr );
833 array_push ( $has_opened_tr , true );
835 if ( array_pop ( $tr_history ) ) {
839 if ( array_pop ( $td_history ) ) {
840 $line = "</{$last_tag}>{$line}";
844 array_push ( $tr_history , false );
845 array_push ( $td_history , false );
846 array_push ( $last_tag_history , '' );
848 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
849 // This might be cell elements, td, th or captions
850 if ( substr ( $line , 0 , 2 ) === '|+' ) {
851 $first_character = '+';
852 $line = substr ( $line , 1 );
855 $line = substr ( $line , 1 );
857 if ( $first_character === '!' ) {
858 $line = str_replace ( '!!' , '||' , $line );
861 // Split up multiple cells on the same line.
862 // FIXME : This can result in improper nesting of tags processed
863 // by earlier parser steps, but should avoid splitting up eg
864 // attribute values containing literal "||".
865 $cells = StringUtils
::explodeMarkup( '||' , $line );
869 // Loop through each table cell
870 foreach ( $cells as $cell )
873 if ( $first_character !== '+' )
875 $tr_after = array_pop ( $tr_attributes );
876 if ( !array_pop ( $tr_history ) ) {
877 $previous = "<tr{$tr_after}>\n";
879 array_push ( $tr_history , true );
880 array_push ( $tr_attributes , '' );
881 array_pop ( $has_opened_tr );
882 array_push ( $has_opened_tr , true );
885 $last_tag = array_pop ( $last_tag_history );
887 if ( array_pop ( $td_history ) ) {
888 $previous = "</{$last_tag}>{$previous}";
891 if ( $first_character === '|' ) {
893 } else if ( $first_character === '!' ) {
895 } else if ( $first_character === '+' ) {
896 $last_tag = 'caption';
901 array_push ( $last_tag_history , $last_tag );
903 // A cell could contain both parameters and data
904 $cell_data = explode ( '|' , $cell , 2 );
906 // Bug 553: Note that a '|' inside an invalid link should not
907 // be mistaken as delimiting cell parameters
908 if ( strpos( $cell_data[0], '[[' ) !== false ) {
909 $cell = "{$previous}<{$last_tag}>{$cell}";
910 } else if ( count ( $cell_data ) == 1 )
911 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
913 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
914 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
915 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
919 array_push ( $td_history , true );
922 $out .= $outLine . "\n";
925 // Closing open td, tr && table
926 while ( count ( $td_history ) > 0 )
928 if ( array_pop ( $td_history ) ) {
931 if ( array_pop ( $tr_history ) ) {
934 if ( !array_pop ( $has_opened_tr ) ) {
935 $out .= "<tr><td></td></tr>\n" ;
938 $out .= "</table>\n";
941 // Remove trailing line-ending (b/c)
942 if ( substr( $out, -1 ) === "\n" ) {
943 $out = substr( $out, 0, -1 );
946 // special case: don't return empty table
947 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
951 wfProfileOut( __METHOD__
);
957 * Helper function for parse() that transforms wiki markup into
958 * HTML. Only called for $mOutputType == self::OT_HTML.
962 function internalParse( $text ) {
964 wfProfileIn( __METHOD__
);
966 # Hook to suspend the parser in this state
967 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
968 wfProfileOut( __METHOD__
);
972 $text = $this->replaceVariables( $text );
973 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
974 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
976 // Tables need to come after variable replacement for things to work
977 // properly; putting them before other transformations should keep
978 // exciting things like link expansions from showing up in surprising
980 $text = $this->doTableStuff( $text );
982 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
984 $text = $this->doDoubleUnderscore( $text );
985 $text = $this->doHeadings( $text );
986 if($this->mOptions
->getUseDynamicDates()) {
987 $df = DateFormatter
::getInstance();
988 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
990 $text = $this->doAllQuotes( $text );
991 $text = $this->replaceInternalLinks( $text );
992 $text = $this->replaceExternalLinks( $text );
994 # replaceInternalLinks may sometimes leave behind
995 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
996 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
998 $text = $this->doMagicLinks( $text );
999 $text = $this->formatHeadings( $text, $isMain );
1001 wfProfileOut( __METHOD__
);
1006 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1007 * magic external links.
1012 function doMagicLinks( $text ) {
1013 wfProfileIn( __METHOD__
);
1014 $prots = $this->mUrlProtocols
;
1015 $urlChar = self
::EXT_LINK_URL_CLASS
;
1016 $text = preg_replace_callback(
1018 (<a.*?</a>) | # m[1]: Skip link text
1019 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1020 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1021 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1022 ISBN\s+(\b # m[5]: ISBN, capture number
1023 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1024 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1025 [0-9Xx] # check digit
1027 )!x', array( &$this, 'magicLinkCallback' ), $text );
1028 wfProfileOut( __METHOD__
);
1032 function magicLinkCallback( $m ) {
1033 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1036 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1039 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1040 # Free external link
1041 return $this->makeFreeExternalLink( $m[0] );
1042 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1044 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1048 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1050 $urlmsg = 'pubmedurl';
1053 throw new MWException( __METHOD__
.': unrecognised match type "' .
1054 substr($m[0], 0, 20 ) . '"' );
1056 $url = wfMsg( $urlmsg, $id);
1057 $sk = $this->mOptions
->getSkin();
1058 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1059 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1060 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1063 $num = strtr( $isbn, array(
1068 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1070 $titleObj->escapeLocalUrl() .
1071 "\" class=\"internal\">ISBN $isbn</a>";
1078 * Make a free external link, given a user-supplied URL
1082 function makeFreeExternalLink( $url ) {
1084 wfProfileIn( __METHOD__
);
1086 $sk = $this->mOptions
->getSkin();
1089 # The characters '<' and '>' (which were escaped by
1090 # removeHTMLtags()) should not be included in
1091 # URLs, per RFC 2396.
1093 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1094 $trail = substr($url, $m2[0][1]) . $trail;
1095 $url = substr($url, 0, $m2[0][1]);
1098 # Move trailing punctuation to $trail
1100 # If there is no left bracket, then consider right brackets fair game too
1101 if ( strpos( $url, '(' ) === false ) {
1105 $numSepChars = strspn( strrev( $url ), $sep );
1106 if ( $numSepChars ) {
1107 $trail = substr( $url, -$numSepChars ) . $trail;
1108 $url = substr( $url, 0, -$numSepChars );
1111 $url = Sanitizer
::cleanUrl( $url );
1113 # Is this an external image?
1114 $text = $this->maybeMakeExternalImage( $url );
1115 if ( $text === false ) {
1116 # Not an image, make a link
1117 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1118 # Register it in the output object...
1119 # Replace unnecessary URL escape codes with their equivalent characters
1120 $pasteurized = self
::replaceUnusualEscapes( $url );
1121 $this->mOutput
->addExternalLink( $pasteurized );
1123 wfProfileOut( __METHOD__
);
1124 return $text . $trail;
1129 * Parse headers and return html
1133 function doHeadings( $text ) {
1134 wfProfileIn( __METHOD__
);
1135 for ( $i = 6; $i >= 1; --$i ) {
1136 $h = str_repeat( '=', $i );
1137 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1138 "<h$i>\\1</h$i>", $text );
1140 wfProfileOut( __METHOD__
);
1145 * Replace single quotes with HTML markup
1147 * @return string the altered text
1149 function doAllQuotes( $text ) {
1150 wfProfileIn( __METHOD__
);
1152 $lines = StringUtils
::explode( "\n", $text );
1153 foreach ( $lines as $line ) {
1154 $outtext .= $this->doQuotes( $line ) . "\n";
1156 $outtext = substr($outtext, 0,-1);
1157 wfProfileOut( __METHOD__
);
1162 * Helper function for doAllQuotes()
1164 public function doQuotes( $text ) {
1165 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1166 if ( count( $arr ) == 1 )
1170 # First, do some preliminary work. This may shift some apostrophes from
1171 # being mark-up to being text. It also counts the number of occurrences
1172 # of bold and italics mark-ups.
1176 foreach ( $arr as $r )
1178 if ( ( $i %
2 ) == 1 )
1180 # If there are ever four apostrophes, assume the first is supposed to
1181 # be text, and the remaining three constitute mark-up for bold text.
1182 if ( strlen( $arr[$i] ) == 4 )
1187 # If there are more than 5 apostrophes in a row, assume they're all
1188 # text except for the last 5.
1189 else if ( strlen( $arr[$i] ) > 5 )
1191 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1194 # Count the number of occurrences of bold and italics mark-ups.
1195 # We are not counting sequences of five apostrophes.
1196 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1197 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1198 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1203 # If there is an odd number of both bold and italics, it is likely
1204 # that one of the bold ones was meant to be an apostrophe followed
1205 # by italics. Which one we cannot know for certain, but it is more
1206 # likely to be one that has a single-letter word before it.
1207 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1210 $firstsingleletterword = -1;
1211 $firstmultiletterword = -1;
1213 foreach ( $arr as $r )
1215 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1217 $x1 = substr ($arr[$i-1], -1);
1218 $x2 = substr ($arr[$i-1], -2, 1);
1220 if ($firstspace == -1) $firstspace = $i;
1221 } else if ($x2 === ' ') {
1222 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1224 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1230 # If there is a single-letter word, use it!
1231 if ($firstsingleletterword > -1)
1233 $arr [ $firstsingleletterword ] = "''";
1234 $arr [ $firstsingleletterword-1 ] .= "'";
1236 # If not, but there's a multi-letter word, use that one.
1237 else if ($firstmultiletterword > -1)
1239 $arr [ $firstmultiletterword ] = "''";
1240 $arr [ $firstmultiletterword-1 ] .= "'";
1242 # ... otherwise use the first one that has neither.
1243 # (notice that it is possible for all three to be -1 if, for example,
1244 # there is only one pentuple-apostrophe in the line)
1245 else if ($firstspace > -1)
1247 $arr [ $firstspace ] = "''";
1248 $arr [ $firstspace-1 ] .= "'";
1252 # Now let's actually convert our apostrophic mush to HTML!
1257 foreach ($arr as $r)
1261 if ($state === 'both')
1268 if (strlen ($r) == 2)
1271 { $output .= '</i>'; $state = ''; }
1272 else if ($state === 'bi')
1273 { $output .= '</i>'; $state = 'b'; }
1274 else if ($state === 'ib')
1275 { $output .= '</b></i><b>'; $state = 'b'; }
1276 else if ($state === 'both')
1277 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1278 else # $state can be 'b' or ''
1279 { $output .= '<i>'; $state .= 'i'; }
1281 else if (strlen ($r) == 3)
1284 { $output .= '</b>'; $state = ''; }
1285 else if ($state === 'bi')
1286 { $output .= '</i></b><i>'; $state = 'i'; }
1287 else if ($state === 'ib')
1288 { $output .= '</b>'; $state = 'i'; }
1289 else if ($state === 'both')
1290 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1291 else # $state can be 'i' or ''
1292 { $output .= '<b>'; $state .= 'b'; }
1294 else if (strlen ($r) == 5)
1297 { $output .= '</b><i>'; $state = 'i'; }
1298 else if ($state === 'i')
1299 { $output .= '</i><b>'; $state = 'b'; }
1300 else if ($state === 'bi')
1301 { $output .= '</i></b>'; $state = ''; }
1302 else if ($state === 'ib')
1303 { $output .= '</b></i>'; $state = ''; }
1304 else if ($state === 'both')
1305 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1306 else # ($state == '')
1307 { $buffer = ''; $state = 'both'; }
1312 # Now close all remaining tags. Notice that the order is important.
1313 if ($state === 'b' ||
$state === 'ib')
1315 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1317 if ($state === 'bi')
1319 # There might be lonely ''''', so make sure we have a buffer
1320 if ($state === 'both' && $buffer)
1321 $output .= '<b><i>'.$buffer.'</i></b>';
1327 * Replace external links (REL)
1329 * Note: this is all very hackish and the order of execution matters a lot.
1330 * Make sure to run maintenance/parserTests.php if you change this code.
1334 function replaceExternalLinks( $text ) {
1336 wfProfileIn( __METHOD__
);
1338 $sk = $this->mOptions
->getSkin();
1340 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1341 $s = array_shift( $bits );
1344 while ( $i<count( $bits ) ) {
1346 $protocol = $bits[$i++
];
1347 $text = $bits[$i++
];
1348 $trail = $bits[$i++
];
1350 # The characters '<' and '>' (which were escaped by
1351 # removeHTMLtags()) should not be included in
1352 # URLs, per RFC 2396.
1354 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1355 $text = substr($url, $m2[0][1]) . ' ' . $text;
1356 $url = substr($url, 0, $m2[0][1]);
1359 # If the link text is an image URL, replace it with an <img> tag
1360 # This happened by accident in the original parser, but some people used it extensively
1361 $img = $this->maybeMakeExternalImage( $text );
1362 if ( $img !== false ) {
1368 # Set linktype for CSS - if URL==text, link is essentially free
1369 $linktype = ($text === $url) ?
'free' : 'text';
1371 # No link text, e.g. [http://domain.tld/some.link]
1372 if ( $text == '' ) {
1373 # Autonumber if allowed. See bug #5918
1374 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1375 $text = '[' . ++
$this->mAutonumber
. ']';
1376 $linktype = 'autonumber';
1378 # Otherwise just use the URL
1379 $text = htmlspecialchars( $url );
1383 # Have link text, e.g. [http://domain.tld/some.link text]s
1385 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1388 $text = $wgContLang->markNoConversion($text);
1390 $url = Sanitizer
::cleanUrl( $url );
1392 # Use the encoded URL
1393 # This means that users can paste URLs directly into the text
1394 # Funny characters like ö aren't valid in URLs anyway
1395 # This was changed in August 2004
1396 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1398 # Register link in the output object.
1399 # Replace unnecessary URL escape codes with the referenced character
1400 # This prevents spammers from hiding links from the filters
1401 $pasteurized = self
::replaceUnusualEscapes( $url );
1402 $this->mOutput
->addExternalLink( $pasteurized );
1405 wfProfileOut( __METHOD__
);
1410 * Replace unusual URL escape codes with their equivalent characters
1414 * @todo This can merge genuinely required bits in the path or query string,
1415 * breaking legit URLs. A proper fix would treat the various parts of
1416 * the URL differently; as a workaround, just use the output for
1417 * statistical records, not for actual linking/output.
1419 static function replaceUnusualEscapes( $url ) {
1420 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1421 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1425 * Callback function used in replaceUnusualEscapes().
1426 * Replaces unusual URL escape codes with their equivalent character
1430 private static function replaceUnusualEscapesCallback( $matches ) {
1431 $char = urldecode( $matches[0] );
1432 $ord = ord( $char );
1433 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1434 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1435 // No, shouldn't be escaped
1438 // Yes, leave it escaped
1444 * make an image if it's allowed, either through the global
1445 * option, through the exception, or through the on-wiki whitelist
1448 function maybeMakeExternalImage( $url ) {
1449 $sk = $this->mOptions
->getSkin();
1450 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1451 $imagesexception = !empty($imagesfrom);
1453 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1454 if( $imagesexception && is_array( $imagesfrom ) ) {
1455 $imagematch = false;
1456 foreach( $imagesfrom as $match ) {
1457 if( strpos( $url, $match ) === 0 ) {
1462 } elseif( $imagesexception ) {
1463 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1465 $imagematch = false;
1467 if ( $this->mOptions
->getAllowExternalImages()
1468 ||
( $imagesexception && $imagematch ) ) {
1469 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1471 $text = $sk->makeExternalImage( $url );
1474 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1475 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1476 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1477 foreach( $whitelist as $entry ) {
1478 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1479 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1481 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1482 # Image matches a whitelist entry
1483 $text = $sk->makeExternalImage( $url );
1492 * Process [[ ]] wikilinks
1493 * @return processed text
1497 function replaceInternalLinks( $s ) {
1498 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1503 * Process [[ ]] wikilinks (RIL)
1504 * @return LinkHolderArray
1508 function replaceInternalLinks2( &$s ) {
1511 wfProfileIn( __METHOD__
);
1513 wfProfileIn( __METHOD__
.'-setup' );
1514 static $tc = FALSE, $e1, $e1_img;
1515 # the % is needed to support urlencoded titles as well
1517 $tc = Title
::legalChars() . '#%';
1518 # Match a link having the form [[namespace:link|alternate]]trail
1519 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1520 # Match cases where there is no "]]", which might still be images
1521 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1524 $sk = $this->mOptions
->getSkin();
1525 $holders = new LinkHolderArray( $this );
1527 #split the entire text string on occurences of [[
1528 $a = StringUtils
::explode( '[[', ' ' . $s );
1529 #get the first element (all text up to first [[), and remove the space we added
1532 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1533 $s = substr( $s, 1 );
1535 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1537 if ( $useLinkPrefixExtension ) {
1538 # Match the end of a line for a word that's not followed by whitespace,
1539 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1540 $e2 = wfMsgForContent( 'linkprefix' );
1543 if( is_null( $this->mTitle
) ) {
1544 wfProfileOut( __METHOD__
.'-setup' );
1545 wfProfileOut( __METHOD__
);
1546 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1548 $nottalk = !$this->mTitle
->isTalkPage();
1550 if ( $useLinkPrefixExtension ) {
1552 if ( preg_match( $e2, $s, $m ) ) {
1553 $first_prefix = $m[2];
1555 $first_prefix = false;
1561 if($wgContLang->hasVariants()) {
1562 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1564 $selflink = array($this->mTitle
->getPrefixedText());
1566 $useSubpages = $this->areSubpagesAllowed();
1567 wfProfileOut( __METHOD__
.'-setup' );
1569 # Loop for each link
1570 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1571 # Check for excessive memory usage
1572 if ( $holders->isBig() ) {
1574 # Do the existence check, replace the link holders and clear the array
1575 $holders->replace( $s );
1579 if ( $useLinkPrefixExtension ) {
1580 wfProfileIn( __METHOD__
.'-prefixhandling' );
1581 if ( preg_match( $e2, $s, $m ) ) {
1589 $prefix = $first_prefix;
1590 $first_prefix = false;
1592 wfProfileOut( __METHOD__
.'-prefixhandling' );
1595 $might_be_img = false;
1597 wfProfileIn( __METHOD__
."-e1" );
1598 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1600 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1601 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1602 # the real problem is with the $e1 regex
1605 # Still some problems for cases where the ] is meant to be outside punctuation,
1606 # and no image is in sight. See bug 2095.
1609 substr( $m[3], 0, 1 ) === ']' &&
1610 strpos($text, '[') !== false
1613 $text .= ']'; # so that replaceExternalLinks($text) works later
1614 $m[3] = substr( $m[3], 1 );
1616 # fix up urlencoded title texts
1617 if( strpos( $m[1], '%' ) !== false ) {
1618 # Should anchors '#' also be rejected?
1619 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1622 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1623 $might_be_img = true;
1625 if ( strpos( $m[1], '%' ) !== false ) {
1626 $m[1] = urldecode($m[1]);
1629 } else { # Invalid form; output directly
1630 $s .= $prefix . '[[' . $line ;
1631 wfProfileOut( __METHOD__
."-e1" );
1634 wfProfileOut( __METHOD__
."-e1" );
1635 wfProfileIn( __METHOD__
."-misc" );
1637 # Don't allow internal links to pages containing
1638 # PROTO: where PROTO is a valid URL protocol; these
1639 # should be external links.
1640 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1641 $s .= $prefix . '[[' . $line ;
1642 wfProfileOut( __METHOD__
."-misc" );
1646 # Make subpage if necessary
1647 if( $useSubpages ) {
1648 $link = $this->maybeDoSubpageLink( $m[1], $text );
1653 $noforce = (substr($m[1], 0, 1) !== ':');
1655 # Strip off leading ':'
1656 $link = substr($link, 1);
1659 wfProfileOut( __METHOD__
."-misc" );
1660 wfProfileIn( __METHOD__
."-title" );
1661 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1663 $s .= $prefix . '[[' . $line;
1664 wfProfileOut( __METHOD__
."-title" );
1668 $ns = $nt->getNamespace();
1669 $iw = $nt->getInterWiki();
1670 wfProfileOut( __METHOD__
."-title" );
1672 if ($might_be_img) { # if this is actually an invalid link
1673 wfProfileIn( __METHOD__
."-might_be_img" );
1674 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1677 #look at the next 'line' to see if we can close it there
1679 $next_line = $a->current();
1680 if ( $next_line === false ||
$next_line === null ) {
1683 $m = explode( ']]', $next_line, 3 );
1684 if ( count( $m ) == 3 ) {
1685 # the first ]] closes the inner link, the second the image
1687 $text .= "[[{$m[0]}]]{$m[1]}";
1690 } elseif ( count( $m ) == 2 ) {
1691 #if there's exactly one ]] that's fine, we'll keep looking
1692 $text .= "[[{$m[0]}]]{$m[1]}";
1694 #if $next_line is invalid too, we need look no further
1695 $text .= '[[' . $next_line;
1700 # we couldn't find the end of this imageLink, so output it raw
1701 #but don't ignore what might be perfectly normal links in the text we've examined
1702 $holders->merge( $this->replaceInternalLinks2( $text ) );
1703 $s .= "{$prefix}[[$link|$text";
1704 # note: no $trail, because without an end, there *is* no trail
1705 wfProfileOut( __METHOD__
."-might_be_img" );
1708 } else { #it's not an image, so output it raw
1709 $s .= "{$prefix}[[$link|$text";
1710 # note: no $trail, because without an end, there *is* no trail
1711 wfProfileOut( __METHOD__
."-might_be_img" );
1714 wfProfileOut( __METHOD__
."-might_be_img" );
1717 $wasblank = ( '' == $text );
1718 if( $wasblank ) $text = $link;
1720 # Link not escaped by : , create the various objects
1724 wfProfileIn( __METHOD__
."-interwiki" );
1725 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1726 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1727 $s = rtrim($s . $prefix);
1728 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1729 wfProfileOut( __METHOD__
."-interwiki" );
1732 wfProfileOut( __METHOD__
."-interwiki" );
1734 if ( $ns == NS_IMAGE
) {
1735 wfProfileIn( __METHOD__
."-image" );
1736 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1737 # recursively parse links inside the image caption
1738 # actually, this will parse them in any other parameters, too,
1739 # but it might be hard to fix that, and it doesn't matter ATM
1740 $text = $this->replaceExternalLinks($text);
1741 $holders->merge( $this->replaceInternalLinks2( $text ) );
1743 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1744 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1746 $this->mOutput
->addImage( $nt->getDBkey() );
1747 wfProfileOut( __METHOD__
."-image" );
1752 if ( $ns == NS_CATEGORY
) {
1753 wfProfileIn( __METHOD__
."-category" );
1754 $s = rtrim($s . "\n"); # bug 87
1757 $sortkey = $this->getDefaultSort();
1761 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1762 $sortkey = str_replace( "\n", '', $sortkey );
1763 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1764 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1767 * Strip the whitespace Category links produce, see bug 87
1768 * @todo We might want to use trim($tmp, "\n") here.
1770 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1772 wfProfileOut( __METHOD__
."-category" );
1777 # Self-link checking
1778 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1779 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1780 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1785 # Special and Media are pseudo-namespaces; no pages actually exist in them
1786 if( $ns == NS_MEDIA
) {
1787 # Give extensions a chance to select the file revision for us
1788 $skip = $time = false;
1789 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1791 $link = $sk->link( $nt );
1793 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1795 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1796 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1797 $this->mOutput
->addImage( $nt->getDBkey() );
1799 } elseif( $ns == NS_SPECIAL
) {
1800 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1801 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1803 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1806 } elseif( $ns == NS_IMAGE
) {
1807 $img = wfFindFile( $nt );
1809 // Force a blue link if the file exists; may be a remote
1810 // upload on the shared repository, and we want to see its
1811 // auto-generated page.
1812 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1813 $this->mOutput
->addLink( $nt );
1817 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1819 wfProfileOut( __METHOD__
);
1824 * Make a link placeholder. The text returned can be later resolved to a real link with
1825 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1826 * parsing of interwiki links, and secondly to allow all existence checks and
1827 * article length checks (for stub links) to be bundled into a single query.
1831 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1832 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1836 * Render a forced-blue link inline; protect against double expansion of
1837 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1838 * Since this little disaster has to split off the trail text to avoid
1839 * breaking URLs in the following text without breaking trails on the
1840 * wiki links, it's been made into a horrible function.
1843 * @param string $text
1844 * @param string $query
1845 * @param string $trail
1846 * @param string $prefix
1847 * @return string HTML-wikitext mix oh yuck
1849 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1850 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1851 $sk = $this->mOptions
->getSkin();
1852 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1853 return $this->armorLinks( $link ) . $trail;
1857 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1858 * going to go through further parsing steps before inline URL expansion.
1860 * Not needed quite as much as it used to be since free links are a bit
1861 * more sensible these days. But bracketed links are still an issue.
1863 * @param string more-or-less HTML
1864 * @return string less-or-more HTML with NOPARSE bits
1866 function armorLinks( $text ) {
1867 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1868 "{$this->mUniqPrefix}NOPARSE$1", $text );
1872 * Return true if subpage links should be expanded on this page.
1875 function areSubpagesAllowed() {
1876 # Some namespaces don't allow subpages
1877 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1881 * Handle link to subpage if necessary
1882 * @param string $target the source of the link
1883 * @param string &$text the link text, modified as necessary
1884 * @return string the full name of the link
1887 function maybeDoSubpageLink($target, &$text) {
1890 # :Foobar -- override special treatment of prefix (images, language links)
1891 # /Foobar -- convert to CurrentPage/Foobar
1892 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1893 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1894 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1896 wfProfileIn( __METHOD__
);
1897 $ret = $target; # default return value is no change
1899 # Some namespaces don't allow subpages,
1900 # so only perform processing if subpages are allowed
1901 if( $this->areSubpagesAllowed() ) {
1902 $hash = strpos( $target, '#' );
1903 if( $hash !== false ) {
1904 $suffix = substr( $target, $hash );
1905 $target = substr( $target, 0, $hash );
1910 $target = trim( $target );
1911 # Look at the first character
1912 if( $target != '' && $target{0} === '/' ) {
1913 # / at end means we don't want the slash to be shown
1915 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1916 if( $trailingSlashes ) {
1917 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1919 $noslash = substr( $target, 1 );
1922 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1923 if( '' === $text ) {
1924 $text = $target . $suffix;
1925 } # this might be changed for ugliness reasons
1927 # check for .. subpage backlinks
1929 $nodotdot = $target;
1930 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1932 $nodotdot = substr( $nodotdot, 3 );
1934 if($dotdotcount > 0) {
1935 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1936 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1937 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1938 # / at the end means don't show full path
1939 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1940 $nodotdot = substr( $nodotdot, 0, -1 );
1941 if( '' === $text ) {
1942 $text = $nodotdot . $suffix;
1945 $nodotdot = trim( $nodotdot );
1946 if( $nodotdot != '' ) {
1947 $ret .= '/' . $nodotdot;
1955 wfProfileOut( __METHOD__
);
1960 * Used by doBlockLevels()
1963 /* private */ function closeParagraph() {
1965 if ( '' != $this->mLastSection
) {
1966 $result = '</' . $this->mLastSection
. ">\n";
1968 $this->mInPre
= false;
1969 $this->mLastSection
= '';
1972 # getCommon() returns the length of the longest common substring
1973 # of both arguments, starting at the beginning of both.
1975 /* private */ function getCommon( $st1, $st2 ) {
1976 $fl = strlen( $st1 );
1977 $shorter = strlen( $st2 );
1978 if ( $fl < $shorter ) { $shorter = $fl; }
1980 for ( $i = 0; $i < $shorter; ++
$i ) {
1981 if ( $st1{$i} != $st2{$i} ) { break; }
1985 # These next three functions open, continue, and close the list
1986 # element appropriate to the prefix character passed into them.
1988 /* private */ function openList( $char ) {
1989 $result = $this->closeParagraph();
1991 if ( '*' === $char ) { $result .= '<ul><li>'; }
1992 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1993 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1994 else if ( ';' === $char ) {
1995 $result .= '<dl><dt>';
1996 $this->mDTopen
= true;
1998 else { $result = '<!-- ERR 1 -->'; }
2003 /* private */ function nextItem( $char ) {
2004 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2005 else if ( ':' === $char ||
';' === $char ) {
2007 if ( $this->mDTopen
) { $close = '</dt>'; }
2008 if ( ';' === $char ) {
2009 $this->mDTopen
= true;
2010 return $close . '<dt>';
2012 $this->mDTopen
= false;
2013 return $close . '<dd>';
2016 return '<!-- ERR 2 -->';
2019 /* private */ function closeList( $char ) {
2020 if ( '*' === $char ) { $text = '</li></ul>'; }
2021 else if ( '#' === $char ) { $text = '</li></ol>'; }
2022 else if ( ':' === $char ) {
2023 if ( $this->mDTopen
) {
2024 $this->mDTopen
= false;
2025 $text = '</dt></dl>';
2027 $text = '</dd></dl>';
2030 else { return '<!-- ERR 3 -->'; }
2036 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2039 * @return string the lists rendered as HTML
2041 function doBlockLevels( $text, $linestart ) {
2042 wfProfileIn( __METHOD__
);
2044 # Parsing through the text line by line. The main thing
2045 # happening here is handling of block-level elements p, pre,
2046 # and making lists from lines starting with * # : etc.
2048 $textLines = StringUtils
::explode( "\n", $text );
2050 $lastPrefix = $output = '';
2051 $this->mDTopen
= $inBlockElem = false;
2053 $paragraphStack = false;
2055 foreach ( $textLines as $oLine ) {
2057 if ( !$linestart ) {
2063 $lastPrefixLength = strlen( $lastPrefix );
2064 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2065 $preOpenMatch = preg_match('/<pre/i', $oLine );
2066 if ( !$this->mInPre
) {
2067 # Multiple prefixes may abut each other for nested lists.
2068 $prefixLength = strspn( $oLine, '*#:;' );
2069 $prefix = substr( $oLine, 0, $prefixLength );
2072 $prefix2 = str_replace( ';', ':', $prefix );
2073 $t = substr( $oLine, $prefixLength );
2074 $this->mInPre
= (bool)$preOpenMatch;
2076 # Don't interpret any other prefixes in preformatted text
2078 $prefix = $prefix2 = '';
2083 if( $prefixLength && $lastPrefix === $prefix2 ) {
2084 # Same as the last item, so no need to deal with nesting or opening stuff
2085 $output .= $this->nextItem( substr( $prefix, -1 ) );
2086 $paragraphStack = false;
2088 if ( substr( $prefix, -1 ) === ';') {
2089 # The one nasty exception: definition lists work like this:
2090 # ; title : definition text
2091 # So we check for : in the remainder text to split up the
2092 # title and definition, without b0rking links.
2094 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2096 $output .= $term . $this->nextItem( ':' );
2099 } elseif( $prefixLength ||
$lastPrefixLength ) {
2100 # Either open or close a level...
2101 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2102 $paragraphStack = false;
2104 while( $commonPrefixLength < $lastPrefixLength ) {
2105 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2106 --$lastPrefixLength;
2108 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2109 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2111 while ( $prefixLength > $commonPrefixLength ) {
2112 $char = substr( $prefix, $commonPrefixLength, 1 );
2113 $output .= $this->openList( $char );
2115 if ( ';' === $char ) {
2116 # FIXME: This is dupe of code above
2117 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2119 $output .= $term . $this->nextItem( ':' );
2122 ++
$commonPrefixLength;
2124 $lastPrefix = $prefix2;
2126 if( 0 == $prefixLength ) {
2127 wfProfileIn( __METHOD__
."-paragraph" );
2128 # No prefix (not in list)--go to paragraph mode
2129 // XXX: use a stack for nestable elements like span, table and div
2130 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2131 $closematch = preg_match(
2132 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2133 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2134 if ( $openmatch or $closematch ) {
2135 $paragraphStack = false;
2136 #Â TODO bug 5718: paragraph closed
2137 $output .= $this->closeParagraph();
2138 if ( $preOpenMatch and !$preCloseMatch ) {
2139 $this->mInPre
= true;
2141 if ( $closematch ) {
2142 $inBlockElem = false;
2144 $inBlockElem = true;
2146 } else if ( !$inBlockElem && !$this->mInPre
) {
2147 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2149 if ($this->mLastSection
!== 'pre') {
2150 $paragraphStack = false;
2151 $output .= $this->closeParagraph().'<pre>';
2152 $this->mLastSection
= 'pre';
2154 $t = substr( $t, 1 );
2157 if ( '' == trim($t) ) {
2158 if ( $paragraphStack ) {
2159 $output .= $paragraphStack.'<br />';
2160 $paragraphStack = false;
2161 $this->mLastSection
= 'p';
2163 if ($this->mLastSection
!== 'p' ) {
2164 $output .= $this->closeParagraph();
2165 $this->mLastSection
= '';
2166 $paragraphStack = '<p>';
2168 $paragraphStack = '</p><p>';
2172 if ( $paragraphStack ) {
2173 $output .= $paragraphStack;
2174 $paragraphStack = false;
2175 $this->mLastSection
= 'p';
2176 } else if ($this->mLastSection
!== 'p') {
2177 $output .= $this->closeParagraph().'<p>';
2178 $this->mLastSection
= 'p';
2183 wfProfileOut( __METHOD__
."-paragraph" );
2185 // somewhere above we forget to get out of pre block (bug 785)
2186 if($preCloseMatch && $this->mInPre
) {
2187 $this->mInPre
= false;
2189 if ($paragraphStack === false) {
2193 while ( $prefixLength ) {
2194 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2197 if ( '' != $this->mLastSection
) {
2198 $output .= '</' . $this->mLastSection
. '>';
2199 $this->mLastSection
= '';
2202 wfProfileOut( __METHOD__
);
2207 * Split up a string on ':', ignoring any occurences inside tags
2208 * to prevent illegal overlapping.
2209 * @param string $str the string to split
2210 * @param string &$before set to everything before the ':'
2211 * @param string &$after set to everything after the ':'
2212 * return string the position of the ':', or false if none found
2214 function findColonNoLinks($str, &$before, &$after) {
2215 wfProfileIn( __METHOD__
);
2217 $pos = strpos( $str, ':' );
2218 if( $pos === false ) {
2220 wfProfileOut( __METHOD__
);
2224 $lt = strpos( $str, '<' );
2225 if( $lt === false ||
$lt > $pos ) {
2226 // Easy; no tag nesting to worry about
2227 $before = substr( $str, 0, $pos );
2228 $after = substr( $str, $pos+
1 );
2229 wfProfileOut( __METHOD__
);
2233 // Ugly state machine to walk through avoiding tags.
2234 $state = self
::COLON_STATE_TEXT
;
2236 $len = strlen( $str );
2237 for( $i = 0; $i < $len; $i++
) {
2241 // (Using the number is a performance hack for common cases)
2242 case 0: // self::COLON_STATE_TEXT:
2245 // Could be either a <start> tag or an </end> tag
2246 $state = self
::COLON_STATE_TAGSTART
;
2251 $before = substr( $str, 0, $i );
2252 $after = substr( $str, $i +
1 );
2253 wfProfileOut( __METHOD__
);
2256 // Embedded in a tag; don't break it.
2259 // Skip ahead looking for something interesting
2260 $colon = strpos( $str, ':', $i );
2261 if( $colon === false ) {
2262 // Nothing else interesting
2263 wfProfileOut( __METHOD__
);
2266 $lt = strpos( $str, '<', $i );
2267 if( $stack === 0 ) {
2268 if( $lt === false ||
$colon < $lt ) {
2270 $before = substr( $str, 0, $colon );
2271 $after = substr( $str, $colon +
1 );
2272 wfProfileOut( __METHOD__
);
2276 if( $lt === false ) {
2277 // Nothing else interesting to find; abort!
2278 // We're nested, but there's no close tags left. Abort!
2281 // Skip ahead to next tag start
2283 $state = self
::COLON_STATE_TAGSTART
;
2286 case 1: // self::COLON_STATE_TAG:
2291 $state = self
::COLON_STATE_TEXT
;
2294 // Slash may be followed by >?
2295 $state = self
::COLON_STATE_TAGSLASH
;
2301 case 2: // self::COLON_STATE_TAGSTART:
2304 $state = self
::COLON_STATE_CLOSETAG
;
2307 $state = self
::COLON_STATE_COMMENT
;
2310 // Illegal early close? This shouldn't happen D:
2311 $state = self
::COLON_STATE_TEXT
;
2314 $state = self
::COLON_STATE_TAG
;
2317 case 3: // self::COLON_STATE_CLOSETAG:
2322 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2323 wfProfileOut( __METHOD__
);
2326 $state = self
::COLON_STATE_TEXT
;
2329 case self
::COLON_STATE_TAGSLASH
:
2331 // Yes, a self-closed tag <blah/>
2332 $state = self
::COLON_STATE_TEXT
;
2334 // Probably we're jumping the gun, and this is an attribute
2335 $state = self
::COLON_STATE_TAG
;
2338 case 5: // self::COLON_STATE_COMMENT:
2340 $state = self
::COLON_STATE_COMMENTDASH
;
2343 case self
::COLON_STATE_COMMENTDASH
:
2345 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2347 $state = self
::COLON_STATE_COMMENT
;
2350 case self
::COLON_STATE_COMMENTDASHDASH
:
2352 $state = self
::COLON_STATE_TEXT
;
2354 $state = self
::COLON_STATE_COMMENT
;
2358 throw new MWException( "State machine error in " . __METHOD__
);
2362 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2365 wfProfileOut( __METHOD__
);
2370 * Return value of a magic variable (like PAGENAME)
2374 function getVariableValue( $index ) {
2375 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2378 * Some of these require message or data lookups and can be
2379 * expensive to check many times.
2381 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2382 if ( isset( $this->mVarCache
[$index] ) ) {
2383 return $this->mVarCache
[$index];
2387 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2388 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2391 global $wgLocaltimezone;
2392 if ( isset( $wgLocaltimezone ) ) {
2393 $oldtz = getenv( 'TZ' );
2394 putenv( 'TZ='.$wgLocaltimezone );
2397 wfSuppressWarnings(); // E_STRICT system time bitching
2398 $localTimestamp = date( 'YmdHis', $ts );
2399 $localMonth = date( 'm', $ts );
2400 $localMonthName = date( 'n', $ts );
2401 $localDay = date( 'j', $ts );
2402 $localDay2 = date( 'd', $ts );
2403 $localDayOfWeek = date( 'w', $ts );
2404 $localWeek = date( 'W', $ts );
2405 $localYear = date( 'Y', $ts );
2406 $localHour = date( 'H', $ts );
2407 if ( isset( $wgLocaltimezone ) ) {
2408 putenv( 'TZ='.$oldtz );
2410 wfRestoreWarnings();
2413 case 'currentmonth':
2414 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2415 case 'currentmonthname':
2416 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2417 case 'currentmonthnamegen':
2418 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2419 case 'currentmonthabbrev':
2420 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2422 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2424 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2426 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2427 case 'localmonthname':
2428 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2429 case 'localmonthnamegen':
2430 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2431 case 'localmonthabbrev':
2432 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2434 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2436 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2438 return wfEscapeWikiText( $this->mTitle
->getText() );
2440 return $this->mTitle
->getPartialURL();
2441 case 'fullpagename':
2442 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2443 case 'fullpagenamee':
2444 return $this->mTitle
->getPrefixedURL();
2446 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2447 case 'subpagenamee':
2448 return $this->mTitle
->getSubpageUrlForm();
2449 case 'basepagename':
2450 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2451 case 'basepagenamee':
2452 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2453 case 'talkpagename':
2454 if( $this->mTitle
->canTalk() ) {
2455 $talkPage = $this->mTitle
->getTalkPage();
2456 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2460 case 'talkpagenamee':
2461 if( $this->mTitle
->canTalk() ) {
2462 $talkPage = $this->mTitle
->getTalkPage();
2463 return $talkPage->getPrefixedUrl();
2467 case 'subjectpagename':
2468 $subjPage = $this->mTitle
->getSubjectPage();
2469 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2470 case 'subjectpagenamee':
2471 $subjPage = $this->mTitle
->getSubjectPage();
2472 return $subjPage->getPrefixedUrl();
2474 // Let the edit saving system know we should parse the page
2475 // *after* a revision ID has been assigned.
2476 $this->mOutput
->setFlag( 'vary-revision' );
2477 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2478 return $this->mRevisionId
;
2480 // Let the edit saving system know we should parse the page
2481 // *after* a revision ID has been assigned. This is for null edits.
2482 $this->mOutput
->setFlag( 'vary-revision' );
2483 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2484 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2485 case 'revisionday2':
2486 // Let the edit saving system know we should parse the page
2487 // *after* a revision ID has been assigned. This is for null edits.
2488 $this->mOutput
->setFlag( 'vary-revision' );
2489 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2490 return substr( $this->getRevisionTimestamp(), 6, 2 );
2491 case 'revisionmonth':
2492 // Let the edit saving system know we should parse the page
2493 // *after* a revision ID has been assigned. This is for null edits.
2494 $this->mOutput
->setFlag( 'vary-revision' );
2495 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2496 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2497 case 'revisionyear':
2498 // Let the edit saving system know we should parse the page
2499 // *after* a revision ID has been assigned. This is for null edits.
2500 $this->mOutput
->setFlag( 'vary-revision' );
2501 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2502 return substr( $this->getRevisionTimestamp(), 0, 4 );
2503 case 'revisiontimestamp':
2504 // Let the edit saving system know we should parse the page
2505 // *after* a revision ID has been assigned. This is for null edits.
2506 $this->mOutput
->setFlag( 'vary-revision' );
2507 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2508 return $this->getRevisionTimestamp();
2510 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2512 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2514 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2516 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2517 case 'subjectspace':
2518 return $this->mTitle
->getSubjectNsText();
2519 case 'subjectspacee':
2520 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2521 case 'currentdayname':
2522 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2524 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2526 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2530 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2531 // int to remove the padding
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2534 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2535 case 'localdayname':
2536 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2538 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2540 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2542 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2544 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2545 // int to remove the padding
2546 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2548 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2549 case 'numberofarticles':
2550 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2551 case 'numberoffiles':
2552 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2553 case 'numberofusers':
2554 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2555 case 'numberofpages':
2556 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2557 case 'numberofadmins':
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2559 case 'numberofedits':
2560 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2561 case 'currenttimestamp':
2562 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2563 case 'localtimestamp':
2564 return $this->mVarCache
[$index] = $localTimestamp;
2565 case 'currentversion':
2566 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2572 return $wgServerName;
2574 return $wgScriptPath;
2575 case 'directionmark':
2576 return $wgContLang->getDirMark();
2577 case 'contentlanguage':
2578 global $wgContLanguageCode;
2579 return $wgContLanguageCode;
2582 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2590 * initialise the magic variables (like CURRENTMONTHNAME)
2594 function initialiseVariables() {
2595 wfProfileIn( __METHOD__
);
2596 $variableIDs = MagicWord
::getVariableIDs();
2598 $this->mVariables
= new MagicWordArray( $variableIDs );
2599 wfProfileOut( __METHOD__
);
2603 * Preprocess some wikitext and return the document tree.
2604 * This is the ghost of replace_variables().
2606 * @param string $text The text to parse
2607 * @param integer flags Bitwise combination of:
2608 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2609 * included. Default is to assume a direct page view.
2611 * The generated DOM tree must depend only on the input text and the flags.
2612 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2614 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2615 * change in the DOM tree for a given text, must be passed through the section identifier
2616 * in the section edit link and thus back to extractSections().
2618 * The output of this function is currently only cached in process memory, but a persistent
2619 * cache may be implemented at a later date which takes further advantage of these strict
2620 * dependency requirements.
2624 function preprocessToDom ( $text, $flags = 0 ) {
2625 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2630 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2632 public static function splitWhitespace( $s ) {
2633 $ltrimmed = ltrim( $s );
2634 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2635 $trimmed = rtrim( $ltrimmed );
2636 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2638 $w2 = substr( $ltrimmed, -$diff );
2642 return array( $w1, $trimmed, $w2 );
2646 * Replace magic variables, templates, and template arguments
2647 * with the appropriate text. Templates are substituted recursively,
2648 * taking care to avoid infinite loops.
2650 * Note that the substitution depends on value of $mOutputType:
2651 * self::OT_WIKI: only {{subst:}} templates
2652 * self::OT_PREPROCESS: templates but not extension tags
2653 * self::OT_HTML: all templates and extension tags
2655 * @param string $tex The text to transform
2656 * @param PPFrame $frame Object describing the arguments passed to the template.
2657 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2658 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2659 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2662 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2663 # Prevent too big inclusions
2664 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2668 wfProfileIn( __METHOD__
);
2670 if ( $frame === false ) {
2671 $frame = $this->getPreprocessor()->newFrame();
2672 } elseif ( !( $frame instanceof PPFrame
) ) {
2673 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2674 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2677 $dom = $this->preprocessToDom( $text );
2678 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2679 $text = $frame->expand( $dom, $flags );
2681 wfProfileOut( __METHOD__
);
2685 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2686 static function createAssocArgs( $args ) {
2687 $assocArgs = array();
2689 foreach( $args as $arg ) {
2690 $eqpos = strpos( $arg, '=' );
2691 if ( $eqpos === false ) {
2692 $assocArgs[$index++
] = $arg;
2694 $name = trim( substr( $arg, 0, $eqpos ) );
2695 $value = trim( substr( $arg, $eqpos+
1 ) );
2696 if ( $value === false ) {
2699 if ( $name !== false ) {
2700 $assocArgs[$name] = $value;
2709 * Warn the user when a parser limitation is reached
2710 * Will warn at most once the user per limitation type
2712 * @param string $limitationType, should be one of:
2713 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2714 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2715 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2716 * @params int $current, $max When an explicit limit has been
2717 * exceeded, provide the values (optional)
2719 function limitationWarn( $limitationType, $current=null, $max=null) {
2720 $msgName = $limitationType . '-warning';
2721 //does no harm if $current and $max are present but are unnecessary for the message
2722 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2723 $this->mOutput
->addWarning( $warning );
2724 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2726 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2731 * Return the text of a template, after recursively
2732 * replacing any variables or templates within the template.
2734 * @param array $piece The parts of the template
2735 * $piece['title']: the title, i.e. the part before the |
2736 * $piece['parts']: the parameter array
2737 * $piece['lineStart']: whether the brace was at the start of a line
2738 * @param PPFrame The current frame, contains template arguments
2739 * @return string the text of the template
2742 function braceSubstitution( $piece, $frame ) {
2743 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2744 wfProfileIn( __METHOD__
);
2745 wfProfileIn( __METHOD__
.'-setup' );
2748 $found = false; # $text has been filled
2749 $nowiki = false; # wiki markup in $text should be escaped
2750 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2751 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2752 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2753 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2755 # Title object, where $text came from
2758 # $part1 is the bit before the first |, and must contain only title characters.
2759 # Various prefixes will be stripped from it later.
2760 $titleWithSpaces = $frame->expand( $piece['title'] );
2761 $part1 = trim( $titleWithSpaces );
2764 # Original title text preserved for various purposes
2765 $originalTitle = $part1;
2767 # $args is a list of argument nodes, starting from index 0, not including $part1
2768 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2769 wfProfileOut( __METHOD__
.'-setup' );
2772 wfProfileIn( __METHOD__
.'-modifiers' );
2774 $mwSubst = MagicWord
::get( 'subst' );
2775 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2776 # One of two possibilities is true:
2777 # 1) Found SUBST but not in the PST phase
2778 # 2) Didn't find SUBST and in the PST phase
2779 # In either case, return without further processing
2780 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2787 if ( !$found && $args->getLength() == 0 ) {
2788 $id = $this->mVariables
->matchStartToEnd( $part1 );
2789 if ( $id !== false ) {
2790 $text = $this->getVariableValue( $id );
2791 if (MagicWord
::getCacheTTL($id)>-1)
2792 $this->mOutput
->mContainsOldMagic
= true;
2797 # MSG, MSGNW and RAW
2800 $mwMsgnw = MagicWord
::get( 'msgnw' );
2801 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2804 # Remove obsolete MSG:
2805 $mwMsg = MagicWord
::get( 'msg' );
2806 $mwMsg->matchStartAndRemove( $part1 );
2810 $mwRaw = MagicWord
::get( 'raw' );
2811 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2812 $forceRawInterwiki = true;
2815 wfProfileOut( __METHOD__
.'-modifiers' );
2819 wfProfileIn( __METHOD__
. '-pfunc' );
2821 $colonPos = strpos( $part1, ':' );
2822 if ( $colonPos !== false ) {
2823 # Case sensitive functions
2824 $function = substr( $part1, 0, $colonPos );
2825 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2826 $function = $this->mFunctionSynonyms
[1][$function];
2828 # Case insensitive functions
2829 $function = strtolower( $function );
2830 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2831 $function = $this->mFunctionSynonyms
[0][$function];
2837 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2838 $initialArgs = array( &$this );
2839 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2840 if ( $flags & SFH_OBJECT_ARGS
) {
2841 # Add a frame parameter, and pass the arguments as an array
2842 $allArgs = $initialArgs;
2843 $allArgs[] = $frame;
2844 for ( $i = 0; $i < $args->getLength(); $i++
) {
2845 $funcArgs[] = $args->item( $i );
2847 $allArgs[] = $funcArgs;
2849 # Convert arguments to plain text
2850 for ( $i = 0; $i < $args->getLength(); $i++
) {
2851 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2853 $allArgs = array_merge( $initialArgs, $funcArgs );
2856 # Workaround for PHP bug 35229 and similar
2857 if ( !is_callable( $callback ) ) {
2858 throw new MWException( "Tag hook for $name is not callable\n" );
2860 $result = call_user_func_array( $callback, $allArgs );
2863 $preprocessFlags = 0;
2865 if ( is_array( $result ) ) {
2866 if ( isset( $result[0] ) ) {
2868 unset( $result[0] );
2871 // Extract flags into the local scope
2872 // This allows callers to set flags such as nowiki, found, etc.
2878 $text = $this->preprocessToDom( $text, $preprocessFlags );
2883 wfProfileOut( __METHOD__
. '-pfunc' );
2886 # Finish mangling title and then check for loops.
2887 # Set $title to a Title object and $titleText to the PDBK
2890 # Split the title into page and subpage
2892 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2893 if ($subpage !== '') {
2894 $ns = $this->mTitle
->getNamespace();
2896 $title = Title
::newFromText( $part1, $ns );
2898 $titleText = $title->getPrefixedText();
2899 # Check for language variants if the template is not found
2900 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2901 $wgContLang->findVariantLink( $part1, $title, true );
2903 # Do infinite loop check
2904 if ( !$frame->loopCheck( $title ) ) {
2906 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2907 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2909 # Do recursion depth check
2910 $limit = $this->mOptions
->getMaxTemplateDepth();
2911 if ( $frame->depth
>= $limit ) {
2913 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2918 # Load from database
2919 if ( !$found && $title ) {
2920 wfProfileIn( __METHOD__
. '-loadtpl' );
2921 if ( !$title->isExternal() ) {
2922 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2923 $text = SpecialPage
::capturePath( $title );
2924 if ( is_string( $text ) ) {
2927 $this->disableCache();
2929 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2930 $found = false; //access denied
2931 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2933 list( $text, $title ) = $this->getTemplateDom( $title );
2934 if ( $text !== false ) {
2940 # If the title is valid but undisplayable, make a link to it
2941 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2942 $text = "[[:$titleText]]";
2945 } elseif ( $title->isTrans() ) {
2946 // Interwiki transclusion
2947 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2948 $text = $this->interwikiTransclude( $title, 'render' );
2951 $text = $this->interwikiTransclude( $title, 'raw' );
2952 // Preprocess it like a template
2953 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2958 wfProfileOut( __METHOD__
. '-loadtpl' );
2961 # If we haven't found text to substitute by now, we're done
2962 # Recover the source wikitext and return it
2964 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2965 wfProfileOut( __METHOD__
);
2966 return array( 'object' => $text );
2969 # Expand DOM-style return values in a child frame
2970 if ( $isChildObj ) {
2971 # Clean up argument array
2972 $newFrame = $frame->newChild( $args, $title );
2975 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2976 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2977 # Expansion is eligible for the empty-frame cache
2978 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2979 $text = $this->mTplExpandCache
[$titleText];
2981 $text = $newFrame->expand( $text );
2982 $this->mTplExpandCache
[$titleText] = $text;
2985 # Uncached expansion
2986 $text = $newFrame->expand( $text );
2989 if ( $isLocalObj && $nowiki ) {
2990 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2991 $isLocalObj = false;
2994 # Replace raw HTML by a placeholder
2995 # Add a blank line preceding, to prevent it from mucking up
2996 # immediately preceding headings
2998 $text = "\n\n" . $this->insertStripItem( $text );
3000 # Escape nowiki-style return values
3001 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3002 $text = wfEscapeWikiText( $text );
3004 # Bug 529: if the template begins with a table or block-level
3005 # element, it should be treated as beginning a new line.
3006 # This behaviour is somewhat controversial.
3007 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3008 $text = "\n" . $text;
3011 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3012 # Error, oversize inclusion
3013 $text = "[[$originalTitle]]" .
3014 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3015 $this->limitationWarn( 'post-expand-template-inclusion' );
3018 if ( $isLocalObj ) {
3019 $ret = array( 'object' => $text );
3021 $ret = array( 'text' => $text );
3024 wfProfileOut( __METHOD__
);
3029 * Get the semi-parsed DOM representation of a template with a given title,
3030 * and its redirect destination title. Cached.
3032 function getTemplateDom( $title ) {
3033 $cacheTitle = $title;
3034 $titleText = $title->getPrefixedDBkey();
3036 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3037 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3038 $title = Title
::makeTitle( $ns, $dbk );
3039 $titleText = $title->getPrefixedDBkey();
3041 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3042 return array( $this->mTplDomCache
[$titleText], $title );
3045 // Cache miss, go to the database
3046 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3048 if ( $text === false ) {
3049 $this->mTplDomCache
[$titleText] = false;
3050 return array( false, $title );
3053 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3054 $this->mTplDomCache
[ $titleText ] = $dom;
3056 if (! $title->equals($cacheTitle)) {
3057 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3058 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3061 return array( $dom, $title );
3065 * Fetch the unparsed text of a template and register a reference to it.
3067 function fetchTemplateAndTitle( $title ) {
3068 $templateCb = $this->mOptions
->getTemplateCallback();
3069 $stuff = call_user_func( $templateCb, $title, $this );
3070 $text = $stuff['text'];
3071 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3072 if ( isset( $stuff['deps'] ) ) {
3073 foreach ( $stuff['deps'] as $dep ) {
3074 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3077 return array($text,$finalTitle);
3080 function fetchTemplate( $title ) {
3081 $rv = $this->fetchTemplateAndTitle($title);
3086 * Static function to get a template
3087 * Can be overridden via ParserOptions::setTemplateCallback().
3089 static function statelessFetchTemplate( $title, $parser=false ) {
3090 $text = $skip = false;
3091 $finalTitle = $title;
3094 // Loop to fetch the article, with up to 1 redirect
3095 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3096 # Give extensions a chance to select the revision instead
3097 $id = false; // Assume current
3098 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3104 'page_id' => $title->getArticleID(),
3108 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3109 $rev_id = $rev ?
$rev->getId() : 0;
3110 // If there is no current revision, there is no page
3111 if( $id === false && !$rev ) {
3112 $linkCache = LinkCache
::singleton();
3113 $linkCache->addBadLinkObj( $title );
3118 'page_id' => $title->getArticleID(),
3119 'rev_id' => $rev_id );
3122 $text = $rev->getText();
3123 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3125 $message = $wgLang->lcfirst( $title->getText() );
3126 $text = wfMsgForContentNoTrans( $message );
3127 if( wfEmptyMsg( $message, $text ) ) {
3134 if ( $text === false ) {
3138 $finalTitle = $title;
3139 $title = Title
::newFromRedirect( $text );
3143 'finalTitle' => $finalTitle,
3148 * Transclude an interwiki link.
3150 function interwikiTransclude( $title, $action ) {
3151 global $wgEnableScaryTranscluding;
3153 if (!$wgEnableScaryTranscluding)
3154 return wfMsg('scarytranscludedisabled');
3156 $url = $title->getFullUrl( "action=$action" );
3158 if (strlen($url) > 255)
3159 return wfMsg('scarytranscludetoolong');
3160 return $this->fetchScaryTemplateMaybeFromCache($url);
3163 function fetchScaryTemplateMaybeFromCache($url) {
3164 global $wgTranscludeCacheExpiry;
3165 $dbr = wfGetDB(DB_SLAVE
);
3166 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3167 array('tc_url' => $url));
3169 $time = $obj->tc_time
;
3170 $text = $obj->tc_contents
;
3171 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3176 $text = Http
::get($url);
3178 return wfMsg('scarytranscludefailed', $url);
3180 $dbw = wfGetDB(DB_MASTER
);
3181 $dbw->replace('transcache', array('tc_url'), array(
3183 'tc_time' => time(),
3184 'tc_contents' => $text));
3190 * Triple brace replacement -- used for template arguments
3193 function argSubstitution( $piece, $frame ) {
3194 wfProfileIn( __METHOD__
);
3197 $parts = $piece['parts'];
3198 $nameWithSpaces = $frame->expand( $piece['title'] );
3199 $argName = trim( $nameWithSpaces );
3201 $text = $frame->getArgument( $argName );
3202 if ( $text === false && $parts->getLength() > 0
3206 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3209 # No match in frame, use the supplied default
3210 $object = $parts->item( 0 )->getChildren();
3212 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3213 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3214 $this->limitationWarn( 'post-expand-template-argument' );
3217 if ( $text === false && $object === false ) {
3219 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3221 if ( $error !== false ) {
3224 if ( $object !== false ) {
3225 $ret = array( 'object' => $object );
3227 $ret = array( 'text' => $text );
3230 wfProfileOut( __METHOD__
);
3235 * Return the text to be used for a given extension tag.
3236 * This is the ghost of strip().
3238 * @param array $params Associative array of parameters:
3239 * name PPNode for the tag name
3240 * attr PPNode for unparsed text where tag attributes are thought to be
3241 * attributes Optional associative array of parsed attributes
3242 * inner Contents of extension element
3243 * noClose Original text did not have a close tag
3244 * @param PPFrame $frame
3246 function extensionSubstitution( $params, $frame ) {
3247 global $wgRawHtml, $wgContLang;
3249 $name = $frame->expand( $params['name'] );
3250 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3251 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3253 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3255 if ( $this->ot
['html'] ) {
3256 $name = strtolower( $name );
3258 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3259 if ( isset( $params['attributes'] ) ) {
3260 $attributes = $attributes +
$params['attributes'];
3268 throw new MWException( '<html> extension tag encountered unexpectedly' );
3271 $output = Xml
::escapeTagsOnly( $content );
3274 $output = $wgContLang->armourMath(
3275 MathRenderer
::renderMath( $content, $attributes ) );
3278 $output = $this->renderImageGallery( $content, $attributes );
3281 if( isset( $this->mTagHooks
[$name] ) ) {
3282 # Workaround for PHP bug 35229 and similar
3283 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3284 throw new MWException( "Tag hook for $name is not callable\n" );
3286 $output = call_user_func_array( $this->mTagHooks
[$name],
3287 array( $content, $attributes, $this ) );
3289 $output = '<span class="error">Invalid tag extension name: ' .
3290 htmlspecialchars( $name ) . '</span>';
3294 if ( is_null( $attrText ) ) {
3297 if ( isset( $params['attributes'] ) ) {
3298 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3299 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3300 htmlspecialchars( $attrValue ) . '"';
3303 if ( $content === null ) {
3304 $output = "<$name$attrText/>";
3306 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3307 $output = "<$name$attrText>$content$close";
3311 if ( $name === 'html' ||
$name === 'nowiki' ) {
3312 $this->mStripState
->nowiki
->setPair( $marker, $output );
3314 $this->mStripState
->general
->setPair( $marker, $output );
3320 * Increment an include size counter
3322 * @param string $type The type of expansion
3323 * @param integer $size The size of the text
3324 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3326 function incrementIncludeSize( $type, $size ) {
3327 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3330 $this->mIncludeSizes
[$type] +
= $size;
3336 * Increment the expensive function count
3338 * @return boolean False if the limit has been exceeded
3340 function incrementExpensiveFunctionCount() {
3341 global $wgExpensiveParserFunctionLimit;
3342 $this->mExpensiveFunctionCount++
;
3343 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3350 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3351 * Fills $this->mDoubleUnderscores, returns the modified text
3353 function doDoubleUnderscore( $text ) {
3354 // The position of __TOC__ needs to be recorded
3355 $mw = MagicWord
::get( 'toc' );
3356 if( $mw->match( $text ) ) {
3357 $this->mShowToc
= true;
3358 $this->mForceTocPosition
= true;
3360 // Set a placeholder. At the end we'll fill it in with the TOC.
3361 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3363 // Only keep the first one.
3364 $text = $mw->replace( '', $text );
3367 // Now match and remove the rest of them
3368 $mwa = MagicWord
::getDoubleUnderscoreArray();
3369 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3371 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3372 $this->mOutput
->mNoGallery
= true;
3374 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3375 $this->mShowToc
= false;
3377 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3378 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3380 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3381 if ( $containerCategory ) {
3382 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3384 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3387 # (bug 8068) Allow control over whether robots index a page.
3389 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3390 # is not desirable, the last one on the page should win.
3391 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3392 $this->mOutput
->setIndexPolicy( 'noindex' );
3393 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3394 $this->mOutput
->setIndexPolicy( 'index' );
3401 * This function accomplishes several tasks:
3402 * 1) Auto-number headings if that option is enabled
3403 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3404 * 3) Add a Table of contents on the top for users who have enabled the option
3405 * 4) Auto-anchor headings
3407 * It loops through all headlines, collects the necessary data, then splits up the
3408 * string and re-inserts the newly formatted headlines.
3410 * @param string $text
3411 * @param boolean $isMain
3414 function formatHeadings( $text, $isMain=true ) {
3415 global $wgMaxTocLevel, $wgContLang;
3417 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3418 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3421 $showEditLink = $this->mOptions
->getEditSection();
3424 # Inhibit editsection links if requested in the page
3425 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3429 # Get all headlines for numbering them and adding funky stuff like [edit]
3430 # links - this is for later, but we need the number of headlines right now
3432 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3434 # if there are fewer than 4 headlines in the article, do not show TOC
3435 # unless it's been explicitly enabled.
3436 $enoughToc = $this->mShowToc
&&
3437 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3439 # Allow user to stipulate that a page should have a "new section"
3440 # link added via __NEWSECTIONLINK__
3441 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3442 $this->mOutput
->setNewSection( true );
3445 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3446 # override above conditions and always show TOC above first header
3447 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3448 $this->mShowToc
= true;
3452 # We need this to perform operations on the HTML
3453 $sk = $this->mOptions
->getSkin();
3459 # Ugh .. the TOC should have neat indentation levels which can be
3460 # passed to the skin functions. These are determined here
3464 $sublevelCount = array();
3465 $levelCount = array();
3471 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3472 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3475 foreach( $matches[3] as $headline ) {
3476 $isTemplate = false;
3478 $sectionIndex = false;
3480 $markerMatches = array();
3481 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3482 $serial = $markerMatches[1];
3483 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3484 $isTemplate = ($titleText != $baseTitleText);
3485 $headline = preg_replace("/^$markerRegex/", "", $headline);
3489 $prevlevel = $level;
3490 $prevtoclevel = $toclevel;
3492 $level = $matches[1][$headlineCount];
3494 if( $doNumberHeadings ||
$enoughToc ) {
3496 if ( $level > $prevlevel ) {
3497 # Increase TOC level
3499 $sublevelCount[$toclevel] = 0;
3500 if( $toclevel<$wgMaxTocLevel ) {
3501 $prevtoclevel = $toclevel;
3502 $toc .= $sk->tocIndent();
3506 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3507 # Decrease TOC level, find level to jump to
3509 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3510 # Can only go down to level 1
3513 for ($i = $toclevel; $i > 0; $i--) {
3514 if ( $levelCount[$i] == $level ) {
3515 # Found last matching level
3519 elseif ( $levelCount[$i] < $level ) {
3520 # Found first matching level below current level
3526 if( $toclevel<$wgMaxTocLevel ) {
3527 if($prevtoclevel < $wgMaxTocLevel) {
3528 # Unindent only if the previous toc level was shown :p
3529 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3530 $prevtoclevel = $toclevel;
3532 $toc .= $sk->tocLineEnd();
3537 # No change in level, end TOC line
3538 if( $toclevel<$wgMaxTocLevel ) {
3539 $toc .= $sk->tocLineEnd();
3543 $levelCount[$toclevel] = $level;
3545 # count number of headlines for each level
3546 @$sublevelCount[$toclevel]++
;
3548 for( $i = 1; $i <= $toclevel; $i++
) {
3549 if( !empty( $sublevelCount[$i] ) ) {
3553 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3559 # The safe header is a version of the header text safe to use for links
3560 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3561 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3563 # Remove link placeholders by the link text.
3564 # <!--LINK number-->
3566 # link text with suffix
3567 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3569 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3570 $tocline = preg_replace(
3571 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3575 $tocline = trim( $tocline );
3577 # For the anchor, strip out HTML-y stuff period
3578 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3579 $safeHeadline = trim( $safeHeadline );
3581 # Save headline for section edit hint before it's escaped
3582 $headlineHint = $safeHeadline;
3583 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3584 # HTML names must be case-insensitively unique (bug 10721)
3585 $arrayKey = strtolower( $safeHeadline );
3587 # count how many in assoc. array so we can track dupes in anchors
3588 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3589 $refcount[$headlineCount] = $refers[$arrayKey];
3591 # Don't number the heading if it is the only one (looks silly)
3592 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3593 # the two are different if the line contains a link
3594 $headline=$numbering . ' ' . $headline;
3597 # Create the anchor for linking from the TOC to the section
3598 $anchor = $safeHeadline;
3599 if($refcount[$headlineCount] > 1 ) {
3600 $anchor .= '_' . $refcount[$headlineCount];
3602 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3603 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3604 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3606 # give headline the correct <h#> tag
3607 if( $showEditLink && $sectionIndex !== false ) {
3609 # Put a T flag in the section identifier, to indicate to extractSections()
3610 # that sections inside <includeonly> should be counted.
3611 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3613 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3618 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3623 $this->mOutput
->setSections( $tocraw );
3625 # Never ever show TOC if no headers
3626 if( $numVisible < 1 ) {
3631 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3632 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3634 $toc = $sk->tocList( $toc );
3637 # split up and insert constructed headlines
3639 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3642 foreach( $blocks as $block ) {
3643 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3644 # This is the [edit] link that appears for the top block of text when
3645 # section editing is enabled
3647 # Disabled because it broke block formatting
3648 # For example, a bullet point in the top line
3649 # $full .= $sk->editSectionLink(0);
3652 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3653 # Top anchor now in skin
3657 if( !empty( $head[$i] ) ) {
3662 if( $this->mForceTocPosition
) {
3663 return str_replace( '<!--MWTOC-->', $toc, $full );
3670 * Transform wiki markup when saving a page by doing \r\n -> \n
3671 * conversion, substitting signatures, {{subst:}} templates, etc.
3673 * @param string $text the text to transform
3674 * @param Title &$title the Title object for the current article
3675 * @param User &$user the User object describing the current user
3676 * @param ParserOptions $options parsing options
3677 * @param bool $clearState whether to clear the parser state first
3678 * @return string the altered wiki markup
3681 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3682 $this->mOptions
= $options;
3683 $this->setTitle( $title );
3684 $this->setOutputType( self
::OT_WIKI
);
3686 if ( $clearState ) {
3687 $this->clearState();
3693 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3694 $text = $this->pstPass2( $text, $user );
3695 $text = $this->mStripState
->unstripBoth( $text );
3700 * Pre-save transform helper function
3703 function pstPass2( $text, $user ) {
3704 global $wgContLang, $wgLocaltimezone;
3706 /* Note: This is the timestamp saved as hardcoded wikitext to
3707 * the database, we use $wgContLang here in order to give
3708 * everyone the same signature and use the default one rather
3709 * than the one selected in each user's preferences.
3711 * (see also bug 12815)
3713 $ts = $this->mOptions
->getTimestamp();
3714 $tz = wfMsgForContent( 'timezone-utc' );
3715 if ( isset( $wgLocaltimezone ) ) {
3716 $unixts = wfTimestamp( TS_UNIX
, $ts );
3717 $oldtz = getenv( 'TZ' );
3718 putenv( 'TZ='.$wgLocaltimezone );
3719 $ts = date( 'YmdHis', $unixts );
3720 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3721 putenv( 'TZ='.$oldtz );
3724 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3726 # Variable replacement
3727 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3728 $text = $this->replaceVariables( $text );
3731 $sigText = $this->getUserSig( $user );
3732 $text = strtr( $text, array(
3734 '~~~~' => "$sigText $d",
3738 # Context links: [[|name]] and [[name (context)|]]
3740 global $wgLegalTitleChars;
3741 $tc = "[$wgLegalTitleChars]";
3742 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3744 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3745 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3746 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3747 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3749 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3750 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3751 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3752 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3754 $t = $this->mTitle
->getText();
3756 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3757 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3758 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3759 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3761 # if there's no context, don't bother duplicating the title
3762 $text = preg_replace( $p2, '[[\\1]]', $text );
3765 # Trim trailing whitespace
3766 $text = rtrim( $text );
3772 * Fetch the user's signature text, if any, and normalize to
3773 * validated, ready-to-insert wikitext.
3779 function getUserSig( &$user ) {
3780 global $wgMaxSigChars;
3782 $username = $user->getName();
3783 $nickname = $user->getOption( 'nickname' );
3784 $nickname = $nickname === '' ?
$username : $nickname;
3786 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3787 $nickname = $username;
3788 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3789 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3790 # Sig. might contain markup; validate this
3791 if( $this->validateSig( $nickname ) !== false ) {
3792 # Validated; clean up (if needed) and return it
3793 return $this->cleanSig( $nickname, true );
3795 # Failed to validate; fall back to the default
3796 $nickname = $username;
3797 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3801 // Make sure nickname doesnt get a sig in a sig
3802 $nickname = $this->cleanSigInSig( $nickname );
3804 # If we're still here, make it a link to the user page
3805 $userText = wfEscapeWikiText( $username );
3806 $nickText = wfEscapeWikiText( $nickname );
3807 if ( $user->isAnon() ) {
3808 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3810 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3815 * Check that the user's signature contains no bad XML
3817 * @param string $text
3818 * @return mixed An expanded string, or false if invalid.
3820 function validateSig( $text ) {
3821 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3825 * Clean up signature text
3827 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3828 * 2) Substitute all transclusions
3830 * @param string $text
3831 * @param $parsing Whether we're cleaning (preferences save) or parsing
3832 * @return string Signature text
3834 function cleanSig( $text, $parsing = false ) {
3837 $this->clearState();
3838 $this->setTitle( $wgTitle );
3839 $this->mOptions
= new ParserOptions
;
3840 $this->setOutputType
= self
::OT_PREPROCESS
;
3843 # Option to disable this feature
3844 if ( !$this->mOptions
->getCleanSignatures() ) {
3848 # FIXME: regex doesn't respect extension tags or nowiki
3849 # => Move this logic to braceSubstitution()
3850 $substWord = MagicWord
::get( 'subst' );
3851 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3852 $substText = '{{' . $substWord->getSynonym( 0 );
3854 $text = preg_replace( $substRegex, $substText, $text );
3855 $text = $this->cleanSigInSig( $text );
3856 $dom = $this->preprocessToDom( $text );
3857 $frame = $this->getPreprocessor()->newFrame();
3858 $text = $frame->expand( $dom );
3861 $text = $this->mStripState
->unstripBoth( $text );
3868 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3869 * @param string $text
3870 * @return string Signature text with /~{3,5}/ removed
3872 function cleanSigInSig( $text ) {
3873 $text = preg_replace( '/~{3,5}/', '', $text );
3878 * Set up some variables which are usually set up in parse()
3879 * so that an external function can call some class members with confidence
3882 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3883 $this->setTitle( $title );
3884 $this->mOptions
= $options;
3885 $this->setOutputType( $outputType );
3886 if ( $clearState ) {
3887 $this->clearState();
3892 * Wrapper for preprocess()
3894 * @param string $text the text to preprocess
3895 * @param ParserOptions $options options
3899 function transformMsg( $text, $options ) {
3901 static $executing = false;
3903 # Guard against infinite recursion
3909 wfProfileIn(__METHOD__
);
3910 $text = $this->preprocess( $text, $wgTitle, $options );
3913 wfProfileOut(__METHOD__
);
3918 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3919 * The callback should have the following form:
3920 * function myParserHook( $text, $params, &$parser ) { ... }
3922 * Transform and return $text. Use $parser for any required context, e.g. use
3923 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3927 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3928 * @param mixed $callback The callback function (and object) to use for the tag
3930 * @return The old value of the mTagHooks array associated with the hook
3932 function setHook( $tag, $callback ) {
3933 $tag = strtolower( $tag );
3934 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3935 $this->mTagHooks
[$tag] = $callback;
3936 if( !in_array( $tag, $this->mStripList
) ) {
3937 $this->mStripList
[] = $tag;
3943 function setTransparentTagHook( $tag, $callback ) {
3944 $tag = strtolower( $tag );
3945 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3946 $this->mTransparentTagHooks
[$tag] = $callback;
3952 * Remove all tag hooks
3954 function clearTagHooks() {
3955 $this->mTagHooks
= array();
3956 $this->mStripList
= $this->mDefaultStripList
;
3960 * Create a function, e.g. {{sum:1|2|3}}
3961 * The callback function should have the form:
3962 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3964 * Or with SFH_OBJECT_ARGS:
3965 * function myParserFunction( $parser, $frame, $args ) { ... }
3967 * The callback may either return the text result of the function, or an array with the text
3968 * in element 0, and a number of flags in the other elements. The names of the flags are
3969 * specified in the keys. Valid flags are:
3970 * found The text returned is valid, stop processing the template. This
3972 * nowiki Wiki markup in the return value should be escaped
3973 * isHTML The returned text is HTML, armour it against wikitext transformation
3977 * @param string $id The magic word ID
3978 * @param mixed $callback The callback function (and object) to use
3979 * @param integer $flags a combination of the following flags:
3980 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3982 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3983 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3984 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3985 * the arguments, and to control the way they are expanded.
3987 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3988 * arguments, for instance:
3989 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3991 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3992 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3993 * working if/when this is changed.
3995 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3998 * Please read the documentation in includes/parser/Preprocessor.php for more information
3999 * about the methods available in PPFrame and PPNode.
4001 * @return The old callback function for this name, if any
4003 function setFunctionHook( $id, $callback, $flags = 0 ) {
4004 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4005 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4007 # Add to function cache
4008 $mw = MagicWord
::get( $id );
4010 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4012 $synonyms = $mw->getSynonyms();
4013 $sensitive = intval( $mw->isCaseSensitive() );
4015 foreach ( $synonyms as $syn ) {
4017 if ( !$sensitive ) {
4018 $syn = strtolower( $syn );
4021 if ( !( $flags & SFH_NO_HASH
) ) {
4024 # Remove trailing colon
4025 if ( substr( $syn, -1, 1 ) === ':' ) {
4026 $syn = substr( $syn, 0, -1 );
4028 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4034 * Get all registered function hook identifiers
4038 function getFunctionHooks() {
4039 return array_keys( $this->mFunctionHooks
);
4043 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4044 * Placeholders created in Skin::makeLinkObj()
4045 * Returns an array of link CSS classes, indexed by PDBK.
4047 function replaceLinkHolders( &$text, $options = 0 ) {
4048 return $this->mLinkHolders
->replace( $text );
4052 * Replace <!--LINK--> link placeholders with plain text of links
4053 * (not HTML-formatted).
4054 * @param string $text
4057 function replaceLinkHoldersText( $text ) {
4058 return $this->mLinkHolders
->replaceText( $text );
4062 * Tag hook handler for 'pre'.
4064 function renderPreTag( $text, $attribs ) {
4065 // Backwards-compatibility hack
4066 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4068 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4069 return wfOpenElement( 'pre', $attribs ) .
4070 Xml
::escapeTagsOnly( $content ) .
4075 * Renders an image gallery from a text with one line per image.
4076 * text labels may be given by using |-style alternative text. E.g.
4077 * Image:one.jpg|The number "1"
4078 * Image:tree.jpg|A tree
4079 * given as text will return the HTML of a gallery with two images,
4080 * labeled 'The number "1"' and
4083 function renderImageGallery( $text, $params ) {
4084 $ig = new ImageGallery();
4085 $ig->setContextTitle( $this->mTitle
);
4086 $ig->setShowBytes( false );
4087 $ig->setShowFilename( false );
4088 $ig->setParser( $this );
4089 $ig->setHideBadImages();
4090 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4091 $ig->useSkin( $this->mOptions
->getSkin() );
4092 $ig->mRevisionId
= $this->mRevisionId
;
4094 if( isset( $params['caption'] ) ) {
4095 $caption = $params['caption'];
4096 $caption = htmlspecialchars( $caption );
4097 $caption = $this->replaceInternalLinks( $caption );
4098 $ig->setCaptionHtml( $caption );
4100 if( isset( $params['perrow'] ) ) {
4101 $ig->setPerRow( $params['perrow'] );
4103 if( isset( $params['widths'] ) ) {
4104 $ig->setWidths( $params['widths'] );
4106 if( isset( $params['heights'] ) ) {
4107 $ig->setHeights( $params['heights'] );
4110 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4112 $lines = StringUtils
::explode( "\n", $text );
4113 foreach ( $lines as $line ) {
4114 # match lines like these:
4115 # Image:someimage.jpg|This is some image
4117 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4119 if ( count( $matches ) == 0 ) {
4123 if ( strpos( $matches[0], '%' ) !== false )
4124 $matches[1] = urldecode( $matches[1] );
4125 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4127 if( is_null( $nt ) ) {
4128 # Bogus title. Ignore these so we don't bomb out later.
4131 if ( isset( $matches[3] ) ) {
4132 $label = $matches[3];
4137 $html = $this->recursiveTagParse( trim( $label ) );
4139 $ig->add( $nt, $html );
4141 # Only add real images (bug #5586)
4142 if ( $nt->getNamespace() == NS_IMAGE
) {
4143 $this->mOutput
->addImage( $nt->getDBkey() );
4146 return $ig->toHTML();
4149 function getImageParams( $handler ) {
4151 $handlerClass = get_class( $handler );
4155 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4156 // Initialise static lists
4157 static $internalParamNames = array(
4158 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4159 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4160 'bottom', 'text-bottom' ),
4161 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4162 'upright', 'border' ),
4164 static $internalParamMap;
4165 if ( !$internalParamMap ) {
4166 $internalParamMap = array();
4167 foreach ( $internalParamNames as $type => $names ) {
4168 foreach ( $names as $name ) {
4169 $magicName = str_replace( '-', '_', "img_$name" );
4170 $internalParamMap[$magicName] = array( $type, $name );
4175 // Add handler params
4176 $paramMap = $internalParamMap;
4178 $handlerParamMap = $handler->getParamMap();
4179 foreach ( $handlerParamMap as $magic => $paramName ) {
4180 $paramMap[$magic] = array( 'handler', $paramName );
4183 $this->mImageParams
[$handlerClass] = $paramMap;
4184 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4186 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4190 * Parse image options text and use it to make an image
4191 * @param Title $title
4192 * @param string $options
4193 * @param LinkHolderArray $holders
4195 function makeImage( $title, $options, $holders = false ) {
4196 # Check if the options text is of the form "options|alt text"
4198 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4199 # * left no resizing, just left align. label is used for alt= only
4200 # * right same, but right aligned
4201 # * none same, but not aligned
4202 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4203 # * center center the image
4204 # * framed Keep original image size, no magnify-button.
4205 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4206 # * upright reduce width for upright images, rounded to full __0 px
4207 # * border draw a 1px border around the image
4208 # vertical-align values (no % or length right now):
4218 $parts = StringUtils
::explode( "|", $options );
4219 $sk = $this->mOptions
->getSkin();
4221 # Give extensions a chance to select the file revision for us
4222 $skip = $time = $descQuery = false;
4223 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4226 return $sk->link( $title );
4230 $file = wfFindFile( $title, $time );
4231 $handler = $file ?
$file->getHandler() : false;
4233 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4235 # Process the input parameters
4237 $params = array( 'frame' => array(), 'handler' => array(),
4238 'horizAlign' => array(), 'vertAlign' => array() );
4239 foreach( $parts as $part ) {
4240 $part = trim( $part );
4241 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4243 if( isset( $paramMap[$magicName] ) ) {
4244 list( $type, $paramName ) = $paramMap[$magicName];
4246 // Special case; width and height come in one variable together
4247 if( $type === 'handler' && $paramName === 'width' ) {
4249 # (bug 13500) In both cases (width/height and width only),
4250 # permit trailing "px" for backward compatibility.
4251 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4252 $width = intval( $m[1] );
4253 $height = intval( $m[2] );
4254 if ( $handler->validateParam( 'width', $width ) ) {
4255 $params[$type]['width'] = $width;
4258 if ( $handler->validateParam( 'height', $height ) ) {
4259 $params[$type]['height'] = $height;
4262 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4263 $width = intval( $value );
4264 if ( $handler->validateParam( 'width', $width ) ) {
4265 $params[$type]['width'] = $width;
4268 } // else no validation -- bug 13436
4270 if ( $type === 'handler' ) {
4271 # Validate handler parameter
4272 $validated = $handler->validateParam( $paramName, $value );
4274 # Validate internal parameters
4275 switch( $paramName ) {
4277 /// @fixme - possibly check validity here?
4278 /// downstream behavior seems odd with missing manual thumbs.
4282 // Most other things appear to be empty or numeric...
4283 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4288 $params[$type][$paramName] = $value;
4292 if ( !$validated ) {
4297 # Process alignment parameters
4298 if ( $params['horizAlign'] ) {
4299 $params['frame']['align'] = key( $params['horizAlign'] );
4301 if ( $params['vertAlign'] ) {
4302 $params['frame']['valign'] = key( $params['vertAlign'] );
4305 # Strip bad stuff out of the alt text
4306 # We can't just use replaceLinkHoldersText() here, because if this function
4307 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4309 $alt = $holders->replaceText( $caption );
4311 $alt = $this->replaceLinkHoldersText( $caption );
4314 # make sure there are no placeholders in thumbnail attributes
4315 # that are later expanded to html- so expand them now and
4317 $alt = $this->mStripState
->unstripBoth( $alt );
4318 $alt = Sanitizer
::stripAllTags( $alt );
4320 $params['frame']['alt'] = $alt;
4321 $params['frame']['caption'] = $caption;
4323 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4325 # Linker does the rest
4326 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4328 # Give the handler a chance to modify the parser object
4330 $handler->parserTransformHook( $this, $file );
4337 * Set a flag in the output object indicating that the content is dynamic and
4338 * shouldn't be cached.
4340 function disableCache() {
4341 wfDebug( "Parser output marked as uncacheable.\n" );
4342 $this->mOutput
->mCacheTime
= -1;
4346 * Callback from the Sanitizer for expanding items found in HTML attribute
4347 * values, so they can be safely tested and escaped.
4348 * @param string $text
4349 * @param PPFrame $frame
4353 function attributeStripCallback( &$text, $frame = false ) {
4354 $text = $this->replaceVariables( $text, $frame );
4355 $text = $this->mStripState
->unstripBoth( $text );
4364 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4365 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4366 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4372 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4377 * Break wikitext input into sections, and either pull or replace
4378 * some particular section's text.
4380 * External callers should use the getSection and replaceSection methods.
4382 * @param string $text Page wikitext
4383 * @param string $section A section identifier string of the form:
4384 * <flag1> - <flag2> - ... - <section number>
4386 * Currently the only recognised flag is "T", which means the target section number
4387 * was derived during a template inclusion parse, in other words this is a template
4388 * section edit link. If no flags are given, it was an ordinary section edit link.
4389 * This flag is required to avoid a section numbering mismatch when a section is
4390 * enclosed by <includeonly> (bug 6563).
4392 * The section number 0 pulls the text before the first heading; other numbers will
4393 * pull the given section along with its lower-level subsections. If the section is
4394 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4396 * @param string $mode One of "get" or "replace"
4397 * @param string $newText Replacement text for section data.
4398 * @return string for "get", the extracted section text.
4399 * for "replace", the whole page with the section replaced.
4401 private function extractSections( $text, $section, $mode, $newText='' ) {
4403 $this->clearState();
4404 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4405 $this->mOptions
= new ParserOptions
;
4406 $this->setOutputType( self
::OT_WIKI
);
4408 $frame = $this->getPreprocessor()->newFrame();
4410 // Process section extraction flags
4412 $sectionParts = explode( '-', $section );
4413 $sectionIndex = array_pop( $sectionParts );
4414 foreach ( $sectionParts as $part ) {
4415 if ( $part === 'T' ) {
4416 $flags |
= self
::PTD_FOR_INCLUSION
;
4419 // Preprocess the text
4420 $root = $this->preprocessToDom( $text, $flags );
4422 // <h> nodes indicate section breaks
4423 // They can only occur at the top level, so we can find them by iterating the root's children
4424 $node = $root->getFirstChild();
4426 // Find the target section
4427 if ( $sectionIndex == 0 ) {
4428 // Section zero doesn't nest, level=big
4429 $targetLevel = 1000;
4432 if ( $node->getName() === 'h' ) {
4433 $bits = $node->splitHeading();
4434 if ( $bits['i'] == $sectionIndex ) {
4435 $targetLevel = $bits['level'];
4439 if ( $mode === 'replace' ) {
4440 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4442 $node = $node->getNextSibling();
4448 if ( $mode === 'get' ) {
4455 // Find the end of the section, including nested sections
4457 if ( $node->getName() === 'h' ) {
4458 $bits = $node->splitHeading();
4459 $curLevel = $bits['level'];
4460 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4464 if ( $mode === 'get' ) {
4465 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4467 $node = $node->getNextSibling();
4470 // Write out the remainder (in replace mode only)
4471 if ( $mode === 'replace' ) {
4472 // Output the replacement text
4473 // Add two newlines on -- trailing whitespace in $newText is conventionally
4474 // stripped by the editor, so we need both newlines to restore the paragraph gap
4475 $outText .= $newText . "\n\n";
4477 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4478 $node = $node->getNextSibling();
4482 if ( is_string( $outText ) ) {
4483 // Re-insert stripped tags
4484 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4491 * This function returns the text of a section, specified by a number ($section).
4492 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4493 * the first section before any such heading (section 0).
4495 * If a section contains subsections, these are also returned.
4497 * @param string $text text to look in
4498 * @param string $section section identifier
4499 * @param string $deftext default to return if section is not found
4500 * @return string text of the requested section
4502 public function getSection( $text, $section, $deftext='' ) {
4503 return $this->extractSections( $text, $section, "get", $deftext );
4506 public function replaceSection( $oldtext, $section, $text ) {
4507 return $this->extractSections( $oldtext, $section, "replace", $text );
4511 * Get the timestamp associated with the current revision, adjusted for
4512 * the default server-local timestamp
4514 function getRevisionTimestamp() {
4515 if ( is_null( $this->mRevisionTimestamp
) ) {
4516 wfProfileIn( __METHOD__
);
4518 $dbr = wfGetDB( DB_SLAVE
);
4519 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4520 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4522 // Normalize timestamp to internal MW format for timezone processing.
4523 // This has the added side-effect of replacing a null value with
4524 // the current time, which gives us more sensible behavior for
4526 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4528 // The cryptic '' timezone parameter tells to use the site-default
4529 // timezone offset instead of the user settings.
4531 // Since this value will be saved into the parser cache, served
4532 // to other users, and potentially even used inside links and such,
4533 // it needs to be consistent for all visitors.
4534 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4536 wfProfileOut( __METHOD__
);
4538 return $this->mRevisionTimestamp
;
4542 * Mutator for $mDefaultSort
4544 * @param $sort New value
4546 public function setDefaultSort( $sort ) {
4547 $this->mDefaultSort
= $sort;
4551 * Accessor for $mDefaultSort
4552 * Will use the title/prefixed title if none is set
4556 public function getDefaultSort() {
4557 global $wgCategoryPrefixedDefaultSortkey;
4558 if( $this->mDefaultSort
!== false ) {
4559 return $this->mDefaultSort
;
4560 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4561 !$wgCategoryPrefixedDefaultSortkey) {
4562 return $this->mTitle
->getText();
4564 return $this->mTitle
->getPrefixedText();
4569 * Try to guess the section anchor name based on a wikitext fragment
4570 * presumably extracted from a heading, for example "Header" from
4573 public function guessSectionNameFromWikiText( $text ) {
4574 # Strip out wikitext links(they break the anchor)
4575 $text = $this->stripSectionName( $text );
4576 $headline = Sanitizer
::decodeCharReferences( $text );
4578 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4579 $headline = trim( $headline );
4580 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4581 $replacearray = array(
4586 array_keys( $replacearray ),
4587 array_values( $replacearray ),
4592 * Strips a text string of wikitext for use in a section anchor
4594 * Accepts a text string and then removes all wikitext from the
4595 * string and leaves only the resultant text (i.e. the result of
4596 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4597 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4598 * to create valid section anchors by mimicing the output of the
4599 * parser when headings are parsed.
4601 * @param $text string Text string to be stripped of wikitext
4602 * for use in a Section anchor
4603 * @return Filtered text string
4605 public function stripSectionName( $text ) {
4606 # Strip internal link markup
4607 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4608 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4610 # Strip external link markup (FIXME: Not Tolerant to blank link text
4611 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4612 # on how many empty links there are on the page - need to figure that out.
4613 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4615 # Parse wikitext quotes (italics & bold)
4616 $text = $this->doQuotes($text);
4619 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4623 function srvus( $text ) {
4624 return $this->testSrvus( $text, $this->mOutputType
);
4628 * strip/replaceVariables/unstrip for preprocessor regression testing
4630 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4631 $this->clearState();
4632 if ( ! ( $title instanceof Title
) ) {
4633 $title = Title
::newFromText( $title );
4635 $this->mTitle
= $title;
4636 $this->mOptions
= $options;
4637 $this->setOutputType( $outputType );
4638 $text = $this->replaceVariables( $text );
4639 $text = $this->mStripState
->unstripBoth( $text );
4640 $text = Sanitizer
::removeHTMLtags( $text );
4644 function testPst( $text, $title, $options ) {
4646 if ( ! ( $title instanceof Title
) ) {
4647 $title = Title
::newFromText( $title );
4649 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4652 function testPreprocess( $text, $title, $options ) {
4653 if ( ! ( $title instanceof Title
) ) {
4654 $title = Title
::newFromText( $title );
4656 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4659 function markerSkipCallback( $s, $callback ) {
4662 while ( $i < strlen( $s ) ) {
4663 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4664 if ( $markerStart === false ) {
4665 $out .= call_user_func( $callback, substr( $s, $i ) );
4668 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4669 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4670 if ( $markerEnd === false ) {
4671 $out .= substr( $s, $markerStart );
4674 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4675 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4685 * @todo document, briefly.
4689 var $general, $nowiki;
4691 function __construct() {
4692 $this->general
= new ReplacementArray
;
4693 $this->nowiki
= new ReplacementArray
;
4696 function unstripGeneral( $text ) {
4697 wfProfileIn( __METHOD__
);
4700 $text = $this->general
->replace( $text );
4701 } while ( $text !== $oldText );
4702 wfProfileOut( __METHOD__
);
4706 function unstripNoWiki( $text ) {
4707 wfProfileIn( __METHOD__
);
4710 $text = $this->nowiki
->replace( $text );
4711 } while ( $text !== $oldText );
4712 wfProfileOut( __METHOD__
);
4716 function unstripBoth( $text ) {
4717 wfProfileIn( __METHOD__
);
4720 $text = $this->general
->replace( $text );
4721 $text = $this->nowiki
->replace( $text );
4722 } while ( $text !== $oldText );
4723 wfProfileOut( __METHOD__
);
4729 * @todo document, briefly.
4732 class OnlyIncludeReplacer
{
4735 function replace( $matches ) {
4736 if ( substr( $matches[1], -1 ) === "\n" ) {
4737 $this->output
.= substr( $matches[1], 0, -1 );
4739 $this->output
.= $matches[1];