3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
124 function __construct( $conf = array() ) {
125 $this->mConf
= $conf;
126 $this->mTagHooks
= array();
127 $this->mTransparentTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
131 $this->mUrlProtocols
= wfUrlProtocols();
132 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
133 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
134 $this->mVarCache
= array();
135 if ( isset( $conf['preprocessorClass'] ) ) {
136 $this->mPreprocessorClass
= $conf['preprocessorClass'];
137 } elseif ( extension_loaded( 'domxml' ) ) {
138 // PECL extension that conflicts with the core DOM extension (bug 13770)
139 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
140 $this->mPreprocessorClass
= 'Preprocessor_Hash';
141 } elseif ( extension_loaded( 'dom' ) ) {
142 $this->mPreprocessorClass
= 'Preprocessor_DOM';
144 $this->mPreprocessorClass
= 'Preprocessor_Hash';
146 $this->mMarkerIndex
= 0;
147 $this->mFirstCall
= true;
151 * Reduce memory usage to reduce the impact of circular references
153 function __destruct() {
154 if ( isset( $this->mLinkHolders
) ) {
155 $this->mLinkHolders
->__destruct();
157 foreach ( $this as $name => $value ) {
158 unset( $this->$name );
163 * Do various kinds of initialisation on the first call of the parser
165 function firstCallInit() {
166 if ( !$this->mFirstCall
) {
169 $this->mFirstCall
= false;
171 wfProfileIn( __METHOD__
);
173 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
174 CoreParserFunctions
::register( $this );
175 $this->initialiseVariables();
177 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
178 wfProfileOut( __METHOD__
);
186 function clearState() {
187 wfProfileIn( __METHOD__
);
188 if ( $this->mFirstCall
) {
189 $this->firstCallInit();
191 $this->mOutput
= new ParserOutput
;
192 $this->mAutonumber
= 0;
193 $this->mLastSection
= '';
194 $this->mDTopen
= false;
195 $this->mIncludeCount
= array();
196 $this->mStripState
= new StripState
;
197 $this->mArgStack
= false;
198 $this->mInPre
= false;
199 $this->mLinkHolders
= new LinkHolderArray( $this );
201 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
204 * Prefix for temporary replacement strings for the multipass parser.
205 * \x07 should never appear in input as it's disallowed in XML.
206 * Using it at the front also gives us a little extra robustness
207 * since it shouldn't match when butted up against identifier-like
210 * Must not consist of all title characters, or else it will change
211 * the behaviour of <nowiki> in a link.
213 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
214 # Changed to \x7f to allow XML double-parsing -- TS
215 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
221 $this->mShowToc
= true;
222 $this->mForceTocPosition
= false;
223 $this->mIncludeSizes
= array(
227 $this->mPPNodeCount
= 0;
228 $this->mDefaultSort
= false;
229 $this->mHeadings
= array();
230 $this->mDoubleUnderscores
= array();
231 $this->mExpensiveFunctionCount
= 0;
234 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
235 $this->mPreprocessor
= null;
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
242 function setOutputType( $ot ) {
243 $this->mOutputType
= $ot;
246 'html' => $ot == self
::OT_HTML
,
247 'wiki' => $ot == self
::OT_WIKI
,
248 'pre' => $ot == self
::OT_PREPROCESS
,
253 * Set the context title
255 function setTitle( $t ) {
256 if ( !$t ||
$t instanceof FakeTitle
) {
257 $t = Title
::newFromText( 'NO TITLE' );
259 if ( strval( $t->getFragment() ) !== '' ) {
260 # Strip the fragment to avoid various odd effects
261 $this->mTitle
= clone $t;
262 $this->mTitle
->setFragment( '' );
269 * Accessor for mUniqPrefix.
273 function uniqPrefix() {
274 if( !isset( $this->mUniqPrefix
) ) {
275 // @fixme this is probably *horribly wrong*
276 // LanguageConverter seems to want $wgParser's uniqPrefix, however
277 // if this is called for a parser cache hit, the parser may not
278 // have ever been initialized in the first place.
279 // Not really sure what the heck is supposed to be going on here.
281 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
283 return $this->mUniqPrefix
;
287 * Convert wikitext to HTML
288 * Do not call this function recursively.
290 * @param $text String: text we want to parse
291 * @param $title A title object
292 * @param $options ParserOptions
293 * @param $linestart boolean
294 * @param $clearState boolean
295 * @param $revid Int: number to pass in {{REVISIONID}}
296 * @return ParserOutput a ParserOutput
298 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
300 * First pass--just handle <nowiki> sections, pass the rest off
301 * to internalParse() which does all the real work.
304 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
305 $fname = __METHOD__
.'-' . wfGetCaller();
306 wfProfileIn( __METHOD__
);
307 wfProfileIn( $fname );
313 $this->mOptions
= $options;
314 $this->setTitle( $title );
315 $oldRevisionId = $this->mRevisionId
;
316 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
317 if( $revid !== null ) {
318 $this->mRevisionId
= $revid;
319 $this->mRevisionTimestamp
= null;
321 $this->setOutputType( self
::OT_HTML
);
322 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
324 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
325 $text = $this->internalParse( $text );
326 $text = $this->mStripState
->unstripGeneral( $text );
328 # Clean up special characters, only run once, next-to-last before doBlockLevels
330 # french spaces, last one Guillemet-left
331 # only if there is something before the space
332 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
333 # french spaces, Guillemet-right
334 '/(\\302\\253) /' => '\\1 ',
335 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
337 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
339 $text = $this->doBlockLevels( $text, $linestart );
341 $this->replaceLinkHolders( $text );
343 # the position of the parserConvert() call should not be changed. it
344 # assumes that the links are all replaced and the only thing left
345 # is the <nowiki> mark.
346 # Side-effects: this calls $this->mOutput->setTitleText()
347 $text = $wgContLang->parserConvert( $text, $this );
349 $text = $this->mStripState
->unstripNoWiki( $text );
351 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
353 //!JF Move to its own function
355 $uniq_prefix = $this->mUniqPrefix
;
357 $elements = array_keys( $this->mTransparentTagHooks
);
358 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
360 foreach( $matches as $marker => $data ) {
361 list( $element, $content, $params, $tag ) = $data;
362 $tagName = strtolower( $element );
363 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
364 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
365 array( $content, $params, $this ) );
369 $this->mStripState
->general
->setPair( $marker, $output );
371 $text = $this->mStripState
->unstripGeneral( $text );
373 $text = Sanitizer
::normalizeCharReferences( $text );
375 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
376 $text = self
::tidy($text);
378 # attempt to sanitize at least some nesting problems
379 # (bug #2702 and quite a few others)
381 # ''Something [http://www.cool.com cool''] -->
382 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
383 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
384 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
385 # fix up an anchor inside another anchor, only
386 # at least for a single single nested link (bug 3695)
387 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
388 '\\1\\2</a>\\3</a>\\1\\4</a>',
389 # fix div inside inline elements- doBlockLevels won't wrap a line which
390 # contains a div, so fix it up here; replace
391 # div with escaped text
392 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
393 '\\1\\3<div\\5>\\6</div>\\8\\9',
394 # remove empty italic or bold tag pairs, some
395 # introduced by rules above
396 '/<([bi])><\/\\1>/' => '',
399 $text = preg_replace(
400 array_keys( $tidyregs ),
401 array_values( $tidyregs ),
404 global $wgExpensiveParserFunctionLimit;
405 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
406 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
409 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
411 # Information on include size limits, for the benefit of users who try to skirt them
412 if ( $this->mOptions
->getEnableLimitReport() ) {
413 global $wgExpensiveParserFunctionLimit;
414 $max = $this->mOptions
->getMaxIncludeSize();
415 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
417 "NewPP limit report\n" .
418 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
419 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
420 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
422 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
423 $text .= "\n<!-- \n$limitReport-->\n";
425 $this->mOutput
->setText( $text );
426 $this->mRevisionId
= $oldRevisionId;
427 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
428 wfProfileOut( $fname );
429 wfProfileOut( __METHOD__
);
431 return $this->mOutput
;
435 * Recursive parser entry point that can be called from an extension tag
438 function recursiveTagParse( $text ) {
439 wfProfileIn( __METHOD__
);
440 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
441 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
442 $text = $this->internalParse( $text );
443 wfProfileOut( __METHOD__
);
448 * Expand templates and variables in the text, producing valid, static wikitext.
449 * Also removes comments.
451 function preprocess( $text, $title, $options, $revid = null ) {
452 wfProfileIn( __METHOD__
);
454 $this->setOutputType( self
::OT_PREPROCESS
);
455 $this->mOptions
= $options;
456 $this->setTitle( $title );
457 if( $revid !== null ) {
458 $this->mRevisionId
= $revid;
460 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
461 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
462 $text = $this->replaceVariables( $text );
463 $text = $this->mStripState
->unstripBoth( $text );
464 wfProfileOut( __METHOD__
);
469 * Get a random string
474 function getRandomString() {
475 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
478 function &getTitle() { return $this->mTitle
; }
479 function getOptions() { return $this->mOptions
; }
480 function getRevisionId() { return $this->mRevisionId
; }
481 function getOutput() { return $this->mOutput
; }
482 function nextLinkID() { return $this->mLinkID++
; }
484 function getFunctionLang() {
485 global $wgLang, $wgContLang;
487 $target = $this->mOptions
->getTargetLanguage();
488 if ( $target !== null ) {
491 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
496 * Get a preprocessor object
498 function getPreprocessor() {
499 if ( !isset( $this->mPreprocessor
) ) {
500 $class = $this->mPreprocessorClass
;
501 $this->mPreprocessor
= new $class( $this );
503 return $this->mPreprocessor
;
507 * Replaces all occurrences of HTML-style comments and the given tags
508 * in the text with a random marker and returns the next text. The output
509 * parameter $matches will be an associative array filled with data in
511 * 'UNIQ-xxxxx' => array(
514 * array( 'param' => 'x' ),
515 * '<element param="x">tag content</element>' ) )
517 * @param $elements list of element names. Comments are always extracted.
518 * @param $text Source text string.
519 * @param $uniq_prefix
524 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
529 $taglist = implode( '|', $elements );
530 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
532 while ( '' != $text ) {
533 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
535 if( count( $p ) < 5 ) {
538 if( count( $p ) > 5 ) {
552 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
553 $stripped .= $marker;
555 if ( $close === '/>' ) {
556 // Empty element tag, <tag />
561 if( $element === '!--' ) {
564 $end = "/(<\\/$element\\s*>)/i";
566 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
568 if( count( $q ) < 3 ) {
569 # No end tag -- let it run out to the end of the text.
578 $matches[$marker] = array( $element,
580 Sanitizer
::decodeTagAttributes( $attributes ),
581 "<$element$attributes$close$content$tail" );
587 * Get a list of strippable XML-like elements
589 function getStripList() {
591 $elements = $this->mStripList
;
593 $elements[] = 'html';
595 if( $this->mOptions
->getUseTeX() ) {
596 $elements[] = 'math';
602 * @deprecated use replaceVariables
604 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
609 * Restores pre, math, and other extensions removed by strip()
611 * always call unstripNoWiki() after this one
613 * @deprecated use $this->mStripState->unstrip()
615 function unstrip( $text, $state ) {
616 return $state->unstripGeneral( $text );
620 * Always call this after unstrip() to preserve the order
623 * @deprecated use $this->mStripState->unstrip()
625 function unstripNoWiki( $text, $state ) {
626 return $state->unstripNoWiki( $text );
630 * @deprecated use $this->mStripState->unstripBoth()
632 function unstripForHTML( $text ) {
633 return $this->mStripState
->unstripBoth( $text );
637 * Add an item to the strip state
638 * Returns the unique tag which must be inserted into the stripped text
639 * The tag will be replaced with the original text in unstrip()
643 function insertStripItem( $text ) {
644 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
645 $this->mMarkerIndex++
;
646 $this->mStripState
->general
->setPair( $rnd, $text );
651 * Interface with html tidy, used if $wgUseTidy = true.
652 * If tidy isn't able to correct the markup, the original will be
653 * returned in all its glory with a warning comment appended.
655 * Either the external tidy program or the in-process tidy extension
656 * will be used depending on availability. Override the default
657 * $wgTidyInternal setting to disable the internal if it's not working.
659 * @param string $text Hideous HTML input
660 * @return string Corrected HTML output
664 function tidy( $text ) {
665 global $wgTidyInternal;
666 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
667 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
668 '<head><title>test</title></head><body>'.$text.'</body></html>';
669 if( $wgTidyInternal ) {
670 $correctedtext = self
::internalTidy( $wrappedtext );
672 $correctedtext = self
::externalTidy( $wrappedtext );
674 if( is_null( $correctedtext ) ) {
675 wfDebug( "Tidy error detected!\n" );
676 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
678 return $correctedtext;
682 * Spawn an external HTML tidy process and get corrected markup back from it.
687 function externalTidy( $text ) {
688 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
689 wfProfileIn( __METHOD__
);
694 $descriptorspec = array(
695 0 => array('pipe', 'r'),
696 1 => array('pipe', 'w'),
697 2 => array('file', wfGetNull(), 'a')
700 if( function_exists('proc_open') ) {
701 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
702 if (is_resource($process)) {
703 // Theoretically, this style of communication could cause a deadlock
704 // here. If the stdout buffer fills up, then writes to stdin could
705 // block. This doesn't appear to happen with tidy, because tidy only
706 // writes to stdout after it's finished reading from stdin. Search
707 // for tidyParseStdin and tidySaveStdout in console/tidy.c
708 fwrite($pipes[0], $text);
710 while (!feof($pipes[1])) {
711 $cleansource .= fgets($pipes[1], 1024);
714 proc_close($process);
718 wfProfileOut( __METHOD__
);
720 if( $cleansource == '' && $text != '') {
721 // Some kind of error happened, so we couldn't get the corrected text.
722 // Just give up; we'll use the source text and append a warning.
730 * Use the HTML tidy PECL extension to use the tidy library in-process,
731 * saving the overhead of spawning a new process.
733 * 'pear install tidy' should be able to compile the extension module.
738 function internalTidy( $text ) {
739 global $wgTidyConf, $IP, $wgDebugTidy;
740 wfProfileIn( __METHOD__
);
743 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
744 $tidy->cleanRepair();
745 if( $tidy->getStatus() == 2 ) {
746 // 2 is magic number for fatal error
747 // http://www.php.net/manual/en/function.tidy-get-status.php
750 $cleansource = tidy_get_output( $tidy );
752 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
753 $cleansource .= "<!--\nTidy reports:\n" .
754 str_replace( '-->', '-->', $tidy->errorBuffer
) .
758 wfProfileOut( __METHOD__
);
763 * parse the wiki syntax used to render tables
767 function doTableStuff ( $text ) {
768 wfProfileIn( __METHOD__
);
770 $lines = StringUtils
::explode( "\n", $text );
772 $td_history = array (); // Is currently a td tag open?
773 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
774 $tr_history = array (); // Is currently a tr tag open?
775 $tr_attributes = array (); // history of tr attributes
776 $has_opened_tr = array(); // Did this table open a <tr> element?
777 $indent_level = 0; // indent level of the table
779 foreach ( $lines as $outLine ) {
780 $line = trim( $outLine );
782 if( $line == '' ) { // empty line, go to next line
783 $out .= $outLine."\n";
786 $first_character = $line[0];
789 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
790 // First check if we are starting a new table
791 $indent_level = strlen( $matches[1] );
793 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
794 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
796 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
797 array_push ( $td_history , false );
798 array_push ( $last_tag_history , '' );
799 array_push ( $tr_history , false );
800 array_push ( $tr_attributes , '' );
801 array_push ( $has_opened_tr , false );
802 } else if ( count ( $td_history ) == 0 ) {
803 // Don't do any of the following
804 $out .= $outLine."\n";
806 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
807 // We are ending a table
808 $line = '</table>' . substr ( $line , 2 );
809 $last_tag = array_pop ( $last_tag_history );
811 if ( !array_pop ( $has_opened_tr ) ) {
812 $line = "<tr><td></td></tr>{$line}";
815 if ( array_pop ( $tr_history ) ) {
816 $line = "</tr>{$line}";
819 if ( array_pop ( $td_history ) ) {
820 $line = "</{$last_tag}>{$line}";
822 array_pop ( $tr_attributes );
823 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
824 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
825 // Now we have a table row
826 $line = preg_replace( '#^\|-+#', '', $line );
828 // Whats after the tag is now only attributes
829 $attributes = $this->mStripState
->unstripBoth( $line );
830 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
831 array_pop ( $tr_attributes );
832 array_push ( $tr_attributes , $attributes );
835 $last_tag = array_pop ( $last_tag_history );
836 array_pop ( $has_opened_tr );
837 array_push ( $has_opened_tr , true );
839 if ( array_pop ( $tr_history ) ) {
843 if ( array_pop ( $td_history ) ) {
844 $line = "</{$last_tag}>{$line}";
848 array_push ( $tr_history , false );
849 array_push ( $td_history , false );
850 array_push ( $last_tag_history , '' );
852 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
853 // This might be cell elements, td, th or captions
854 if ( substr ( $line , 0 , 2 ) === '|+' ) {
855 $first_character = '+';
856 $line = substr ( $line , 1 );
859 $line = substr ( $line , 1 );
861 if ( $first_character === '!' ) {
862 $line = str_replace ( '!!' , '||' , $line );
865 // Split up multiple cells on the same line.
866 // FIXME : This can result in improper nesting of tags processed
867 // by earlier parser steps, but should avoid splitting up eg
868 // attribute values containing literal "||".
869 $cells = StringUtils
::explodeMarkup( '||' , $line );
873 // Loop through each table cell
874 foreach ( $cells as $cell )
877 if ( $first_character !== '+' )
879 $tr_after = array_pop ( $tr_attributes );
880 if ( !array_pop ( $tr_history ) ) {
881 $previous = "<tr{$tr_after}>\n";
883 array_push ( $tr_history , true );
884 array_push ( $tr_attributes , '' );
885 array_pop ( $has_opened_tr );
886 array_push ( $has_opened_tr , true );
889 $last_tag = array_pop ( $last_tag_history );
891 if ( array_pop ( $td_history ) ) {
892 $previous = "</{$last_tag}>{$previous}";
895 if ( $first_character === '|' ) {
897 } else if ( $first_character === '!' ) {
899 } else if ( $first_character === '+' ) {
900 $last_tag = 'caption';
905 array_push ( $last_tag_history , $last_tag );
907 // A cell could contain both parameters and data
908 $cell_data = explode ( '|' , $cell , 2 );
910 // Bug 553: Note that a '|' inside an invalid link should not
911 // be mistaken as delimiting cell parameters
912 if ( strpos( $cell_data[0], '[[' ) !== false ) {
913 $cell = "{$previous}<{$last_tag}>{$cell}";
914 } else if ( count ( $cell_data ) == 1 )
915 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
917 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
918 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
919 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
923 array_push ( $td_history , true );
926 $out .= $outLine . "\n";
929 // Closing open td, tr && table
930 while ( count ( $td_history ) > 0 )
932 if ( array_pop ( $td_history ) ) {
935 if ( array_pop ( $tr_history ) ) {
938 if ( !array_pop ( $has_opened_tr ) ) {
939 $out .= "<tr><td></td></tr>\n" ;
942 $out .= "</table>\n";
945 // Remove trailing line-ending (b/c)
946 if ( substr( $out, -1 ) === "\n" ) {
947 $out = substr( $out, 0, -1 );
950 // special case: don't return empty table
951 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
955 wfProfileOut( __METHOD__
);
961 * Helper function for parse() that transforms wiki markup into
962 * HTML. Only called for $mOutputType == self::OT_HTML.
966 function internalParse( $text ) {
968 wfProfileIn( __METHOD__
);
970 # Hook to suspend the parser in this state
971 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
972 wfProfileOut( __METHOD__
);
976 $text = $this->replaceVariables( $text );
977 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
978 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
980 // Tables need to come after variable replacement for things to work
981 // properly; putting them before other transformations should keep
982 // exciting things like link expansions from showing up in surprising
984 $text = $this->doTableStuff( $text );
986 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
988 $text = $this->doDoubleUnderscore( $text );
989 $text = $this->doHeadings( $text );
990 if($this->mOptions
->getUseDynamicDates()) {
991 $df = DateFormatter
::getInstance();
992 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
994 $text = $this->doAllQuotes( $text );
995 $text = $this->replaceInternalLinks( $text );
996 $text = $this->replaceExternalLinks( $text );
998 # replaceInternalLinks may sometimes leave behind
999 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1000 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1002 $text = $this->doMagicLinks( $text );
1003 $text = $this->formatHeadings( $text, $isMain );
1005 wfProfileOut( __METHOD__
);
1010 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1011 * magic external links.
1016 function doMagicLinks( $text ) {
1017 wfProfileIn( __METHOD__
);
1018 $prots = $this->mUrlProtocols
;
1019 $urlChar = self
::EXT_LINK_URL_CLASS
;
1020 $text = preg_replace_callback(
1022 (<a.*?</a>) | # m[1]: Skip link text
1023 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1024 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1025 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1026 ISBN\s+(\b # m[5]: ISBN, capture number
1027 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1028 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1029 [0-9Xx] # check digit
1031 )!x', array( &$this, 'magicLinkCallback' ), $text );
1032 wfProfileOut( __METHOD__
);
1036 function magicLinkCallback( $m ) {
1037 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1040 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1043 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1044 # Free external link
1045 return $this->makeFreeExternalLink( $m[0] );
1046 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1048 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1052 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1054 $urlmsg = 'pubmedurl';
1057 throw new MWException( __METHOD__
.': unrecognised match type "' .
1058 substr($m[0], 0, 20 ) . '"' );
1060 $url = wfMsg( $urlmsg, $id);
1061 $sk = $this->mOptions
->getSkin();
1062 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1063 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1064 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1067 $num = strtr( $isbn, array(
1072 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1074 $titleObj->escapeLocalUrl() .
1075 "\" class=\"internal\">ISBN $isbn</a>";
1082 * Make a free external link, given a user-supplied URL
1086 function makeFreeExternalLink( $url ) {
1088 wfProfileIn( __METHOD__
);
1090 $sk = $this->mOptions
->getSkin();
1093 # The characters '<' and '>' (which were escaped by
1094 # removeHTMLtags()) should not be included in
1095 # URLs, per RFC 2396.
1097 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1098 $trail = substr($url, $m2[0][1]) . $trail;
1099 $url = substr($url, 0, $m2[0][1]);
1102 # Move trailing punctuation to $trail
1104 # If there is no left bracket, then consider right brackets fair game too
1105 if ( strpos( $url, '(' ) === false ) {
1109 $numSepChars = strspn( strrev( $url ), $sep );
1110 if ( $numSepChars ) {
1111 $trail = substr( $url, -$numSepChars ) . $trail;
1112 $url = substr( $url, 0, -$numSepChars );
1115 $url = Sanitizer
::cleanUrl( $url );
1117 # Is this an external image?
1118 $text = $this->maybeMakeExternalImage( $url );
1119 if ( $text === false ) {
1120 # Not an image, make a link
1121 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1122 # Register it in the output object...
1123 # Replace unnecessary URL escape codes with their equivalent characters
1124 $pasteurized = self
::replaceUnusualEscapes( $url );
1125 $this->mOutput
->addExternalLink( $pasteurized );
1127 wfProfileOut( __METHOD__
);
1128 return $text . $trail;
1133 * Parse headers and return html
1137 function doHeadings( $text ) {
1138 wfProfileIn( __METHOD__
);
1139 for ( $i = 6; $i >= 1; --$i ) {
1140 $h = str_repeat( '=', $i );
1141 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1142 "<h$i>\\1</h$i>", $text );
1144 wfProfileOut( __METHOD__
);
1149 * Replace single quotes with HTML markup
1151 * @return string the altered text
1153 function doAllQuotes( $text ) {
1154 wfProfileIn( __METHOD__
);
1156 $lines = StringUtils
::explode( "\n", $text );
1157 foreach ( $lines as $line ) {
1158 $outtext .= $this->doQuotes( $line ) . "\n";
1160 $outtext = substr($outtext, 0,-1);
1161 wfProfileOut( __METHOD__
);
1166 * Helper function for doAllQuotes()
1168 public function doQuotes( $text ) {
1169 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1170 if ( count( $arr ) == 1 )
1174 # First, do some preliminary work. This may shift some apostrophes from
1175 # being mark-up to being text. It also counts the number of occurrences
1176 # of bold and italics mark-ups.
1180 foreach ( $arr as $r )
1182 if ( ( $i %
2 ) == 1 )
1184 # If there are ever four apostrophes, assume the first is supposed to
1185 # be text, and the remaining three constitute mark-up for bold text.
1186 if ( strlen( $arr[$i] ) == 4 )
1191 # If there are more than 5 apostrophes in a row, assume they're all
1192 # text except for the last 5.
1193 else if ( strlen( $arr[$i] ) > 5 )
1195 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1198 # Count the number of occurrences of bold and italics mark-ups.
1199 # We are not counting sequences of five apostrophes.
1200 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1201 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1202 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1207 # If there is an odd number of both bold and italics, it is likely
1208 # that one of the bold ones was meant to be an apostrophe followed
1209 # by italics. Which one we cannot know for certain, but it is more
1210 # likely to be one that has a single-letter word before it.
1211 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1214 $firstsingleletterword = -1;
1215 $firstmultiletterword = -1;
1217 foreach ( $arr as $r )
1219 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1221 $x1 = substr ($arr[$i-1], -1);
1222 $x2 = substr ($arr[$i-1], -2, 1);
1224 if ($firstspace == -1) $firstspace = $i;
1225 } else if ($x2 === ' ') {
1226 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1228 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1234 # If there is a single-letter word, use it!
1235 if ($firstsingleletterword > -1)
1237 $arr [ $firstsingleletterword ] = "''";
1238 $arr [ $firstsingleletterword-1 ] .= "'";
1240 # If not, but there's a multi-letter word, use that one.
1241 else if ($firstmultiletterword > -1)
1243 $arr [ $firstmultiletterword ] = "''";
1244 $arr [ $firstmultiletterword-1 ] .= "'";
1246 # ... otherwise use the first one that has neither.
1247 # (notice that it is possible for all three to be -1 if, for example,
1248 # there is only one pentuple-apostrophe in the line)
1249 else if ($firstspace > -1)
1251 $arr [ $firstspace ] = "''";
1252 $arr [ $firstspace-1 ] .= "'";
1256 # Now let's actually convert our apostrophic mush to HTML!
1261 foreach ($arr as $r)
1265 if ($state === 'both')
1272 if (strlen ($r) == 2)
1275 { $output .= '</i>'; $state = ''; }
1276 else if ($state === 'bi')
1277 { $output .= '</i>'; $state = 'b'; }
1278 else if ($state === 'ib')
1279 { $output .= '</b></i><b>'; $state = 'b'; }
1280 else if ($state === 'both')
1281 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1282 else # $state can be 'b' or ''
1283 { $output .= '<i>'; $state .= 'i'; }
1285 else if (strlen ($r) == 3)
1288 { $output .= '</b>'; $state = ''; }
1289 else if ($state === 'bi')
1290 { $output .= '</i></b><i>'; $state = 'i'; }
1291 else if ($state === 'ib')
1292 { $output .= '</b>'; $state = 'i'; }
1293 else if ($state === 'both')
1294 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1295 else # $state can be 'i' or ''
1296 { $output .= '<b>'; $state .= 'b'; }
1298 else if (strlen ($r) == 5)
1301 { $output .= '</b><i>'; $state = 'i'; }
1302 else if ($state === 'i')
1303 { $output .= '</i><b>'; $state = 'b'; }
1304 else if ($state === 'bi')
1305 { $output .= '</i></b>'; $state = ''; }
1306 else if ($state === 'ib')
1307 { $output .= '</b></i>'; $state = ''; }
1308 else if ($state === 'both')
1309 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1310 else # ($state == '')
1311 { $buffer = ''; $state = 'both'; }
1316 # Now close all remaining tags. Notice that the order is important.
1317 if ($state === 'b' ||
$state === 'ib')
1319 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1321 if ($state === 'bi')
1323 # There might be lonely ''''', so make sure we have a buffer
1324 if ($state === 'both' && $buffer)
1325 $output .= '<b><i>'.$buffer.'</i></b>';
1331 * Replace external links (REL)
1333 * Note: this is all very hackish and the order of execution matters a lot.
1334 * Make sure to run maintenance/parserTests.php if you change this code.
1338 function replaceExternalLinks( $text ) {
1340 wfProfileIn( __METHOD__
);
1342 $sk = $this->mOptions
->getSkin();
1344 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1345 $s = array_shift( $bits );
1348 while ( $i<count( $bits ) ) {
1350 $protocol = $bits[$i++
];
1351 $text = $bits[$i++
];
1352 $trail = $bits[$i++
];
1354 # The characters '<' and '>' (which were escaped by
1355 # removeHTMLtags()) should not be included in
1356 # URLs, per RFC 2396.
1358 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1359 $text = substr($url, $m2[0][1]) . ' ' . $text;
1360 $url = substr($url, 0, $m2[0][1]);
1363 # If the link text is an image URL, replace it with an <img> tag
1364 # This happened by accident in the original parser, but some people used it extensively
1365 $img = $this->maybeMakeExternalImage( $text );
1366 if ( $img !== false ) {
1372 # Set linktype for CSS - if URL==text, link is essentially free
1373 $linktype = ($text === $url) ?
'free' : 'text';
1375 # No link text, e.g. [http://domain.tld/some.link]
1376 if ( $text == '' ) {
1377 # Autonumber if allowed. See bug #5918
1378 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1379 $langObj = $this->getFunctionLang();
1380 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1381 $linktype = 'autonumber';
1383 # Otherwise just use the URL
1384 $text = htmlspecialchars( $url );
1388 # Have link text, e.g. [http://domain.tld/some.link text]s
1390 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1393 $text = $wgContLang->markNoConversion($text);
1395 $url = Sanitizer
::cleanUrl( $url );
1397 # Use the encoded URL
1398 # This means that users can paste URLs directly into the text
1399 # Funny characters like ö aren't valid in URLs anyway
1400 # This was changed in August 2004
1401 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1403 # Register link in the output object.
1404 # Replace unnecessary URL escape codes with the referenced character
1405 # This prevents spammers from hiding links from the filters
1406 $pasteurized = self
::replaceUnusualEscapes( $url );
1407 $this->mOutput
->addExternalLink( $pasteurized );
1410 wfProfileOut( __METHOD__
);
1415 * Replace unusual URL escape codes with their equivalent characters
1419 * @todo This can merge genuinely required bits in the path or query string,
1420 * breaking legit URLs. A proper fix would treat the various parts of
1421 * the URL differently; as a workaround, just use the output for
1422 * statistical records, not for actual linking/output.
1424 static function replaceUnusualEscapes( $url ) {
1425 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1426 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1430 * Callback function used in replaceUnusualEscapes().
1431 * Replaces unusual URL escape codes with their equivalent character
1435 private static function replaceUnusualEscapesCallback( $matches ) {
1436 $char = urldecode( $matches[0] );
1437 $ord = ord( $char );
1438 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1439 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1440 // No, shouldn't be escaped
1443 // Yes, leave it escaped
1449 * make an image if it's allowed, either through the global
1450 * option, through the exception, or through the on-wiki whitelist
1453 function maybeMakeExternalImage( $url ) {
1454 $sk = $this->mOptions
->getSkin();
1455 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1456 $imagesexception = !empty($imagesfrom);
1458 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1459 if( $imagesexception && is_array( $imagesfrom ) ) {
1460 $imagematch = false;
1461 foreach( $imagesfrom as $match ) {
1462 if( strpos( $url, $match ) === 0 ) {
1467 } elseif( $imagesexception ) {
1468 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1470 $imagematch = false;
1472 if ( $this->mOptions
->getAllowExternalImages()
1473 ||
( $imagesexception && $imagematch ) ) {
1474 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1476 $text = $sk->makeExternalImage( $url );
1479 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1480 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1481 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1482 foreach( $whitelist as $entry ) {
1483 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1484 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1486 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1487 # Image matches a whitelist entry
1488 $text = $sk->makeExternalImage( $url );
1497 * Process [[ ]] wikilinks
1498 * @return processed text
1502 function replaceInternalLinks( $s ) {
1503 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1508 * Process [[ ]] wikilinks (RIL)
1509 * @return LinkHolderArray
1513 function replaceInternalLinks2( &$s ) {
1516 wfProfileIn( __METHOD__
);
1518 wfProfileIn( __METHOD__
.'-setup' );
1519 static $tc = FALSE, $e1, $e1_img;
1520 # the % is needed to support urlencoded titles as well
1522 $tc = Title
::legalChars() . '#%';
1523 # Match a link having the form [[namespace:link|alternate]]trail
1524 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1525 # Match cases where there is no "]]", which might still be images
1526 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1529 $sk = $this->mOptions
->getSkin();
1530 $holders = new LinkHolderArray( $this );
1532 #split the entire text string on occurences of [[
1533 $a = StringUtils
::explode( '[[', ' ' . $s );
1534 #get the first element (all text up to first [[), and remove the space we added
1537 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1538 $s = substr( $s, 1 );
1540 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1542 if ( $useLinkPrefixExtension ) {
1543 # Match the end of a line for a word that's not followed by whitespace,
1544 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1545 $e2 = wfMsgForContent( 'linkprefix' );
1548 if( is_null( $this->mTitle
) ) {
1549 wfProfileOut( __METHOD__
.'-setup' );
1550 wfProfileOut( __METHOD__
);
1551 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1553 $nottalk = !$this->mTitle
->isTalkPage();
1555 if ( $useLinkPrefixExtension ) {
1557 if ( preg_match( $e2, $s, $m ) ) {
1558 $first_prefix = $m[2];
1560 $first_prefix = false;
1566 if($wgContLang->hasVariants()) {
1567 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1569 $selflink = array($this->mTitle
->getPrefixedText());
1571 $useSubpages = $this->areSubpagesAllowed();
1572 wfProfileOut( __METHOD__
.'-setup' );
1574 # Loop for each link
1575 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1576 # Check for excessive memory usage
1577 if ( $holders->isBig() ) {
1579 # Do the existence check, replace the link holders and clear the array
1580 $holders->replace( $s );
1584 if ( $useLinkPrefixExtension ) {
1585 wfProfileIn( __METHOD__
.'-prefixhandling' );
1586 if ( preg_match( $e2, $s, $m ) ) {
1594 $prefix = $first_prefix;
1595 $first_prefix = false;
1597 wfProfileOut( __METHOD__
.'-prefixhandling' );
1600 $might_be_img = false;
1602 wfProfileIn( __METHOD__
."-e1" );
1603 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1605 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1606 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1607 # the real problem is with the $e1 regex
1610 # Still some problems for cases where the ] is meant to be outside punctuation,
1611 # and no image is in sight. See bug 2095.
1614 substr( $m[3], 0, 1 ) === ']' &&
1615 strpos($text, '[') !== false
1618 $text .= ']'; # so that replaceExternalLinks($text) works later
1619 $m[3] = substr( $m[3], 1 );
1621 # fix up urlencoded title texts
1622 if( strpos( $m[1], '%' ) !== false ) {
1623 # Should anchors '#' also be rejected?
1624 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1627 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1628 $might_be_img = true;
1630 if ( strpos( $m[1], '%' ) !== false ) {
1631 $m[1] = urldecode($m[1]);
1634 } else { # Invalid form; output directly
1635 $s .= $prefix . '[[' . $line ;
1636 wfProfileOut( __METHOD__
."-e1" );
1639 wfProfileOut( __METHOD__
."-e1" );
1640 wfProfileIn( __METHOD__
."-misc" );
1642 # Don't allow internal links to pages containing
1643 # PROTO: where PROTO is a valid URL protocol; these
1644 # should be external links.
1645 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1646 $s .= $prefix . '[[' . $line ;
1647 wfProfileOut( __METHOD__
."-misc" );
1651 # Make subpage if necessary
1652 if( $useSubpages ) {
1653 $link = $this->maybeDoSubpageLink( $m[1], $text );
1658 $noforce = (substr($m[1], 0, 1) !== ':');
1660 # Strip off leading ':'
1661 $link = substr($link, 1);
1664 wfProfileOut( __METHOD__
."-misc" );
1665 wfProfileIn( __METHOD__
."-title" );
1666 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1668 $s .= $prefix . '[[' . $line;
1669 wfProfileOut( __METHOD__
."-title" );
1673 $ns = $nt->getNamespace();
1674 $iw = $nt->getInterWiki();
1675 wfProfileOut( __METHOD__
."-title" );
1677 if ($might_be_img) { # if this is actually an invalid link
1678 wfProfileIn( __METHOD__
."-might_be_img" );
1679 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1682 #look at the next 'line' to see if we can close it there
1684 $next_line = $a->current();
1685 if ( $next_line === false ||
$next_line === null ) {
1688 $m = explode( ']]', $next_line, 3 );
1689 if ( count( $m ) == 3 ) {
1690 # the first ]] closes the inner link, the second the image
1692 $text .= "[[{$m[0]}]]{$m[1]}";
1695 } elseif ( count( $m ) == 2 ) {
1696 #if there's exactly one ]] that's fine, we'll keep looking
1697 $text .= "[[{$m[0]}]]{$m[1]}";
1699 #if $next_line is invalid too, we need look no further
1700 $text .= '[[' . $next_line;
1705 # we couldn't find the end of this imageLink, so output it raw
1706 #but don't ignore what might be perfectly normal links in the text we've examined
1707 $holders->merge( $this->replaceInternalLinks2( $text ) );
1708 $s .= "{$prefix}[[$link|$text";
1709 # note: no $trail, because without an end, there *is* no trail
1710 wfProfileOut( __METHOD__
."-might_be_img" );
1713 } else { #it's not an image, so output it raw
1714 $s .= "{$prefix}[[$link|$text";
1715 # note: no $trail, because without an end, there *is* no trail
1716 wfProfileOut( __METHOD__
."-might_be_img" );
1719 wfProfileOut( __METHOD__
."-might_be_img" );
1722 $wasblank = ( '' == $text );
1723 if( $wasblank ) $text = $link;
1725 # Link not escaped by : , create the various objects
1729 wfProfileIn( __METHOD__
."-interwiki" );
1730 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1731 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1732 $s = rtrim($s . $prefix);
1733 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1734 wfProfileOut( __METHOD__
."-interwiki" );
1737 wfProfileOut( __METHOD__
."-interwiki" );
1739 if ( $ns == NS_IMAGE
) {
1740 wfProfileIn( __METHOD__
."-image" );
1741 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1742 # recursively parse links inside the image caption
1743 # actually, this will parse them in any other parameters, too,
1744 # but it might be hard to fix that, and it doesn't matter ATM
1745 $text = $this->replaceExternalLinks($text);
1746 $holders->merge( $this->replaceInternalLinks2( $text ) );
1748 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1749 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1751 $this->mOutput
->addImage( $nt->getDBkey() );
1752 wfProfileOut( __METHOD__
."-image" );
1757 if ( $ns == NS_CATEGORY
) {
1758 wfProfileIn( __METHOD__
."-category" );
1759 $s = rtrim($s . "\n"); # bug 87
1762 $sortkey = $this->getDefaultSort();
1766 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1767 $sortkey = str_replace( "\n", '', $sortkey );
1768 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1769 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1772 * Strip the whitespace Category links produce, see bug 87
1773 * @todo We might want to use trim($tmp, "\n") here.
1775 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1777 wfProfileOut( __METHOD__
."-category" );
1782 # Self-link checking
1783 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1784 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1785 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1790 # Special and Media are pseudo-namespaces; no pages actually exist in them
1791 if( $ns == NS_MEDIA
) {
1792 # Give extensions a chance to select the file revision for us
1793 $skip = $time = false;
1794 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1796 $link = $sk->link( $nt );
1798 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1800 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1801 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1802 $this->mOutput
->addImage( $nt->getDBkey() );
1804 } elseif( $ns == NS_SPECIAL
) {
1805 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1806 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1808 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1811 } elseif( $ns == NS_IMAGE
) {
1812 $img = wfFindFile( $nt );
1814 // Force a blue link if the file exists; may be a remote
1815 // upload on the shared repository, and we want to see its
1816 // auto-generated page.
1817 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1818 $this->mOutput
->addLink( $nt );
1822 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1824 wfProfileOut( __METHOD__
);
1829 * Make a link placeholder. The text returned can be later resolved to a real link with
1830 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1831 * parsing of interwiki links, and secondly to allow all existence checks and
1832 * article length checks (for stub links) to be bundled into a single query.
1836 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1837 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1841 * Render a forced-blue link inline; protect against double expansion of
1842 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1843 * Since this little disaster has to split off the trail text to avoid
1844 * breaking URLs in the following text without breaking trails on the
1845 * wiki links, it's been made into a horrible function.
1848 * @param string $text
1849 * @param string $query
1850 * @param string $trail
1851 * @param string $prefix
1852 * @return string HTML-wikitext mix oh yuck
1854 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1855 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1856 $sk = $this->mOptions
->getSkin();
1857 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1858 return $this->armorLinks( $link ) . $trail;
1862 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1863 * going to go through further parsing steps before inline URL expansion.
1865 * Not needed quite as much as it used to be since free links are a bit
1866 * more sensible these days. But bracketed links are still an issue.
1868 * @param string more-or-less HTML
1869 * @return string less-or-more HTML with NOPARSE bits
1871 function armorLinks( $text ) {
1872 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1873 "{$this->mUniqPrefix}NOPARSE$1", $text );
1877 * Return true if subpage links should be expanded on this page.
1880 function areSubpagesAllowed() {
1881 # Some namespaces don't allow subpages
1882 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1886 * Handle link to subpage if necessary
1887 * @param string $target the source of the link
1888 * @param string &$text the link text, modified as necessary
1889 * @return string the full name of the link
1892 function maybeDoSubpageLink($target, &$text) {
1895 # :Foobar -- override special treatment of prefix (images, language links)
1896 # /Foobar -- convert to CurrentPage/Foobar
1897 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1898 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1899 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1901 wfProfileIn( __METHOD__
);
1902 $ret = $target; # default return value is no change
1904 # Some namespaces don't allow subpages,
1905 # so only perform processing if subpages are allowed
1906 if( $this->areSubpagesAllowed() ) {
1907 $hash = strpos( $target, '#' );
1908 if( $hash !== false ) {
1909 $suffix = substr( $target, $hash );
1910 $target = substr( $target, 0, $hash );
1915 $target = trim( $target );
1916 # Look at the first character
1917 if( $target != '' && $target{0} === '/' ) {
1918 # / at end means we don't want the slash to be shown
1920 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1921 if( $trailingSlashes ) {
1922 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1924 $noslash = substr( $target, 1 );
1927 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1928 if( '' === $text ) {
1929 $text = $target . $suffix;
1930 } # this might be changed for ugliness reasons
1932 # check for .. subpage backlinks
1934 $nodotdot = $target;
1935 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1937 $nodotdot = substr( $nodotdot, 3 );
1939 if($dotdotcount > 0) {
1940 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1941 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1942 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1943 # / at the end means don't show full path
1944 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1945 $nodotdot = substr( $nodotdot, 0, -1 );
1946 if( '' === $text ) {
1947 $text = $nodotdot . $suffix;
1950 $nodotdot = trim( $nodotdot );
1951 if( $nodotdot != '' ) {
1952 $ret .= '/' . $nodotdot;
1960 wfProfileOut( __METHOD__
);
1965 * Used by doBlockLevels()
1968 /* private */ function closeParagraph() {
1970 if ( '' != $this->mLastSection
) {
1971 $result = '</' . $this->mLastSection
. ">\n";
1973 $this->mInPre
= false;
1974 $this->mLastSection
= '';
1977 # getCommon() returns the length of the longest common substring
1978 # of both arguments, starting at the beginning of both.
1980 /* private */ function getCommon( $st1, $st2 ) {
1981 $fl = strlen( $st1 );
1982 $shorter = strlen( $st2 );
1983 if ( $fl < $shorter ) { $shorter = $fl; }
1985 for ( $i = 0; $i < $shorter; ++
$i ) {
1986 if ( $st1{$i} != $st2{$i} ) { break; }
1990 # These next three functions open, continue, and close the list
1991 # element appropriate to the prefix character passed into them.
1993 /* private */ function openList( $char ) {
1994 $result = $this->closeParagraph();
1996 if ( '*' === $char ) { $result .= '<ul><li>'; }
1997 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1998 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1999 else if ( ';' === $char ) {
2000 $result .= '<dl><dt>';
2001 $this->mDTopen
= true;
2003 else { $result = '<!-- ERR 1 -->'; }
2008 /* private */ function nextItem( $char ) {
2009 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2010 else if ( ':' === $char ||
';' === $char ) {
2012 if ( $this->mDTopen
) { $close = '</dt>'; }
2013 if ( ';' === $char ) {
2014 $this->mDTopen
= true;
2015 return $close . '<dt>';
2017 $this->mDTopen
= false;
2018 return $close . '<dd>';
2021 return '<!-- ERR 2 -->';
2024 /* private */ function closeList( $char ) {
2025 if ( '*' === $char ) { $text = '</li></ul>'; }
2026 else if ( '#' === $char ) { $text = '</li></ol>'; }
2027 else if ( ':' === $char ) {
2028 if ( $this->mDTopen
) {
2029 $this->mDTopen
= false;
2030 $text = '</dt></dl>';
2032 $text = '</dd></dl>';
2035 else { return '<!-- ERR 3 -->'; }
2041 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2044 * @return string the lists rendered as HTML
2046 function doBlockLevels( $text, $linestart ) {
2047 wfProfileIn( __METHOD__
);
2049 # Parsing through the text line by line. The main thing
2050 # happening here is handling of block-level elements p, pre,
2051 # and making lists from lines starting with * # : etc.
2053 $textLines = StringUtils
::explode( "\n", $text );
2055 $lastPrefix = $output = '';
2056 $this->mDTopen
= $inBlockElem = false;
2058 $paragraphStack = false;
2060 foreach ( $textLines as $oLine ) {
2062 if ( !$linestart ) {
2068 $lastPrefixLength = strlen( $lastPrefix );
2069 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2070 $preOpenMatch = preg_match('/<pre/i', $oLine );
2071 if ( !$this->mInPre
) {
2072 # Multiple prefixes may abut each other for nested lists.
2073 $prefixLength = strspn( $oLine, '*#:;' );
2074 $prefix = substr( $oLine, 0, $prefixLength );
2077 $prefix2 = str_replace( ';', ':', $prefix );
2078 $t = substr( $oLine, $prefixLength );
2079 $this->mInPre
= (bool)$preOpenMatch;
2081 # Don't interpret any other prefixes in preformatted text
2083 $prefix = $prefix2 = '';
2088 if( $prefixLength && $lastPrefix === $prefix2 ) {
2089 # Same as the last item, so no need to deal with nesting or opening stuff
2090 $output .= $this->nextItem( substr( $prefix, -1 ) );
2091 $paragraphStack = false;
2093 if ( substr( $prefix, -1 ) === ';') {
2094 # The one nasty exception: definition lists work like this:
2095 # ; title : definition text
2096 # So we check for : in the remainder text to split up the
2097 # title and definition, without b0rking links.
2099 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2101 $output .= $term . $this->nextItem( ':' );
2104 } elseif( $prefixLength ||
$lastPrefixLength ) {
2105 # Either open or close a level...
2106 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2107 $paragraphStack = false;
2109 while( $commonPrefixLength < $lastPrefixLength ) {
2110 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2111 --$lastPrefixLength;
2113 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2114 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2116 while ( $prefixLength > $commonPrefixLength ) {
2117 $char = substr( $prefix, $commonPrefixLength, 1 );
2118 $output .= $this->openList( $char );
2120 if ( ';' === $char ) {
2121 # FIXME: This is dupe of code above
2122 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2124 $output .= $term . $this->nextItem( ':' );
2127 ++
$commonPrefixLength;
2129 $lastPrefix = $prefix2;
2131 if( 0 == $prefixLength ) {
2132 wfProfileIn( __METHOD__
."-paragraph" );
2133 # No prefix (not in list)--go to paragraph mode
2134 // XXX: use a stack for nestable elements like span, table and div
2135 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2136 $closematch = preg_match(
2137 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2138 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2139 if ( $openmatch or $closematch ) {
2140 $paragraphStack = false;
2141 #Â TODO bug 5718: paragraph closed
2142 $output .= $this->closeParagraph();
2143 if ( $preOpenMatch and !$preCloseMatch ) {
2144 $this->mInPre
= true;
2146 if ( $closematch ) {
2147 $inBlockElem = false;
2149 $inBlockElem = true;
2151 } else if ( !$inBlockElem && !$this->mInPre
) {
2152 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2154 if ($this->mLastSection
!== 'pre') {
2155 $paragraphStack = false;
2156 $output .= $this->closeParagraph().'<pre>';
2157 $this->mLastSection
= 'pre';
2159 $t = substr( $t, 1 );
2162 if ( '' == trim($t) ) {
2163 if ( $paragraphStack ) {
2164 $output .= $paragraphStack.'<br />';
2165 $paragraphStack = false;
2166 $this->mLastSection
= 'p';
2168 if ($this->mLastSection
!== 'p' ) {
2169 $output .= $this->closeParagraph();
2170 $this->mLastSection
= '';
2171 $paragraphStack = '<p>';
2173 $paragraphStack = '</p><p>';
2177 if ( $paragraphStack ) {
2178 $output .= $paragraphStack;
2179 $paragraphStack = false;
2180 $this->mLastSection
= 'p';
2181 } else if ($this->mLastSection
!== 'p') {
2182 $output .= $this->closeParagraph().'<p>';
2183 $this->mLastSection
= 'p';
2188 wfProfileOut( __METHOD__
."-paragraph" );
2190 // somewhere above we forget to get out of pre block (bug 785)
2191 if($preCloseMatch && $this->mInPre
) {
2192 $this->mInPre
= false;
2194 if ($paragraphStack === false) {
2198 while ( $prefixLength ) {
2199 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2202 if ( '' != $this->mLastSection
) {
2203 $output .= '</' . $this->mLastSection
. '>';
2204 $this->mLastSection
= '';
2207 wfProfileOut( __METHOD__
);
2212 * Split up a string on ':', ignoring any occurences inside tags
2213 * to prevent illegal overlapping.
2214 * @param string $str the string to split
2215 * @param string &$before set to everything before the ':'
2216 * @param string &$after set to everything after the ':'
2217 * return string the position of the ':', or false if none found
2219 function findColonNoLinks($str, &$before, &$after) {
2220 wfProfileIn( __METHOD__
);
2222 $pos = strpos( $str, ':' );
2223 if( $pos === false ) {
2225 wfProfileOut( __METHOD__
);
2229 $lt = strpos( $str, '<' );
2230 if( $lt === false ||
$lt > $pos ) {
2231 // Easy; no tag nesting to worry about
2232 $before = substr( $str, 0, $pos );
2233 $after = substr( $str, $pos+
1 );
2234 wfProfileOut( __METHOD__
);
2238 // Ugly state machine to walk through avoiding tags.
2239 $state = self
::COLON_STATE_TEXT
;
2241 $len = strlen( $str );
2242 for( $i = 0; $i < $len; $i++
) {
2246 // (Using the number is a performance hack for common cases)
2247 case 0: // self::COLON_STATE_TEXT:
2250 // Could be either a <start> tag or an </end> tag
2251 $state = self
::COLON_STATE_TAGSTART
;
2256 $before = substr( $str, 0, $i );
2257 $after = substr( $str, $i +
1 );
2258 wfProfileOut( __METHOD__
);
2261 // Embedded in a tag; don't break it.
2264 // Skip ahead looking for something interesting
2265 $colon = strpos( $str, ':', $i );
2266 if( $colon === false ) {
2267 // Nothing else interesting
2268 wfProfileOut( __METHOD__
);
2271 $lt = strpos( $str, '<', $i );
2272 if( $stack === 0 ) {
2273 if( $lt === false ||
$colon < $lt ) {
2275 $before = substr( $str, 0, $colon );
2276 $after = substr( $str, $colon +
1 );
2277 wfProfileOut( __METHOD__
);
2281 if( $lt === false ) {
2282 // Nothing else interesting to find; abort!
2283 // We're nested, but there's no close tags left. Abort!
2286 // Skip ahead to next tag start
2288 $state = self
::COLON_STATE_TAGSTART
;
2291 case 1: // self::COLON_STATE_TAG:
2296 $state = self
::COLON_STATE_TEXT
;
2299 // Slash may be followed by >?
2300 $state = self
::COLON_STATE_TAGSLASH
;
2306 case 2: // self::COLON_STATE_TAGSTART:
2309 $state = self
::COLON_STATE_CLOSETAG
;
2312 $state = self
::COLON_STATE_COMMENT
;
2315 // Illegal early close? This shouldn't happen D:
2316 $state = self
::COLON_STATE_TEXT
;
2319 $state = self
::COLON_STATE_TAG
;
2322 case 3: // self::COLON_STATE_CLOSETAG:
2327 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2328 wfProfileOut( __METHOD__
);
2331 $state = self
::COLON_STATE_TEXT
;
2334 case self
::COLON_STATE_TAGSLASH
:
2336 // Yes, a self-closed tag <blah/>
2337 $state = self
::COLON_STATE_TEXT
;
2339 // Probably we're jumping the gun, and this is an attribute
2340 $state = self
::COLON_STATE_TAG
;
2343 case 5: // self::COLON_STATE_COMMENT:
2345 $state = self
::COLON_STATE_COMMENTDASH
;
2348 case self
::COLON_STATE_COMMENTDASH
:
2350 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2352 $state = self
::COLON_STATE_COMMENT
;
2355 case self
::COLON_STATE_COMMENTDASHDASH
:
2357 $state = self
::COLON_STATE_TEXT
;
2359 $state = self
::COLON_STATE_COMMENT
;
2363 throw new MWException( "State machine error in " . __METHOD__
);
2367 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2370 wfProfileOut( __METHOD__
);
2375 * Return value of a magic variable (like PAGENAME)
2379 function getVariableValue( $index ) {
2380 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2383 * Some of these require message or data lookups and can be
2384 * expensive to check many times.
2386 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2387 if ( isset( $this->mVarCache
[$index] ) ) {
2388 return $this->mVarCache
[$index];
2392 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2393 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2396 global $wgLocaltimezone;
2397 if ( isset( $wgLocaltimezone ) ) {
2398 $oldtz = getenv( 'TZ' );
2399 putenv( 'TZ='.$wgLocaltimezone );
2402 wfSuppressWarnings(); // E_STRICT system time bitching
2403 $localTimestamp = date( 'YmdHis', $ts );
2404 $localMonth = date( 'm', $ts );
2405 $localMonthName = date( 'n', $ts );
2406 $localDay = date( 'j', $ts );
2407 $localDay2 = date( 'd', $ts );
2408 $localDayOfWeek = date( 'w', $ts );
2409 $localWeek = date( 'W', $ts );
2410 $localYear = date( 'Y', $ts );
2411 $localHour = date( 'H', $ts );
2412 if ( isset( $wgLocaltimezone ) ) {
2413 putenv( 'TZ='.$oldtz );
2415 wfRestoreWarnings();
2418 case 'currentmonth':
2419 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2420 case 'currentmonthname':
2421 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2422 case 'currentmonthnamegen':
2423 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2424 case 'currentmonthabbrev':
2425 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2427 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2429 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2431 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2432 case 'localmonthname':
2433 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2434 case 'localmonthnamegen':
2435 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2436 case 'localmonthabbrev':
2437 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2439 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2441 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2443 return wfEscapeWikiText( $this->mTitle
->getText() );
2445 return $this->mTitle
->getPartialURL();
2446 case 'fullpagename':
2447 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2448 case 'fullpagenamee':
2449 return $this->mTitle
->getPrefixedURL();
2451 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2452 case 'subpagenamee':
2453 return $this->mTitle
->getSubpageUrlForm();
2454 case 'basepagename':
2455 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2456 case 'basepagenamee':
2457 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2458 case 'talkpagename':
2459 if( $this->mTitle
->canTalk() ) {
2460 $talkPage = $this->mTitle
->getTalkPage();
2461 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2465 case 'talkpagenamee':
2466 if( $this->mTitle
->canTalk() ) {
2467 $talkPage = $this->mTitle
->getTalkPage();
2468 return $talkPage->getPrefixedUrl();
2472 case 'subjectpagename':
2473 $subjPage = $this->mTitle
->getSubjectPage();
2474 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2475 case 'subjectpagenamee':
2476 $subjPage = $this->mTitle
->getSubjectPage();
2477 return $subjPage->getPrefixedUrl();
2479 // Let the edit saving system know we should parse the page
2480 // *after* a revision ID has been assigned.
2481 $this->mOutput
->setFlag( 'vary-revision' );
2482 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2483 return $this->mRevisionId
;
2485 // Let the edit saving system know we should parse the page
2486 // *after* a revision ID has been assigned. This is for null edits.
2487 $this->mOutput
->setFlag( 'vary-revision' );
2488 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2489 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2490 case 'revisionday2':
2491 // Let the edit saving system know we should parse the page
2492 // *after* a revision ID has been assigned. This is for null edits.
2493 $this->mOutput
->setFlag( 'vary-revision' );
2494 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2495 return substr( $this->getRevisionTimestamp(), 6, 2 );
2496 case 'revisionmonth':
2497 // Let the edit saving system know we should parse the page
2498 // *after* a revision ID has been assigned. This is for null edits.
2499 $this->mOutput
->setFlag( 'vary-revision' );
2500 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2501 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2502 case 'revisionyear':
2503 // Let the edit saving system know we should parse the page
2504 // *after* a revision ID has been assigned. This is for null edits.
2505 $this->mOutput
->setFlag( 'vary-revision' );
2506 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2507 return substr( $this->getRevisionTimestamp(), 0, 4 );
2508 case 'revisiontimestamp':
2509 // Let the edit saving system know we should parse the page
2510 // *after* a revision ID has been assigned. This is for null edits.
2511 $this->mOutput
->setFlag( 'vary-revision' );
2512 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2513 return $this->getRevisionTimestamp();
2515 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2517 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2519 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2521 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2522 case 'subjectspace':
2523 return $this->mTitle
->getSubjectNsText();
2524 case 'subjectspacee':
2525 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2526 case 'currentdayname':
2527 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2531 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2535 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2536 // int to remove the padding
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2540 case 'localdayname':
2541 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2545 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2547 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2549 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2550 // int to remove the padding
2551 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2553 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2554 case 'numberofarticles':
2555 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2556 case 'numberoffiles':
2557 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2558 case 'numberofusers':
2559 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2560 case 'numberofpages':
2561 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2562 case 'numberofadmins':
2563 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2564 case 'numberofedits':
2565 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2566 case 'currenttimestamp':
2567 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2568 case 'localtimestamp':
2569 return $this->mVarCache
[$index] = $localTimestamp;
2570 case 'currentversion':
2571 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2577 return $wgServerName;
2579 return $wgScriptPath;
2580 case 'directionmark':
2581 return $wgContLang->getDirMark();
2582 case 'contentlanguage':
2583 global $wgContLanguageCode;
2584 return $wgContLanguageCode;
2587 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2595 * initialise the magic variables (like CURRENTMONTHNAME)
2599 function initialiseVariables() {
2600 wfProfileIn( __METHOD__
);
2601 $variableIDs = MagicWord
::getVariableIDs();
2603 $this->mVariables
= new MagicWordArray( $variableIDs );
2604 wfProfileOut( __METHOD__
);
2608 * Preprocess some wikitext and return the document tree.
2609 * This is the ghost of replace_variables().
2611 * @param string $text The text to parse
2612 * @param integer flags Bitwise combination of:
2613 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2614 * included. Default is to assume a direct page view.
2616 * The generated DOM tree must depend only on the input text and the flags.
2617 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2619 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2620 * change in the DOM tree for a given text, must be passed through the section identifier
2621 * in the section edit link and thus back to extractSections().
2623 * The output of this function is currently only cached in process memory, but a persistent
2624 * cache may be implemented at a later date which takes further advantage of these strict
2625 * dependency requirements.
2629 function preprocessToDom ( $text, $flags = 0 ) {
2630 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2635 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2637 public static function splitWhitespace( $s ) {
2638 $ltrimmed = ltrim( $s );
2639 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2640 $trimmed = rtrim( $ltrimmed );
2641 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2643 $w2 = substr( $ltrimmed, -$diff );
2647 return array( $w1, $trimmed, $w2 );
2651 * Replace magic variables, templates, and template arguments
2652 * with the appropriate text. Templates are substituted recursively,
2653 * taking care to avoid infinite loops.
2655 * Note that the substitution depends on value of $mOutputType:
2656 * self::OT_WIKI: only {{subst:}} templates
2657 * self::OT_PREPROCESS: templates but not extension tags
2658 * self::OT_HTML: all templates and extension tags
2660 * @param string $tex The text to transform
2661 * @param PPFrame $frame Object describing the arguments passed to the template.
2662 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2663 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2664 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2667 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2668 # Prevent too big inclusions
2669 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2673 wfProfileIn( __METHOD__
);
2675 if ( $frame === false ) {
2676 $frame = $this->getPreprocessor()->newFrame();
2677 } elseif ( !( $frame instanceof PPFrame
) ) {
2678 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2679 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2682 $dom = $this->preprocessToDom( $text );
2683 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2684 $text = $frame->expand( $dom, $flags );
2686 wfProfileOut( __METHOD__
);
2690 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2691 static function createAssocArgs( $args ) {
2692 $assocArgs = array();
2694 foreach( $args as $arg ) {
2695 $eqpos = strpos( $arg, '=' );
2696 if ( $eqpos === false ) {
2697 $assocArgs[$index++
] = $arg;
2699 $name = trim( substr( $arg, 0, $eqpos ) );
2700 $value = trim( substr( $arg, $eqpos+
1 ) );
2701 if ( $value === false ) {
2704 if ( $name !== false ) {
2705 $assocArgs[$name] = $value;
2714 * Warn the user when a parser limitation is reached
2715 * Will warn at most once the user per limitation type
2717 * @param string $limitationType, should be one of:
2718 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2719 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2720 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2721 * @params int $current, $max When an explicit limit has been
2722 * exceeded, provide the values (optional)
2724 function limitationWarn( $limitationType, $current=null, $max=null) {
2725 $msgName = $limitationType . '-warning';
2726 //does no harm if $current and $max are present but are unnecessary for the message
2727 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2728 $this->mOutput
->addWarning( $warning );
2729 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2731 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2736 * Return the text of a template, after recursively
2737 * replacing any variables or templates within the template.
2739 * @param array $piece The parts of the template
2740 * $piece['title']: the title, i.e. the part before the |
2741 * $piece['parts']: the parameter array
2742 * $piece['lineStart']: whether the brace was at the start of a line
2743 * @param PPFrame The current frame, contains template arguments
2744 * @return string the text of the template
2747 function braceSubstitution( $piece, $frame ) {
2748 global $wgContLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2749 wfProfileIn( __METHOD__
);
2750 wfProfileIn( __METHOD__
.'-setup' );
2753 $found = false; # $text has been filled
2754 $nowiki = false; # wiki markup in $text should be escaped
2755 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2756 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2757 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2758 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2760 # Title object, where $text came from
2763 # $part1 is the bit before the first |, and must contain only title characters.
2764 # Various prefixes will be stripped from it later.
2765 $titleWithSpaces = $frame->expand( $piece['title'] );
2766 $part1 = trim( $titleWithSpaces );
2769 # Original title text preserved for various purposes
2770 $originalTitle = $part1;
2772 # $args is a list of argument nodes, starting from index 0, not including $part1
2773 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2774 wfProfileOut( __METHOD__
.'-setup' );
2777 wfProfileIn( __METHOD__
.'-modifiers' );
2779 $mwSubst = MagicWord
::get( 'subst' );
2780 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2781 # One of two possibilities is true:
2782 # 1) Found SUBST but not in the PST phase
2783 # 2) Didn't find SUBST and in the PST phase
2784 # In either case, return without further processing
2785 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2792 if ( !$found && $args->getLength() == 0 ) {
2793 $id = $this->mVariables
->matchStartToEnd( $part1 );
2794 if ( $id !== false ) {
2795 $text = $this->getVariableValue( $id );
2796 if (MagicWord
::getCacheTTL($id)>-1)
2797 $this->mOutput
->mContainsOldMagic
= true;
2802 # MSG, MSGNW and RAW
2805 $mwMsgnw = MagicWord
::get( 'msgnw' );
2806 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2809 # Remove obsolete MSG:
2810 $mwMsg = MagicWord
::get( 'msg' );
2811 $mwMsg->matchStartAndRemove( $part1 );
2815 $mwRaw = MagicWord
::get( 'raw' );
2816 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2817 $forceRawInterwiki = true;
2820 wfProfileOut( __METHOD__
.'-modifiers' );
2824 wfProfileIn( __METHOD__
. '-pfunc' );
2826 $colonPos = strpos( $part1, ':' );
2827 if ( $colonPos !== false ) {
2828 # Case sensitive functions
2829 $function = substr( $part1, 0, $colonPos );
2830 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2831 $function = $this->mFunctionSynonyms
[1][$function];
2833 # Case insensitive functions
2834 $function = strtolower( $function );
2835 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2836 $function = $this->mFunctionSynonyms
[0][$function];
2842 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2843 $initialArgs = array( &$this );
2844 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2845 if ( $flags & SFH_OBJECT_ARGS
) {
2846 # Add a frame parameter, and pass the arguments as an array
2847 $allArgs = $initialArgs;
2848 $allArgs[] = $frame;
2849 for ( $i = 0; $i < $args->getLength(); $i++
) {
2850 $funcArgs[] = $args->item( $i );
2852 $allArgs[] = $funcArgs;
2854 # Convert arguments to plain text
2855 for ( $i = 0; $i < $args->getLength(); $i++
) {
2856 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2858 $allArgs = array_merge( $initialArgs, $funcArgs );
2861 # Workaround for PHP bug 35229 and similar
2862 if ( !is_callable( $callback ) ) {
2863 throw new MWException( "Tag hook for $function is not callable\n" );
2865 $result = call_user_func_array( $callback, $allArgs );
2868 $preprocessFlags = 0;
2870 if ( is_array( $result ) ) {
2871 if ( isset( $result[0] ) ) {
2873 unset( $result[0] );
2876 // Extract flags into the local scope
2877 // This allows callers to set flags such as nowiki, found, etc.
2883 $text = $this->preprocessToDom( $text, $preprocessFlags );
2888 wfProfileOut( __METHOD__
. '-pfunc' );
2891 # Finish mangling title and then check for loops.
2892 # Set $title to a Title object and $titleText to the PDBK
2895 # Split the title into page and subpage
2897 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2898 if ($subpage !== '') {
2899 $ns = $this->mTitle
->getNamespace();
2901 $title = Title
::newFromText( $part1, $ns );
2903 $titleText = $title->getPrefixedText();
2904 # Check for language variants if the template is not found
2905 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2906 $wgContLang->findVariantLink( $part1, $title, true );
2908 # Do infinite loop check
2909 if ( !$frame->loopCheck( $title ) ) {
2911 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2912 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2914 # Do recursion depth check
2915 $limit = $this->mOptions
->getMaxTemplateDepth();
2916 if ( $frame->depth
>= $limit ) {
2918 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2923 # Load from database
2924 if ( !$found && $title ) {
2925 wfProfileIn( __METHOD__
. '-loadtpl' );
2926 if ( !$title->isExternal() ) {
2927 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2928 $text = SpecialPage
::capturePath( $title );
2929 if ( is_string( $text ) ) {
2932 $this->disableCache();
2934 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2935 $found = false; //access denied
2936 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2938 list( $text, $title ) = $this->getTemplateDom( $title );
2939 if ( $text !== false ) {
2945 # If the title is valid but undisplayable, make a link to it
2946 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2947 $text = "[[:$titleText]]";
2950 } elseif ( $title->isTrans() ) {
2951 // Interwiki transclusion
2952 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2953 $text = $this->interwikiTransclude( $title, 'render' );
2956 $text = $this->interwikiTransclude( $title, 'raw' );
2957 // Preprocess it like a template
2958 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2963 wfProfileOut( __METHOD__
. '-loadtpl' );
2966 # If we haven't found text to substitute by now, we're done
2967 # Recover the source wikitext and return it
2969 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2970 wfProfileOut( __METHOD__
);
2971 return array( 'object' => $text );
2974 # Expand DOM-style return values in a child frame
2975 if ( $isChildObj ) {
2976 # Clean up argument array
2977 $newFrame = $frame->newChild( $args, $title );
2980 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2981 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2982 # Expansion is eligible for the empty-frame cache
2983 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2984 $text = $this->mTplExpandCache
[$titleText];
2986 $text = $newFrame->expand( $text );
2987 $this->mTplExpandCache
[$titleText] = $text;
2990 # Uncached expansion
2991 $text = $newFrame->expand( $text );
2994 if ( $isLocalObj && $nowiki ) {
2995 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2996 $isLocalObj = false;
2999 # Replace raw HTML by a placeholder
3000 # Add a blank line preceding, to prevent it from mucking up
3001 # immediately preceding headings
3003 $text = "\n\n" . $this->insertStripItem( $text );
3005 # Escape nowiki-style return values
3006 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3007 $text = wfEscapeWikiText( $text );
3009 # Bug 529: if the template begins with a table or block-level
3010 # element, it should be treated as beginning a new line.
3011 # This behaviour is somewhat controversial.
3012 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3013 $text = "\n" . $text;
3016 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3017 # Error, oversize inclusion
3018 $text = "[[$originalTitle]]" .
3019 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3020 $this->limitationWarn( 'post-expand-template-inclusion' );
3023 if ( $isLocalObj ) {
3024 $ret = array( 'object' => $text );
3026 $ret = array( 'text' => $text );
3029 wfProfileOut( __METHOD__
);
3034 * Get the semi-parsed DOM representation of a template with a given title,
3035 * and its redirect destination title. Cached.
3037 function getTemplateDom( $title ) {
3038 $cacheTitle = $title;
3039 $titleText = $title->getPrefixedDBkey();
3041 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3042 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3043 $title = Title
::makeTitle( $ns, $dbk );
3044 $titleText = $title->getPrefixedDBkey();
3046 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3047 return array( $this->mTplDomCache
[$titleText], $title );
3050 // Cache miss, go to the database
3051 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3053 if ( $text === false ) {
3054 $this->mTplDomCache
[$titleText] = false;
3055 return array( false, $title );
3058 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3059 $this->mTplDomCache
[ $titleText ] = $dom;
3061 if (! $title->equals($cacheTitle)) {
3062 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3063 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3066 return array( $dom, $title );
3070 * Fetch the unparsed text of a template and register a reference to it.
3072 function fetchTemplateAndTitle( $title ) {
3073 $templateCb = $this->mOptions
->getTemplateCallback();
3074 $stuff = call_user_func( $templateCb, $title, $this );
3075 $text = $stuff['text'];
3076 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3077 if ( isset( $stuff['deps'] ) ) {
3078 foreach ( $stuff['deps'] as $dep ) {
3079 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3082 return array($text,$finalTitle);
3085 function fetchTemplate( $title ) {
3086 $rv = $this->fetchTemplateAndTitle($title);
3091 * Static function to get a template
3092 * Can be overridden via ParserOptions::setTemplateCallback().
3094 static function statelessFetchTemplate( $title, $parser=false ) {
3095 $text = $skip = false;
3096 $finalTitle = $title;
3099 // Loop to fetch the article, with up to 1 redirect
3100 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3101 # Give extensions a chance to select the revision instead
3102 $id = false; // Assume current
3103 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3109 'page_id' => $title->getArticleID(),
3113 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3114 $rev_id = $rev ?
$rev->getId() : 0;
3115 // If there is no current revision, there is no page
3116 if( $id === false && !$rev ) {
3117 $linkCache = LinkCache
::singleton();
3118 $linkCache->addBadLinkObj( $title );
3123 'page_id' => $title->getArticleID(),
3124 'rev_id' => $rev_id );
3127 $text = $rev->getText();
3128 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3130 $message = $wgContLang->lcfirst( $title->getText() );
3131 $text = wfMsgForContentNoTrans( $message );
3132 if( wfEmptyMsg( $message, $text ) ) {
3139 if ( $text === false ) {
3143 $finalTitle = $title;
3144 $title = Title
::newFromRedirect( $text );
3148 'finalTitle' => $finalTitle,
3153 * Transclude an interwiki link.
3155 function interwikiTransclude( $title, $action ) {
3156 global $wgEnableScaryTranscluding;
3158 if (!$wgEnableScaryTranscluding)
3159 return wfMsg('scarytranscludedisabled');
3161 $url = $title->getFullUrl( "action=$action" );
3163 if (strlen($url) > 255)
3164 return wfMsg('scarytranscludetoolong');
3165 return $this->fetchScaryTemplateMaybeFromCache($url);
3168 function fetchScaryTemplateMaybeFromCache($url) {
3169 global $wgTranscludeCacheExpiry;
3170 $dbr = wfGetDB(DB_SLAVE
);
3171 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3172 array('tc_url' => $url));
3174 $time = $obj->tc_time
;
3175 $text = $obj->tc_contents
;
3176 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3181 $text = Http
::get($url);
3183 return wfMsg('scarytranscludefailed', $url);
3185 $dbw = wfGetDB(DB_MASTER
);
3186 $dbw->replace('transcache', array('tc_url'), array(
3188 'tc_time' => time(),
3189 'tc_contents' => $text));
3195 * Triple brace replacement -- used for template arguments
3198 function argSubstitution( $piece, $frame ) {
3199 wfProfileIn( __METHOD__
);
3202 $parts = $piece['parts'];
3203 $nameWithSpaces = $frame->expand( $piece['title'] );
3204 $argName = trim( $nameWithSpaces );
3206 $text = $frame->getArgument( $argName );
3207 if ( $text === false && $parts->getLength() > 0
3211 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3214 # No match in frame, use the supplied default
3215 $object = $parts->item( 0 )->getChildren();
3217 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3218 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3219 $this->limitationWarn( 'post-expand-template-argument' );
3222 if ( $text === false && $object === false ) {
3224 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3226 if ( $error !== false ) {
3229 if ( $object !== false ) {
3230 $ret = array( 'object' => $object );
3232 $ret = array( 'text' => $text );
3235 wfProfileOut( __METHOD__
);
3240 * Return the text to be used for a given extension tag.
3241 * This is the ghost of strip().
3243 * @param array $params Associative array of parameters:
3244 * name PPNode for the tag name
3245 * attr PPNode for unparsed text where tag attributes are thought to be
3246 * attributes Optional associative array of parsed attributes
3247 * inner Contents of extension element
3248 * noClose Original text did not have a close tag
3249 * @param PPFrame $frame
3251 function extensionSubstitution( $params, $frame ) {
3252 global $wgRawHtml, $wgContLang;
3254 $name = $frame->expand( $params['name'] );
3255 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3256 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3258 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3260 if ( $this->ot
['html'] ) {
3261 $name = strtolower( $name );
3263 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3264 if ( isset( $params['attributes'] ) ) {
3265 $attributes = $attributes +
$params['attributes'];
3273 throw new MWException( '<html> extension tag encountered unexpectedly' );
3276 $output = Xml
::escapeTagsOnly( $content );
3279 $output = $wgContLang->armourMath(
3280 MathRenderer
::renderMath( $content, $attributes ) );
3283 $output = $this->renderImageGallery( $content, $attributes );
3286 if( isset( $this->mTagHooks
[$name] ) ) {
3287 # Workaround for PHP bug 35229 and similar
3288 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3289 throw new MWException( "Tag hook for $name is not callable\n" );
3291 $output = call_user_func_array( $this->mTagHooks
[$name],
3292 array( $content, $attributes, $this ) );
3294 $output = '<span class="error">Invalid tag extension name: ' .
3295 htmlspecialchars( $name ) . '</span>';
3299 if ( is_null( $attrText ) ) {
3302 if ( isset( $params['attributes'] ) ) {
3303 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3304 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3305 htmlspecialchars( $attrValue ) . '"';
3308 if ( $content === null ) {
3309 $output = "<$name$attrText/>";
3311 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3312 $output = "<$name$attrText>$content$close";
3316 if ( $name === 'html' ||
$name === 'nowiki' ) {
3317 $this->mStripState
->nowiki
->setPair( $marker, $output );
3319 $this->mStripState
->general
->setPair( $marker, $output );
3325 * Increment an include size counter
3327 * @param string $type The type of expansion
3328 * @param integer $size The size of the text
3329 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3331 function incrementIncludeSize( $type, $size ) {
3332 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3335 $this->mIncludeSizes
[$type] +
= $size;
3341 * Increment the expensive function count
3343 * @return boolean False if the limit has been exceeded
3345 function incrementExpensiveFunctionCount() {
3346 global $wgExpensiveParserFunctionLimit;
3347 $this->mExpensiveFunctionCount++
;
3348 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3355 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3356 * Fills $this->mDoubleUnderscores, returns the modified text
3358 function doDoubleUnderscore( $text ) {
3359 // The position of __TOC__ needs to be recorded
3360 $mw = MagicWord
::get( 'toc' );
3361 if( $mw->match( $text ) ) {
3362 $this->mShowToc
= true;
3363 $this->mForceTocPosition
= true;
3365 // Set a placeholder. At the end we'll fill it in with the TOC.
3366 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3368 // Only keep the first one.
3369 $text = $mw->replace( '', $text );
3372 // Now match and remove the rest of them
3373 $mwa = MagicWord
::getDoubleUnderscoreArray();
3374 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3376 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3377 $this->mOutput
->mNoGallery
= true;
3379 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3380 $this->mShowToc
= false;
3382 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3383 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3385 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3386 if ( $containerCategory ) {
3387 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3389 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3392 # (bug 8068) Allow control over whether robots index a page.
3394 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3395 # is not desirable, the last one on the page should win.
3396 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3397 $this->mOutput
->setIndexPolicy( 'noindex' );
3398 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3399 $this->mOutput
->setIndexPolicy( 'index' );
3406 * This function accomplishes several tasks:
3407 * 1) Auto-number headings if that option is enabled
3408 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3409 * 3) Add a Table of contents on the top for users who have enabled the option
3410 * 4) Auto-anchor headings
3412 * It loops through all headlines, collects the necessary data, then splits up the
3413 * string and re-inserts the newly formatted headlines.
3415 * @param string $text
3416 * @param boolean $isMain
3419 function formatHeadings( $text, $isMain=true ) {
3420 global $wgMaxTocLevel, $wgContLang;
3422 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3423 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3426 $showEditLink = $this->mOptions
->getEditSection();
3429 # Inhibit editsection links if requested in the page
3430 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3434 # Get all headlines for numbering them and adding funky stuff like [edit]
3435 # links - this is for later, but we need the number of headlines right now
3437 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3439 # if there are fewer than 4 headlines in the article, do not show TOC
3440 # unless it's been explicitly enabled.
3441 $enoughToc = $this->mShowToc
&&
3442 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3444 # Allow user to stipulate that a page should have a "new section"
3445 # link added via __NEWSECTIONLINK__
3446 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3447 $this->mOutput
->setNewSection( true );
3450 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3451 # override above conditions and always show TOC above first header
3452 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3453 $this->mShowToc
= true;
3457 # We need this to perform operations on the HTML
3458 $sk = $this->mOptions
->getSkin();
3464 # Ugh .. the TOC should have neat indentation levels which can be
3465 # passed to the skin functions. These are determined here
3469 $sublevelCount = array();
3470 $levelCount = array();
3476 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3477 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3480 foreach( $matches[3] as $headline ) {
3481 $isTemplate = false;
3483 $sectionIndex = false;
3485 $markerMatches = array();
3486 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3487 $serial = $markerMatches[1];
3488 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3489 $isTemplate = ($titleText != $baseTitleText);
3490 $headline = preg_replace("/^$markerRegex/", "", $headline);
3494 $prevlevel = $level;
3495 $prevtoclevel = $toclevel;
3497 $level = $matches[1][$headlineCount];
3499 if( $doNumberHeadings ||
$enoughToc ) {
3501 if ( $level > $prevlevel ) {
3502 # Increase TOC level
3504 $sublevelCount[$toclevel] = 0;
3505 if( $toclevel<$wgMaxTocLevel ) {
3506 $prevtoclevel = $toclevel;
3507 $toc .= $sk->tocIndent();
3511 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3512 # Decrease TOC level, find level to jump to
3514 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3515 # Can only go down to level 1
3518 for ($i = $toclevel; $i > 0; $i--) {
3519 if ( $levelCount[$i] == $level ) {
3520 # Found last matching level
3524 elseif ( $levelCount[$i] < $level ) {
3525 # Found first matching level below current level
3531 if( $toclevel<$wgMaxTocLevel ) {
3532 if($prevtoclevel < $wgMaxTocLevel) {
3533 # Unindent only if the previous toc level was shown :p
3534 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3535 $prevtoclevel = $toclevel;
3537 $toc .= $sk->tocLineEnd();
3542 # No change in level, end TOC line
3543 if( $toclevel<$wgMaxTocLevel ) {
3544 $toc .= $sk->tocLineEnd();
3548 $levelCount[$toclevel] = $level;
3550 # count number of headlines for each level
3551 @$sublevelCount[$toclevel]++
;
3553 for( $i = 1; $i <= $toclevel; $i++
) {
3554 if( !empty( $sublevelCount[$i] ) ) {
3558 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3564 # The safe header is a version of the header text safe to use for links
3565 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3566 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3568 # Remove link placeholders by the link text.
3569 # <!--LINK number-->
3571 # link text with suffix
3572 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3574 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3575 $tocline = preg_replace(
3576 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3580 $tocline = trim( $tocline );
3582 # For the anchor, strip out HTML-y stuff period
3583 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3584 $safeHeadline = trim( $safeHeadline );
3586 # Save headline for section edit hint before it's escaped
3587 $headlineHint = $safeHeadline;
3588 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3589 # HTML names must be case-insensitively unique (bug 10721)
3590 $arrayKey = strtolower( $safeHeadline );
3592 # count how many in assoc. array so we can track dupes in anchors
3593 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3594 $refcount[$headlineCount] = $refers[$arrayKey];
3596 # Don't number the heading if it is the only one (looks silly)
3597 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3598 # the two are different if the line contains a link
3599 $headline=$numbering . ' ' . $headline;
3602 # Create the anchor for linking from the TOC to the section
3603 $anchor = $safeHeadline;
3604 if($refcount[$headlineCount] > 1 ) {
3605 $anchor .= '_' . $refcount[$headlineCount];
3607 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3608 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3609 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3611 # give headline the correct <h#> tag
3612 if( $showEditLink && $sectionIndex !== false ) {
3614 # Put a T flag in the section identifier, to indicate to extractSections()
3615 # that sections inside <includeonly> should be counted.
3616 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3618 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3623 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3628 $this->mOutput
->setSections( $tocraw );
3630 # Never ever show TOC if no headers
3631 if( $numVisible < 1 ) {
3636 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3637 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3639 $toc = $sk->tocList( $toc );
3642 # split up and insert constructed headlines
3644 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3647 foreach( $blocks as $block ) {
3648 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3649 # This is the [edit] link that appears for the top block of text when
3650 # section editing is enabled
3652 # Disabled because it broke block formatting
3653 # For example, a bullet point in the top line
3654 # $full .= $sk->editSectionLink(0);
3657 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3658 # Top anchor now in skin
3662 if( !empty( $head[$i] ) ) {
3667 if( $this->mForceTocPosition
) {
3668 return str_replace( '<!--MWTOC-->', $toc, $full );
3675 * Transform wiki markup when saving a page by doing \r\n -> \n
3676 * conversion, substitting signatures, {{subst:}} templates, etc.
3678 * @param string $text the text to transform
3679 * @param Title &$title the Title object for the current article
3680 * @param User &$user the User object describing the current user
3681 * @param ParserOptions $options parsing options
3682 * @param bool $clearState whether to clear the parser state first
3683 * @return string the altered wiki markup
3686 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3687 $this->mOptions
= $options;
3688 $this->setTitle( $title );
3689 $this->setOutputType( self
::OT_WIKI
);
3691 if ( $clearState ) {
3692 $this->clearState();
3698 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3699 $text = $this->pstPass2( $text, $user );
3700 $text = $this->mStripState
->unstripBoth( $text );
3705 * Pre-save transform helper function
3708 function pstPass2( $text, $user ) {
3709 global $wgContLang, $wgLocaltimezone;
3711 /* Note: This is the timestamp saved as hardcoded wikitext to
3712 * the database, we use $wgContLang here in order to give
3713 * everyone the same signature and use the default one rather
3714 * than the one selected in each user's preferences.
3716 * (see also bug 12815)
3718 $ts = $this->mOptions
->getTimestamp();
3719 $tz = wfMsgForContent( 'timezone-utc' );
3720 if ( isset( $wgLocaltimezone ) ) {
3721 $unixts = wfTimestamp( TS_UNIX
, $ts );
3722 $oldtz = getenv( 'TZ' );
3723 putenv( 'TZ='.$wgLocaltimezone );
3724 $ts = date( 'YmdHis', $unixts );
3725 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3726 putenv( 'TZ='.$oldtz );
3729 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3731 # Variable replacement
3732 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3733 $text = $this->replaceVariables( $text );
3736 $sigText = $this->getUserSig( $user );
3737 $text = strtr( $text, array(
3739 '~~~~' => "$sigText $d",
3743 # Context links: [[|name]] and [[name (context)|]]
3745 global $wgLegalTitleChars;
3746 $tc = "[$wgLegalTitleChars]";
3747 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3749 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3750 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3751 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3752 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3754 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3755 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3756 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3757 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3759 $t = $this->mTitle
->getText();
3761 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3762 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3763 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3764 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3766 # if there's no context, don't bother duplicating the title
3767 $text = preg_replace( $p2, '[[\\1]]', $text );
3770 # Trim trailing whitespace
3771 $text = rtrim( $text );
3777 * Fetch the user's signature text, if any, and normalize to
3778 * validated, ready-to-insert wikitext.
3784 function getUserSig( &$user ) {
3785 global $wgMaxSigChars;
3787 $username = $user->getName();
3788 $nickname = $user->getOption( 'nickname' );
3789 $nickname = $nickname === '' ?
$username : $nickname;
3791 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3792 $nickname = $username;
3793 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3794 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3795 # Sig. might contain markup; validate this
3796 if( $this->validateSig( $nickname ) !== false ) {
3797 # Validated; clean up (if needed) and return it
3798 return $this->cleanSig( $nickname, true );
3800 # Failed to validate; fall back to the default
3801 $nickname = $username;
3802 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3806 // Make sure nickname doesnt get a sig in a sig
3807 $nickname = $this->cleanSigInSig( $nickname );
3809 # If we're still here, make it a link to the user page
3810 $userText = wfEscapeWikiText( $username );
3811 $nickText = wfEscapeWikiText( $nickname );
3812 if ( $user->isAnon() ) {
3813 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3815 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3820 * Check that the user's signature contains no bad XML
3822 * @param string $text
3823 * @return mixed An expanded string, or false if invalid.
3825 function validateSig( $text ) {
3826 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3830 * Clean up signature text
3832 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3833 * 2) Substitute all transclusions
3835 * @param string $text
3836 * @param $parsing Whether we're cleaning (preferences save) or parsing
3837 * @return string Signature text
3839 function cleanSig( $text, $parsing = false ) {
3842 $this->clearState();
3843 $this->setTitle( $wgTitle );
3844 $this->mOptions
= new ParserOptions
;
3845 $this->setOutputType
= self
::OT_PREPROCESS
;
3848 # Option to disable this feature
3849 if ( !$this->mOptions
->getCleanSignatures() ) {
3853 # FIXME: regex doesn't respect extension tags or nowiki
3854 # => Move this logic to braceSubstitution()
3855 $substWord = MagicWord
::get( 'subst' );
3856 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3857 $substText = '{{' . $substWord->getSynonym( 0 );
3859 $text = preg_replace( $substRegex, $substText, $text );
3860 $text = $this->cleanSigInSig( $text );
3861 $dom = $this->preprocessToDom( $text );
3862 $frame = $this->getPreprocessor()->newFrame();
3863 $text = $frame->expand( $dom );
3866 $text = $this->mStripState
->unstripBoth( $text );
3873 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3874 * @param string $text
3875 * @return string Signature text with /~{3,5}/ removed
3877 function cleanSigInSig( $text ) {
3878 $text = preg_replace( '/~{3,5}/', '', $text );
3883 * Set up some variables which are usually set up in parse()
3884 * so that an external function can call some class members with confidence
3887 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3888 $this->setTitle( $title );
3889 $this->mOptions
= $options;
3890 $this->setOutputType( $outputType );
3891 if ( $clearState ) {
3892 $this->clearState();
3897 * Wrapper for preprocess()
3899 * @param string $text the text to preprocess
3900 * @param ParserOptions $options options
3904 function transformMsg( $text, $options ) {
3906 static $executing = false;
3908 # Guard against infinite recursion
3914 wfProfileIn(__METHOD__
);
3915 $text = $this->preprocess( $text, $wgTitle, $options );
3918 wfProfileOut(__METHOD__
);
3923 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3924 * The callback should have the following form:
3925 * function myParserHook( $text, $params, &$parser ) { ... }
3927 * Transform and return $text. Use $parser for any required context, e.g. use
3928 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3932 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3933 * @param mixed $callback The callback function (and object) to use for the tag
3935 * @return The old value of the mTagHooks array associated with the hook
3937 function setHook( $tag, $callback ) {
3938 $tag = strtolower( $tag );
3939 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3940 $this->mTagHooks
[$tag] = $callback;
3941 if( !in_array( $tag, $this->mStripList
) ) {
3942 $this->mStripList
[] = $tag;
3948 function setTransparentTagHook( $tag, $callback ) {
3949 $tag = strtolower( $tag );
3950 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3951 $this->mTransparentTagHooks
[$tag] = $callback;
3957 * Remove all tag hooks
3959 function clearTagHooks() {
3960 $this->mTagHooks
= array();
3961 $this->mStripList
= $this->mDefaultStripList
;
3965 * Create a function, e.g. {{sum:1|2|3}}
3966 * The callback function should have the form:
3967 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3969 * Or with SFH_OBJECT_ARGS:
3970 * function myParserFunction( $parser, $frame, $args ) { ... }
3972 * The callback may either return the text result of the function, or an array with the text
3973 * in element 0, and a number of flags in the other elements. The names of the flags are
3974 * specified in the keys. Valid flags are:
3975 * found The text returned is valid, stop processing the template. This
3977 * nowiki Wiki markup in the return value should be escaped
3978 * isHTML The returned text is HTML, armour it against wikitext transformation
3982 * @param string $id The magic word ID
3983 * @param mixed $callback The callback function (and object) to use
3984 * @param integer $flags a combination of the following flags:
3985 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3987 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3988 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3989 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3990 * the arguments, and to control the way they are expanded.
3992 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3993 * arguments, for instance:
3994 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3996 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3997 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3998 * working if/when this is changed.
4000 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4003 * Please read the documentation in includes/parser/Preprocessor.php for more information
4004 * about the methods available in PPFrame and PPNode.
4006 * @return The old callback function for this name, if any
4008 function setFunctionHook( $id, $callback, $flags = 0 ) {
4009 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4010 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4012 # Add to function cache
4013 $mw = MagicWord
::get( $id );
4015 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4017 $synonyms = $mw->getSynonyms();
4018 $sensitive = intval( $mw->isCaseSensitive() );
4020 foreach ( $synonyms as $syn ) {
4022 if ( !$sensitive ) {
4023 $syn = strtolower( $syn );
4026 if ( !( $flags & SFH_NO_HASH
) ) {
4029 # Remove trailing colon
4030 if ( substr( $syn, -1, 1 ) === ':' ) {
4031 $syn = substr( $syn, 0, -1 );
4033 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4039 * Get all registered function hook identifiers
4043 function getFunctionHooks() {
4044 return array_keys( $this->mFunctionHooks
);
4048 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4049 * Placeholders created in Skin::makeLinkObj()
4050 * Returns an array of link CSS classes, indexed by PDBK.
4052 function replaceLinkHolders( &$text, $options = 0 ) {
4053 return $this->mLinkHolders
->replace( $text );
4057 * Replace <!--LINK--> link placeholders with plain text of links
4058 * (not HTML-formatted).
4059 * @param string $text
4062 function replaceLinkHoldersText( $text ) {
4063 return $this->mLinkHolders
->replaceText( $text );
4067 * Tag hook handler for 'pre'.
4069 function renderPreTag( $text, $attribs ) {
4070 // Backwards-compatibility hack
4071 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4073 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4074 return wfOpenElement( 'pre', $attribs ) .
4075 Xml
::escapeTagsOnly( $content ) .
4080 * Renders an image gallery from a text with one line per image.
4081 * text labels may be given by using |-style alternative text. E.g.
4082 * Image:one.jpg|The number "1"
4083 * Image:tree.jpg|A tree
4084 * given as text will return the HTML of a gallery with two images,
4085 * labeled 'The number "1"' and
4088 function renderImageGallery( $text, $params ) {
4089 $ig = new ImageGallery();
4090 $ig->setContextTitle( $this->mTitle
);
4091 $ig->setShowBytes( false );
4092 $ig->setShowFilename( false );
4093 $ig->setParser( $this );
4094 $ig->setHideBadImages();
4095 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4096 $ig->useSkin( $this->mOptions
->getSkin() );
4097 $ig->mRevisionId
= $this->mRevisionId
;
4099 if( isset( $params['caption'] ) ) {
4100 $caption = $params['caption'];
4101 $caption = htmlspecialchars( $caption );
4102 $caption = $this->replaceInternalLinks( $caption );
4103 $ig->setCaptionHtml( $caption );
4105 if( isset( $params['perrow'] ) ) {
4106 $ig->setPerRow( $params['perrow'] );
4108 if( isset( $params['widths'] ) ) {
4109 $ig->setWidths( $params['widths'] );
4111 if( isset( $params['heights'] ) ) {
4112 $ig->setHeights( $params['heights'] );
4115 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4117 $lines = StringUtils
::explode( "\n", $text );
4118 foreach ( $lines as $line ) {
4119 # match lines like these:
4120 # Image:someimage.jpg|This is some image
4122 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4124 if ( count( $matches ) == 0 ) {
4128 if ( strpos( $matches[0], '%' ) !== false )
4129 $matches[1] = urldecode( $matches[1] );
4130 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4132 if( is_null( $nt ) ) {
4133 # Bogus title. Ignore these so we don't bomb out later.
4136 if ( isset( $matches[3] ) ) {
4137 $label = $matches[3];
4142 $html = $this->recursiveTagParse( trim( $label ) );
4144 $ig->add( $nt, $html );
4146 # Only add real images (bug #5586)
4147 if ( $nt->getNamespace() == NS_IMAGE
) {
4148 $this->mOutput
->addImage( $nt->getDBkey() );
4151 return $ig->toHTML();
4154 function getImageParams( $handler ) {
4156 $handlerClass = get_class( $handler );
4160 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4161 // Initialise static lists
4162 static $internalParamNames = array(
4163 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4164 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4165 'bottom', 'text-bottom' ),
4166 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4167 'upright', 'border' ),
4169 static $internalParamMap;
4170 if ( !$internalParamMap ) {
4171 $internalParamMap = array();
4172 foreach ( $internalParamNames as $type => $names ) {
4173 foreach ( $names as $name ) {
4174 $magicName = str_replace( '-', '_', "img_$name" );
4175 $internalParamMap[$magicName] = array( $type, $name );
4180 // Add handler params
4181 $paramMap = $internalParamMap;
4183 $handlerParamMap = $handler->getParamMap();
4184 foreach ( $handlerParamMap as $magic => $paramName ) {
4185 $paramMap[$magic] = array( 'handler', $paramName );
4188 $this->mImageParams
[$handlerClass] = $paramMap;
4189 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4191 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4195 * Parse image options text and use it to make an image
4196 * @param Title $title
4197 * @param string $options
4198 * @param LinkHolderArray $holders
4200 function makeImage( $title, $options, $holders = false ) {
4201 # Check if the options text is of the form "options|alt text"
4203 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4204 # * left no resizing, just left align. label is used for alt= only
4205 # * right same, but right aligned
4206 # * none same, but not aligned
4207 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4208 # * center center the image
4209 # * framed Keep original image size, no magnify-button.
4210 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4211 # * upright reduce width for upright images, rounded to full __0 px
4212 # * border draw a 1px border around the image
4213 # vertical-align values (no % or length right now):
4223 $parts = StringUtils
::explode( "|", $options );
4224 $sk = $this->mOptions
->getSkin();
4226 # Give extensions a chance to select the file revision for us
4227 $skip = $time = $descQuery = false;
4228 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4231 return $sk->link( $title );
4235 $file = wfFindFile( $title, $time );
4236 $handler = $file ?
$file->getHandler() : false;
4238 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4240 # Process the input parameters
4242 $params = array( 'frame' => array(), 'handler' => array(),
4243 'horizAlign' => array(), 'vertAlign' => array() );
4244 foreach( $parts as $part ) {
4245 $part = trim( $part );
4246 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4248 if( isset( $paramMap[$magicName] ) ) {
4249 list( $type, $paramName ) = $paramMap[$magicName];
4251 // Special case; width and height come in one variable together
4252 if( $type === 'handler' && $paramName === 'width' ) {
4254 # (bug 13500) In both cases (width/height and width only),
4255 # permit trailing "px" for backward compatibility.
4256 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4257 $width = intval( $m[1] );
4258 $height = intval( $m[2] );
4259 if ( $handler->validateParam( 'width', $width ) ) {
4260 $params[$type]['width'] = $width;
4263 if ( $handler->validateParam( 'height', $height ) ) {
4264 $params[$type]['height'] = $height;
4267 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4268 $width = intval( $value );
4269 if ( $handler->validateParam( 'width', $width ) ) {
4270 $params[$type]['width'] = $width;
4273 } // else no validation -- bug 13436
4275 if ( $type === 'handler' ) {
4276 # Validate handler parameter
4277 $validated = $handler->validateParam( $paramName, $value );
4279 # Validate internal parameters
4280 switch( $paramName ) {
4282 /// @fixme - possibly check validity here?
4283 /// downstream behavior seems odd with missing manual thumbs.
4287 // Most other things appear to be empty or numeric...
4288 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4293 $params[$type][$paramName] = $value;
4297 if ( !$validated ) {
4302 # Process alignment parameters
4303 if ( $params['horizAlign'] ) {
4304 $params['frame']['align'] = key( $params['horizAlign'] );
4306 if ( $params['vertAlign'] ) {
4307 $params['frame']['valign'] = key( $params['vertAlign'] );
4310 # Strip bad stuff out of the alt text
4311 # We can't just use replaceLinkHoldersText() here, because if this function
4312 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4314 $alt = $holders->replaceText( $caption );
4316 $alt = $this->replaceLinkHoldersText( $caption );
4319 # make sure there are no placeholders in thumbnail attributes
4320 # that are later expanded to html- so expand them now and
4322 $alt = $this->mStripState
->unstripBoth( $alt );
4323 $alt = Sanitizer
::stripAllTags( $alt );
4325 $params['frame']['alt'] = $alt;
4326 $params['frame']['caption'] = $caption;
4328 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4330 # Linker does the rest
4331 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4333 # Give the handler a chance to modify the parser object
4335 $handler->parserTransformHook( $this, $file );
4342 * Set a flag in the output object indicating that the content is dynamic and
4343 * shouldn't be cached.
4345 function disableCache() {
4346 wfDebug( "Parser output marked as uncacheable.\n" );
4347 $this->mOutput
->mCacheTime
= -1;
4351 * Callback from the Sanitizer for expanding items found in HTML attribute
4352 * values, so they can be safely tested and escaped.
4353 * @param string $text
4354 * @param PPFrame $frame
4358 function attributeStripCallback( &$text, $frame = false ) {
4359 $text = $this->replaceVariables( $text, $frame );
4360 $text = $this->mStripState
->unstripBoth( $text );
4369 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4370 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4371 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4377 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4382 * Break wikitext input into sections, and either pull or replace
4383 * some particular section's text.
4385 * External callers should use the getSection and replaceSection methods.
4387 * @param string $text Page wikitext
4388 * @param string $section A section identifier string of the form:
4389 * <flag1> - <flag2> - ... - <section number>
4391 * Currently the only recognised flag is "T", which means the target section number
4392 * was derived during a template inclusion parse, in other words this is a template
4393 * section edit link. If no flags are given, it was an ordinary section edit link.
4394 * This flag is required to avoid a section numbering mismatch when a section is
4395 * enclosed by <includeonly> (bug 6563).
4397 * The section number 0 pulls the text before the first heading; other numbers will
4398 * pull the given section along with its lower-level subsections. If the section is
4399 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4401 * @param string $mode One of "get" or "replace"
4402 * @param string $newText Replacement text for section data.
4403 * @return string for "get", the extracted section text.
4404 * for "replace", the whole page with the section replaced.
4406 private function extractSections( $text, $section, $mode, $newText='' ) {
4408 $this->clearState();
4409 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4410 $this->mOptions
= new ParserOptions
;
4411 $this->setOutputType( self
::OT_WIKI
);
4413 $frame = $this->getPreprocessor()->newFrame();
4415 // Process section extraction flags
4417 $sectionParts = explode( '-', $section );
4418 $sectionIndex = array_pop( $sectionParts );
4419 foreach ( $sectionParts as $part ) {
4420 if ( $part === 'T' ) {
4421 $flags |
= self
::PTD_FOR_INCLUSION
;
4424 // Preprocess the text
4425 $root = $this->preprocessToDom( $text, $flags );
4427 // <h> nodes indicate section breaks
4428 // They can only occur at the top level, so we can find them by iterating the root's children
4429 $node = $root->getFirstChild();
4431 // Find the target section
4432 if ( $sectionIndex == 0 ) {
4433 // Section zero doesn't nest, level=big
4434 $targetLevel = 1000;
4437 if ( $node->getName() === 'h' ) {
4438 $bits = $node->splitHeading();
4439 if ( $bits['i'] == $sectionIndex ) {
4440 $targetLevel = $bits['level'];
4444 if ( $mode === 'replace' ) {
4445 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4447 $node = $node->getNextSibling();
4453 if ( $mode === 'get' ) {
4460 // Find the end of the section, including nested sections
4462 if ( $node->getName() === 'h' ) {
4463 $bits = $node->splitHeading();
4464 $curLevel = $bits['level'];
4465 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4469 if ( $mode === 'get' ) {
4470 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4472 $node = $node->getNextSibling();
4475 // Write out the remainder (in replace mode only)
4476 if ( $mode === 'replace' ) {
4477 // Output the replacement text
4478 // Add two newlines on -- trailing whitespace in $newText is conventionally
4479 // stripped by the editor, so we need both newlines to restore the paragraph gap
4480 $outText .= $newText . "\n\n";
4482 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4483 $node = $node->getNextSibling();
4487 if ( is_string( $outText ) ) {
4488 // Re-insert stripped tags
4489 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4496 * This function returns the text of a section, specified by a number ($section).
4497 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4498 * the first section before any such heading (section 0).
4500 * If a section contains subsections, these are also returned.
4502 * @param string $text text to look in
4503 * @param string $section section identifier
4504 * @param string $deftext default to return if section is not found
4505 * @return string text of the requested section
4507 public function getSection( $text, $section, $deftext='' ) {
4508 return $this->extractSections( $text, $section, "get", $deftext );
4511 public function replaceSection( $oldtext, $section, $text ) {
4512 return $this->extractSections( $oldtext, $section, "replace", $text );
4516 * Get the timestamp associated with the current revision, adjusted for
4517 * the default server-local timestamp
4519 function getRevisionTimestamp() {
4520 if ( is_null( $this->mRevisionTimestamp
) ) {
4521 wfProfileIn( __METHOD__
);
4523 $dbr = wfGetDB( DB_SLAVE
);
4524 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4525 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4527 // Normalize timestamp to internal MW format for timezone processing.
4528 // This has the added side-effect of replacing a null value with
4529 // the current time, which gives us more sensible behavior for
4531 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4533 // The cryptic '' timezone parameter tells to use the site-default
4534 // timezone offset instead of the user settings.
4536 // Since this value will be saved into the parser cache, served
4537 // to other users, and potentially even used inside links and such,
4538 // it needs to be consistent for all visitors.
4539 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4541 wfProfileOut( __METHOD__
);
4543 return $this->mRevisionTimestamp
;
4547 * Mutator for $mDefaultSort
4549 * @param $sort New value
4551 public function setDefaultSort( $sort ) {
4552 $this->mDefaultSort
= $sort;
4556 * Accessor for $mDefaultSort
4557 * Will use the title/prefixed title if none is set
4561 public function getDefaultSort() {
4562 global $wgCategoryPrefixedDefaultSortkey;
4563 if( $this->mDefaultSort
!== false ) {
4564 return $this->mDefaultSort
;
4565 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4566 !$wgCategoryPrefixedDefaultSortkey) {
4567 return $this->mTitle
->getText();
4569 return $this->mTitle
->getPrefixedText();
4574 * Try to guess the section anchor name based on a wikitext fragment
4575 * presumably extracted from a heading, for example "Header" from
4578 public function guessSectionNameFromWikiText( $text ) {
4579 # Strip out wikitext links(they break the anchor)
4580 $text = $this->stripSectionName( $text );
4581 $headline = Sanitizer
::decodeCharReferences( $text );
4583 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4584 $headline = trim( $headline );
4585 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4586 $replacearray = array(
4591 array_keys( $replacearray ),
4592 array_values( $replacearray ),
4597 * Strips a text string of wikitext for use in a section anchor
4599 * Accepts a text string and then removes all wikitext from the
4600 * string and leaves only the resultant text (i.e. the result of
4601 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4602 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4603 * to create valid section anchors by mimicing the output of the
4604 * parser when headings are parsed.
4606 * @param $text string Text string to be stripped of wikitext
4607 * for use in a Section anchor
4608 * @return Filtered text string
4610 public function stripSectionName( $text ) {
4611 # Strip internal link markup
4612 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4613 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4615 # Strip external link markup (FIXME: Not Tolerant to blank link text
4616 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4617 # on how many empty links there are on the page - need to figure that out.
4618 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4620 # Parse wikitext quotes (italics & bold)
4621 $text = $this->doQuotes($text);
4624 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4628 function srvus( $text ) {
4629 return $this->testSrvus( $text, $this->mOutputType
);
4633 * strip/replaceVariables/unstrip for preprocessor regression testing
4635 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4636 $this->clearState();
4637 if ( ! ( $title instanceof Title
) ) {
4638 $title = Title
::newFromText( $title );
4640 $this->mTitle
= $title;
4641 $this->mOptions
= $options;
4642 $this->setOutputType( $outputType );
4643 $text = $this->replaceVariables( $text );
4644 $text = $this->mStripState
->unstripBoth( $text );
4645 $text = Sanitizer
::removeHTMLtags( $text );
4649 function testPst( $text, $title, $options ) {
4651 if ( ! ( $title instanceof Title
) ) {
4652 $title = Title
::newFromText( $title );
4654 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4657 function testPreprocess( $text, $title, $options ) {
4658 if ( ! ( $title instanceof Title
) ) {
4659 $title = Title
::newFromText( $title );
4661 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4664 function markerSkipCallback( $s, $callback ) {
4667 while ( $i < strlen( $s ) ) {
4668 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4669 if ( $markerStart === false ) {
4670 $out .= call_user_func( $callback, substr( $s, $i ) );
4673 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4674 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4675 if ( $markerEnd === false ) {
4676 $out .= substr( $s, $markerStart );
4679 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4680 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4690 * @todo document, briefly.
4694 var $general, $nowiki;
4696 function __construct() {
4697 $this->general
= new ReplacementArray
;
4698 $this->nowiki
= new ReplacementArray
;
4701 function unstripGeneral( $text ) {
4702 wfProfileIn( __METHOD__
);
4705 $text = $this->general
->replace( $text );
4706 } while ( $text !== $oldText );
4707 wfProfileOut( __METHOD__
);
4711 function unstripNoWiki( $text ) {
4712 wfProfileIn( __METHOD__
);
4715 $text = $this->nowiki
->replace( $text );
4716 } while ( $text !== $oldText );
4717 wfProfileOut( __METHOD__
);
4721 function unstripBoth( $text ) {
4722 wfProfileIn( __METHOD__
);
4725 $text = $this->general
->replace( $text );
4726 $text = $this->nowiki
->replace( $text );
4727 } while ( $text !== $oldText );
4728 wfProfileOut( __METHOD__
);
4734 * @todo document, briefly.
4737 class OnlyIncludeReplacer
{
4740 function replace( $matches ) {
4741 if ( substr( $matches[1], -1 ) === "\n" ) {
4742 $this->output
.= substr( $matches[1], 0, -1 );
4744 $this->output
.= $matches[1];