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 $text = '[' . ++
$this->mAutonumber
. ']';
1380 $linktype = 'autonumber';
1382 # Otherwise just use the URL
1383 $text = htmlspecialchars( $url );
1387 # Have link text, e.g. [http://domain.tld/some.link text]s
1389 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1392 $text = $wgContLang->markNoConversion($text);
1394 $url = Sanitizer
::cleanUrl( $url );
1396 # Use the encoded URL
1397 # This means that users can paste URLs directly into the text
1398 # Funny characters like ö aren't valid in URLs anyway
1399 # This was changed in August 2004
1400 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1402 # Register link in the output object.
1403 # Replace unnecessary URL escape codes with the referenced character
1404 # This prevents spammers from hiding links from the filters
1405 $pasteurized = self
::replaceUnusualEscapes( $url );
1406 $this->mOutput
->addExternalLink( $pasteurized );
1409 wfProfileOut( __METHOD__
);
1414 * Replace unusual URL escape codes with their equivalent characters
1418 * @todo This can merge genuinely required bits in the path or query string,
1419 * breaking legit URLs. A proper fix would treat the various parts of
1420 * the URL differently; as a workaround, just use the output for
1421 * statistical records, not for actual linking/output.
1423 static function replaceUnusualEscapes( $url ) {
1424 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1425 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1429 * Callback function used in replaceUnusualEscapes().
1430 * Replaces unusual URL escape codes with their equivalent character
1434 private static function replaceUnusualEscapesCallback( $matches ) {
1435 $char = urldecode( $matches[0] );
1436 $ord = ord( $char );
1437 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1438 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1439 // No, shouldn't be escaped
1442 // Yes, leave it escaped
1448 * make an image if it's allowed, either through the global
1449 * option, through the exception, or through the on-wiki whitelist
1452 function maybeMakeExternalImage( $url ) {
1453 $sk = $this->mOptions
->getSkin();
1454 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1455 $imagesexception = !empty($imagesfrom);
1457 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1458 if( $imagesexception && is_array( $imagesfrom ) ) {
1459 $imagematch = false;
1460 foreach( $imagesfrom as $match ) {
1461 if( strpos( $url, $match ) === 0 ) {
1466 } elseif( $imagesexception ) {
1467 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1469 $imagematch = false;
1471 if ( $this->mOptions
->getAllowExternalImages()
1472 ||
( $imagesexception && $imagematch ) ) {
1473 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1475 $text = $sk->makeExternalImage( $url );
1478 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1479 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1480 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1481 foreach( $whitelist as $entry ) {
1482 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1483 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1485 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1486 # Image matches a whitelist entry
1487 $text = $sk->makeExternalImage( $url );
1496 * Process [[ ]] wikilinks
1497 * @return processed text
1501 function replaceInternalLinks( $s ) {
1502 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1507 * Process [[ ]] wikilinks (RIL)
1508 * @return LinkHolderArray
1512 function replaceInternalLinks2( &$s ) {
1515 wfProfileIn( __METHOD__
);
1517 wfProfileIn( __METHOD__
.'-setup' );
1518 static $tc = FALSE, $e1, $e1_img;
1519 # the % is needed to support urlencoded titles as well
1521 $tc = Title
::legalChars() . '#%';
1522 # Match a link having the form [[namespace:link|alternate]]trail
1523 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1524 # Match cases where there is no "]]", which might still be images
1525 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1528 $sk = $this->mOptions
->getSkin();
1529 $holders = new LinkHolderArray( $this );
1531 #split the entire text string on occurences of [[
1532 $a = StringUtils
::explode( '[[', ' ' . $s );
1533 #get the first element (all text up to first [[), and remove the space we added
1536 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1537 $s = substr( $s, 1 );
1539 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1541 if ( $useLinkPrefixExtension ) {
1542 # Match the end of a line for a word that's not followed by whitespace,
1543 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1544 $e2 = wfMsgForContent( 'linkprefix' );
1547 if( is_null( $this->mTitle
) ) {
1548 wfProfileOut( __METHOD__
.'-setup' );
1549 wfProfileOut( __METHOD__
);
1550 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1552 $nottalk = !$this->mTitle
->isTalkPage();
1554 if ( $useLinkPrefixExtension ) {
1556 if ( preg_match( $e2, $s, $m ) ) {
1557 $first_prefix = $m[2];
1559 $first_prefix = false;
1565 if($wgContLang->hasVariants()) {
1566 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1568 $selflink = array($this->mTitle
->getPrefixedText());
1570 $useSubpages = $this->areSubpagesAllowed();
1571 wfProfileOut( __METHOD__
.'-setup' );
1573 # Loop for each link
1574 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1575 # Check for excessive memory usage
1576 if ( $holders->isBig() ) {
1578 # Do the existence check, replace the link holders and clear the array
1579 $holders->replace( $s );
1583 if ( $useLinkPrefixExtension ) {
1584 wfProfileIn( __METHOD__
.'-prefixhandling' );
1585 if ( preg_match( $e2, $s, $m ) ) {
1593 $prefix = $first_prefix;
1594 $first_prefix = false;
1596 wfProfileOut( __METHOD__
.'-prefixhandling' );
1599 $might_be_img = false;
1601 wfProfileIn( __METHOD__
."-e1" );
1602 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1604 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1605 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1606 # the real problem is with the $e1 regex
1609 # Still some problems for cases where the ] is meant to be outside punctuation,
1610 # and no image is in sight. See bug 2095.
1613 substr( $m[3], 0, 1 ) === ']' &&
1614 strpos($text, '[') !== false
1617 $text .= ']'; # so that replaceExternalLinks($text) works later
1618 $m[3] = substr( $m[3], 1 );
1620 # fix up urlencoded title texts
1621 if( strpos( $m[1], '%' ) !== false ) {
1622 # Should anchors '#' also be rejected?
1623 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1626 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1627 $might_be_img = true;
1629 if ( strpos( $m[1], '%' ) !== false ) {
1630 $m[1] = urldecode($m[1]);
1633 } else { # Invalid form; output directly
1634 $s .= $prefix . '[[' . $line ;
1635 wfProfileOut( __METHOD__
."-e1" );
1638 wfProfileOut( __METHOD__
."-e1" );
1639 wfProfileIn( __METHOD__
."-misc" );
1641 # Don't allow internal links to pages containing
1642 # PROTO: where PROTO is a valid URL protocol; these
1643 # should be external links.
1644 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1645 $s .= $prefix . '[[' . $line ;
1646 wfProfileOut( __METHOD__
."-misc" );
1650 # Make subpage if necessary
1651 if( $useSubpages ) {
1652 $link = $this->maybeDoSubpageLink( $m[1], $text );
1657 $noforce = (substr($m[1], 0, 1) !== ':');
1659 # Strip off leading ':'
1660 $link = substr($link, 1);
1663 wfProfileOut( __METHOD__
."-misc" );
1664 wfProfileIn( __METHOD__
."-title" );
1665 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1667 $s .= $prefix . '[[' . $line;
1668 wfProfileOut( __METHOD__
."-title" );
1672 $ns = $nt->getNamespace();
1673 $iw = $nt->getInterWiki();
1674 wfProfileOut( __METHOD__
."-title" );
1676 if ($might_be_img) { # if this is actually an invalid link
1677 wfProfileIn( __METHOD__
."-might_be_img" );
1678 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1681 #look at the next 'line' to see if we can close it there
1683 $next_line = $a->current();
1684 if ( $next_line === false ||
$next_line === null ) {
1687 $m = explode( ']]', $next_line, 3 );
1688 if ( count( $m ) == 3 ) {
1689 # the first ]] closes the inner link, the second the image
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1694 } elseif ( count( $m ) == 2 ) {
1695 #if there's exactly one ]] that's fine, we'll keep looking
1696 $text .= "[[{$m[0]}]]{$m[1]}";
1698 #if $next_line is invalid too, we need look no further
1699 $text .= '[[' . $next_line;
1704 # we couldn't find the end of this imageLink, so output it raw
1705 #but don't ignore what might be perfectly normal links in the text we've examined
1706 $holders->merge( $this->replaceInternalLinks2( $text ) );
1707 $s .= "{$prefix}[[$link|$text";
1708 # note: no $trail, because without an end, there *is* no trail
1709 wfProfileOut( __METHOD__
."-might_be_img" );
1712 } else { #it's not an image, so output it raw
1713 $s .= "{$prefix}[[$link|$text";
1714 # note: no $trail, because without an end, there *is* no trail
1715 wfProfileOut( __METHOD__
."-might_be_img" );
1718 wfProfileOut( __METHOD__
."-might_be_img" );
1721 $wasblank = ( '' == $text );
1722 if( $wasblank ) $text = $link;
1724 # Link not escaped by : , create the various objects
1728 wfProfileIn( __METHOD__
."-interwiki" );
1729 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1730 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1731 $s = rtrim($s . $prefix);
1732 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1733 wfProfileOut( __METHOD__
."-interwiki" );
1736 wfProfileOut( __METHOD__
."-interwiki" );
1738 if ( $ns == NS_IMAGE
) {
1739 wfProfileIn( __METHOD__
."-image" );
1740 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1741 # recursively parse links inside the image caption
1742 # actually, this will parse them in any other parameters, too,
1743 # but it might be hard to fix that, and it doesn't matter ATM
1744 $text = $this->replaceExternalLinks($text);
1745 $holders->merge( $this->replaceInternalLinks2( $text ) );
1747 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1748 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1750 $this->mOutput
->addImage( $nt->getDBkey() );
1751 wfProfileOut( __METHOD__
."-image" );
1756 if ( $ns == NS_CATEGORY
) {
1757 wfProfileIn( __METHOD__
."-category" );
1758 $s = rtrim($s . "\n"); # bug 87
1761 $sortkey = $this->getDefaultSort();
1765 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1766 $sortkey = str_replace( "\n", '', $sortkey );
1767 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1768 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1771 * Strip the whitespace Category links produce, see bug 87
1772 * @todo We might want to use trim($tmp, "\n") here.
1774 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1776 wfProfileOut( __METHOD__
."-category" );
1781 # Self-link checking
1782 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1783 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1784 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1789 # Special and Media are pseudo-namespaces; no pages actually exist in them
1790 if( $ns == NS_MEDIA
) {
1791 # Give extensions a chance to select the file revision for us
1792 $skip = $time = false;
1793 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1795 $link = $sk->link( $nt );
1797 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1799 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1800 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1801 $this->mOutput
->addImage( $nt->getDBkey() );
1803 } elseif( $ns == NS_SPECIAL
) {
1804 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1805 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1807 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1810 } elseif( $ns == NS_IMAGE
) {
1811 $img = wfFindFile( $nt );
1813 // Force a blue link if the file exists; may be a remote
1814 // upload on the shared repository, and we want to see its
1815 // auto-generated page.
1816 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1817 $this->mOutput
->addLink( $nt );
1821 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1823 wfProfileOut( __METHOD__
);
1828 * Make a link placeholder. The text returned can be later resolved to a real link with
1829 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1830 * parsing of interwiki links, and secondly to allow all existence checks and
1831 * article length checks (for stub links) to be bundled into a single query.
1835 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1836 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1840 * Render a forced-blue link inline; protect against double expansion of
1841 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1842 * Since this little disaster has to split off the trail text to avoid
1843 * breaking URLs in the following text without breaking trails on the
1844 * wiki links, it's been made into a horrible function.
1847 * @param string $text
1848 * @param string $query
1849 * @param string $trail
1850 * @param string $prefix
1851 * @return string HTML-wikitext mix oh yuck
1853 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1854 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1855 $sk = $this->mOptions
->getSkin();
1856 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1857 return $this->armorLinks( $link ) . $trail;
1861 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1862 * going to go through further parsing steps before inline URL expansion.
1864 * Not needed quite as much as it used to be since free links are a bit
1865 * more sensible these days. But bracketed links are still an issue.
1867 * @param string more-or-less HTML
1868 * @return string less-or-more HTML with NOPARSE bits
1870 function armorLinks( $text ) {
1871 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1872 "{$this->mUniqPrefix}NOPARSE$1", $text );
1876 * Return true if subpage links should be expanded on this page.
1879 function areSubpagesAllowed() {
1880 # Some namespaces don't allow subpages
1881 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1885 * Handle link to subpage if necessary
1886 * @param string $target the source of the link
1887 * @param string &$text the link text, modified as necessary
1888 * @return string the full name of the link
1891 function maybeDoSubpageLink($target, &$text) {
1894 # :Foobar -- override special treatment of prefix (images, language links)
1895 # /Foobar -- convert to CurrentPage/Foobar
1896 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1897 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1898 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1900 wfProfileIn( __METHOD__
);
1901 $ret = $target; # default return value is no change
1903 # Some namespaces don't allow subpages,
1904 # so only perform processing if subpages are allowed
1905 if( $this->areSubpagesAllowed() ) {
1906 $hash = strpos( $target, '#' );
1907 if( $hash !== false ) {
1908 $suffix = substr( $target, $hash );
1909 $target = substr( $target, 0, $hash );
1914 $target = trim( $target );
1915 # Look at the first character
1916 if( $target != '' && $target{0} === '/' ) {
1917 # / at end means we don't want the slash to be shown
1919 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1920 if( $trailingSlashes ) {
1921 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1923 $noslash = substr( $target, 1 );
1926 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1927 if( '' === $text ) {
1928 $text = $target . $suffix;
1929 } # this might be changed for ugliness reasons
1931 # check for .. subpage backlinks
1933 $nodotdot = $target;
1934 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1936 $nodotdot = substr( $nodotdot, 3 );
1938 if($dotdotcount > 0) {
1939 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1940 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1941 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1942 # / at the end means don't show full path
1943 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1944 $nodotdot = substr( $nodotdot, 0, -1 );
1945 if( '' === $text ) {
1946 $text = $nodotdot . $suffix;
1949 $nodotdot = trim( $nodotdot );
1950 if( $nodotdot != '' ) {
1951 $ret .= '/' . $nodotdot;
1959 wfProfileOut( __METHOD__
);
1964 * Used by doBlockLevels()
1967 /* private */ function closeParagraph() {
1969 if ( '' != $this->mLastSection
) {
1970 $result = '</' . $this->mLastSection
. ">\n";
1972 $this->mInPre
= false;
1973 $this->mLastSection
= '';
1976 # getCommon() returns the length of the longest common substring
1977 # of both arguments, starting at the beginning of both.
1979 /* private */ function getCommon( $st1, $st2 ) {
1980 $fl = strlen( $st1 );
1981 $shorter = strlen( $st2 );
1982 if ( $fl < $shorter ) { $shorter = $fl; }
1984 for ( $i = 0; $i < $shorter; ++
$i ) {
1985 if ( $st1{$i} != $st2{$i} ) { break; }
1989 # These next three functions open, continue, and close the list
1990 # element appropriate to the prefix character passed into them.
1992 /* private */ function openList( $char ) {
1993 $result = $this->closeParagraph();
1995 if ( '*' === $char ) { $result .= '<ul><li>'; }
1996 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1997 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1998 else if ( ';' === $char ) {
1999 $result .= '<dl><dt>';
2000 $this->mDTopen
= true;
2002 else { $result = '<!-- ERR 1 -->'; }
2007 /* private */ function nextItem( $char ) {
2008 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2009 else if ( ':' === $char ||
';' === $char ) {
2011 if ( $this->mDTopen
) { $close = '</dt>'; }
2012 if ( ';' === $char ) {
2013 $this->mDTopen
= true;
2014 return $close . '<dt>';
2016 $this->mDTopen
= false;
2017 return $close . '<dd>';
2020 return '<!-- ERR 2 -->';
2023 /* private */ function closeList( $char ) {
2024 if ( '*' === $char ) { $text = '</li></ul>'; }
2025 else if ( '#' === $char ) { $text = '</li></ol>'; }
2026 else if ( ':' === $char ) {
2027 if ( $this->mDTopen
) {
2028 $this->mDTopen
= false;
2029 $text = '</dt></dl>';
2031 $text = '</dd></dl>';
2034 else { return '<!-- ERR 3 -->'; }
2040 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2043 * @return string the lists rendered as HTML
2045 function doBlockLevels( $text, $linestart ) {
2046 wfProfileIn( __METHOD__
);
2048 # Parsing through the text line by line. The main thing
2049 # happening here is handling of block-level elements p, pre,
2050 # and making lists from lines starting with * # : etc.
2052 $textLines = StringUtils
::explode( "\n", $text );
2054 $lastPrefix = $output = '';
2055 $this->mDTopen
= $inBlockElem = false;
2057 $paragraphStack = false;
2059 foreach ( $textLines as $oLine ) {
2061 if ( !$linestart ) {
2067 $lastPrefixLength = strlen( $lastPrefix );
2068 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2069 $preOpenMatch = preg_match('/<pre/i', $oLine );
2070 if ( !$this->mInPre
) {
2071 # Multiple prefixes may abut each other for nested lists.
2072 $prefixLength = strspn( $oLine, '*#:;' );
2073 $prefix = substr( $oLine, 0, $prefixLength );
2076 $prefix2 = str_replace( ';', ':', $prefix );
2077 $t = substr( $oLine, $prefixLength );
2078 $this->mInPre
= (bool)$preOpenMatch;
2080 # Don't interpret any other prefixes in preformatted text
2082 $prefix = $prefix2 = '';
2087 if( $prefixLength && $lastPrefix === $prefix2 ) {
2088 # Same as the last item, so no need to deal with nesting or opening stuff
2089 $output .= $this->nextItem( substr( $prefix, -1 ) );
2090 $paragraphStack = false;
2092 if ( substr( $prefix, -1 ) === ';') {
2093 # The one nasty exception: definition lists work like this:
2094 # ; title : definition text
2095 # So we check for : in the remainder text to split up the
2096 # title and definition, without b0rking links.
2098 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2100 $output .= $term . $this->nextItem( ':' );
2103 } elseif( $prefixLength ||
$lastPrefixLength ) {
2104 # Either open or close a level...
2105 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2106 $paragraphStack = false;
2108 while( $commonPrefixLength < $lastPrefixLength ) {
2109 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2110 --$lastPrefixLength;
2112 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2113 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2115 while ( $prefixLength > $commonPrefixLength ) {
2116 $char = substr( $prefix, $commonPrefixLength, 1 );
2117 $output .= $this->openList( $char );
2119 if ( ';' === $char ) {
2120 # FIXME: This is dupe of code above
2121 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2123 $output .= $term . $this->nextItem( ':' );
2126 ++
$commonPrefixLength;
2128 $lastPrefix = $prefix2;
2130 if( 0 == $prefixLength ) {
2131 wfProfileIn( __METHOD__
."-paragraph" );
2132 # No prefix (not in list)--go to paragraph mode
2133 // XXX: use a stack for nestable elements like span, table and div
2134 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2135 $closematch = preg_match(
2136 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2137 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2138 if ( $openmatch or $closematch ) {
2139 $paragraphStack = false;
2140 #Â TODO bug 5718: paragraph closed
2141 $output .= $this->closeParagraph();
2142 if ( $preOpenMatch and !$preCloseMatch ) {
2143 $this->mInPre
= true;
2145 if ( $closematch ) {
2146 $inBlockElem = false;
2148 $inBlockElem = true;
2150 } else if ( !$inBlockElem && !$this->mInPre
) {
2151 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2153 if ($this->mLastSection
!== 'pre') {
2154 $paragraphStack = false;
2155 $output .= $this->closeParagraph().'<pre>';
2156 $this->mLastSection
= 'pre';
2158 $t = substr( $t, 1 );
2161 if ( '' == trim($t) ) {
2162 if ( $paragraphStack ) {
2163 $output .= $paragraphStack.'<br />';
2164 $paragraphStack = false;
2165 $this->mLastSection
= 'p';
2167 if ($this->mLastSection
!== 'p' ) {
2168 $output .= $this->closeParagraph();
2169 $this->mLastSection
= '';
2170 $paragraphStack = '<p>';
2172 $paragraphStack = '</p><p>';
2176 if ( $paragraphStack ) {
2177 $output .= $paragraphStack;
2178 $paragraphStack = false;
2179 $this->mLastSection
= 'p';
2180 } else if ($this->mLastSection
!== 'p') {
2181 $output .= $this->closeParagraph().'<p>';
2182 $this->mLastSection
= 'p';
2187 wfProfileOut( __METHOD__
."-paragraph" );
2189 // somewhere above we forget to get out of pre block (bug 785)
2190 if($preCloseMatch && $this->mInPre
) {
2191 $this->mInPre
= false;
2193 if ($paragraphStack === false) {
2197 while ( $prefixLength ) {
2198 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2201 if ( '' != $this->mLastSection
) {
2202 $output .= '</' . $this->mLastSection
. '>';
2203 $this->mLastSection
= '';
2206 wfProfileOut( __METHOD__
);
2211 * Split up a string on ':', ignoring any occurences inside tags
2212 * to prevent illegal overlapping.
2213 * @param string $str the string to split
2214 * @param string &$before set to everything before the ':'
2215 * @param string &$after set to everything after the ':'
2216 * return string the position of the ':', or false if none found
2218 function findColonNoLinks($str, &$before, &$after) {
2219 wfProfileIn( __METHOD__
);
2221 $pos = strpos( $str, ':' );
2222 if( $pos === false ) {
2224 wfProfileOut( __METHOD__
);
2228 $lt = strpos( $str, '<' );
2229 if( $lt === false ||
$lt > $pos ) {
2230 // Easy; no tag nesting to worry about
2231 $before = substr( $str, 0, $pos );
2232 $after = substr( $str, $pos+
1 );
2233 wfProfileOut( __METHOD__
);
2237 // Ugly state machine to walk through avoiding tags.
2238 $state = self
::COLON_STATE_TEXT
;
2240 $len = strlen( $str );
2241 for( $i = 0; $i < $len; $i++
) {
2245 // (Using the number is a performance hack for common cases)
2246 case 0: // self::COLON_STATE_TEXT:
2249 // Could be either a <start> tag or an </end> tag
2250 $state = self
::COLON_STATE_TAGSTART
;
2255 $before = substr( $str, 0, $i );
2256 $after = substr( $str, $i +
1 );
2257 wfProfileOut( __METHOD__
);
2260 // Embedded in a tag; don't break it.
2263 // Skip ahead looking for something interesting
2264 $colon = strpos( $str, ':', $i );
2265 if( $colon === false ) {
2266 // Nothing else interesting
2267 wfProfileOut( __METHOD__
);
2270 $lt = strpos( $str, '<', $i );
2271 if( $stack === 0 ) {
2272 if( $lt === false ||
$colon < $lt ) {
2274 $before = substr( $str, 0, $colon );
2275 $after = substr( $str, $colon +
1 );
2276 wfProfileOut( __METHOD__
);
2280 if( $lt === false ) {
2281 // Nothing else interesting to find; abort!
2282 // We're nested, but there's no close tags left. Abort!
2285 // Skip ahead to next tag start
2287 $state = self
::COLON_STATE_TAGSTART
;
2290 case 1: // self::COLON_STATE_TAG:
2295 $state = self
::COLON_STATE_TEXT
;
2298 // Slash may be followed by >?
2299 $state = self
::COLON_STATE_TAGSLASH
;
2305 case 2: // self::COLON_STATE_TAGSTART:
2308 $state = self
::COLON_STATE_CLOSETAG
;
2311 $state = self
::COLON_STATE_COMMENT
;
2314 // Illegal early close? This shouldn't happen D:
2315 $state = self
::COLON_STATE_TEXT
;
2318 $state = self
::COLON_STATE_TAG
;
2321 case 3: // self::COLON_STATE_CLOSETAG:
2326 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2327 wfProfileOut( __METHOD__
);
2330 $state = self
::COLON_STATE_TEXT
;
2333 case self
::COLON_STATE_TAGSLASH
:
2335 // Yes, a self-closed tag <blah/>
2336 $state = self
::COLON_STATE_TEXT
;
2338 // Probably we're jumping the gun, and this is an attribute
2339 $state = self
::COLON_STATE_TAG
;
2342 case 5: // self::COLON_STATE_COMMENT:
2344 $state = self
::COLON_STATE_COMMENTDASH
;
2347 case self
::COLON_STATE_COMMENTDASH
:
2349 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2351 $state = self
::COLON_STATE_COMMENT
;
2354 case self
::COLON_STATE_COMMENTDASHDASH
:
2356 $state = self
::COLON_STATE_TEXT
;
2358 $state = self
::COLON_STATE_COMMENT
;
2362 throw new MWException( "State machine error in " . __METHOD__
);
2366 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2369 wfProfileOut( __METHOD__
);
2374 * Return value of a magic variable (like PAGENAME)
2378 function getVariableValue( $index ) {
2379 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2382 * Some of these require message or data lookups and can be
2383 * expensive to check many times.
2385 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2386 if ( isset( $this->mVarCache
[$index] ) ) {
2387 return $this->mVarCache
[$index];
2391 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2392 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2395 global $wgLocaltimezone;
2396 if ( isset( $wgLocaltimezone ) ) {
2397 $oldtz = getenv( 'TZ' );
2398 putenv( 'TZ='.$wgLocaltimezone );
2401 wfSuppressWarnings(); // E_STRICT system time bitching
2402 $localTimestamp = date( 'YmdHis', $ts );
2403 $localMonth = date( 'm', $ts );
2404 $localMonthName = date( 'n', $ts );
2405 $localDay = date( 'j', $ts );
2406 $localDay2 = date( 'd', $ts );
2407 $localDayOfWeek = date( 'w', $ts );
2408 $localWeek = date( 'W', $ts );
2409 $localYear = date( 'Y', $ts );
2410 $localHour = date( 'H', $ts );
2411 if ( isset( $wgLocaltimezone ) ) {
2412 putenv( 'TZ='.$oldtz );
2414 wfRestoreWarnings();
2417 case 'currentmonth':
2418 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2419 case 'currentmonthname':
2420 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2421 case 'currentmonthnamegen':
2422 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2423 case 'currentmonthabbrev':
2424 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2426 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2428 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2430 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2431 case 'localmonthname':
2432 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2433 case 'localmonthnamegen':
2434 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2435 case 'localmonthabbrev':
2436 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2438 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2440 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2442 return wfEscapeWikiText( $this->mTitle
->getText() );
2444 return $this->mTitle
->getPartialURL();
2445 case 'fullpagename':
2446 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2447 case 'fullpagenamee':
2448 return $this->mTitle
->getPrefixedURL();
2450 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2451 case 'subpagenamee':
2452 return $this->mTitle
->getSubpageUrlForm();
2453 case 'basepagename':
2454 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2455 case 'basepagenamee':
2456 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2457 case 'talkpagename':
2458 if( $this->mTitle
->canTalk() ) {
2459 $talkPage = $this->mTitle
->getTalkPage();
2460 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2464 case 'talkpagenamee':
2465 if( $this->mTitle
->canTalk() ) {
2466 $talkPage = $this->mTitle
->getTalkPage();
2467 return $talkPage->getPrefixedUrl();
2471 case 'subjectpagename':
2472 $subjPage = $this->mTitle
->getSubjectPage();
2473 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2474 case 'subjectpagenamee':
2475 $subjPage = $this->mTitle
->getSubjectPage();
2476 return $subjPage->getPrefixedUrl();
2478 // Let the edit saving system know we should parse the page
2479 // *after* a revision ID has been assigned.
2480 $this->mOutput
->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2482 return $this->mRevisionId
;
2484 // Let the edit saving system know we should parse the page
2485 // *after* a revision ID has been assigned. This is for null edits.
2486 $this->mOutput
->setFlag( 'vary-revision' );
2487 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2488 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2489 case 'revisionday2':
2490 // Let the edit saving system know we should parse the page
2491 // *after* a revision ID has been assigned. This is for null edits.
2492 $this->mOutput
->setFlag( 'vary-revision' );
2493 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2494 return substr( $this->getRevisionTimestamp(), 6, 2 );
2495 case 'revisionmonth':
2496 // Let the edit saving system know we should parse the page
2497 // *after* a revision ID has been assigned. This is for null edits.
2498 $this->mOutput
->setFlag( 'vary-revision' );
2499 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2500 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2501 case 'revisionyear':
2502 // Let the edit saving system know we should parse the page
2503 // *after* a revision ID has been assigned. This is for null edits.
2504 $this->mOutput
->setFlag( 'vary-revision' );
2505 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2506 return substr( $this->getRevisionTimestamp(), 0, 4 );
2507 case 'revisiontimestamp':
2508 // Let the edit saving system know we should parse the page
2509 // *after* a revision ID has been assigned. This is for null edits.
2510 $this->mOutput
->setFlag( 'vary-revision' );
2511 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2512 return $this->getRevisionTimestamp();
2514 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2516 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2518 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2520 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2521 case 'subjectspace':
2522 return $this->mTitle
->getSubjectNsText();
2523 case 'subjectspacee':
2524 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2525 case 'currentdayname':
2526 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2530 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2534 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2535 // int to remove the padding
2536 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2538 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2539 case 'localdayname':
2540 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2542 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2544 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2546 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2548 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2549 // int to remove the padding
2550 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2552 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2553 case 'numberofarticles':
2554 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2555 case 'numberoffiles':
2556 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2557 case 'numberofusers':
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2559 case 'numberofpages':
2560 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2561 case 'numberofadmins':
2562 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2563 case 'numberofedits':
2564 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2565 case 'currenttimestamp':
2566 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2567 case 'localtimestamp':
2568 return $this->mVarCache
[$index] = $localTimestamp;
2569 case 'currentversion':
2570 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2576 return $wgServerName;
2578 return $wgScriptPath;
2579 case 'directionmark':
2580 return $wgContLang->getDirMark();
2581 case 'contentlanguage':
2582 global $wgContLanguageCode;
2583 return $wgContLanguageCode;
2586 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2594 * initialise the magic variables (like CURRENTMONTHNAME)
2598 function initialiseVariables() {
2599 wfProfileIn( __METHOD__
);
2600 $variableIDs = MagicWord
::getVariableIDs();
2602 $this->mVariables
= new MagicWordArray( $variableIDs );
2603 wfProfileOut( __METHOD__
);
2607 * Preprocess some wikitext and return the document tree.
2608 * This is the ghost of replace_variables().
2610 * @param string $text The text to parse
2611 * @param integer flags Bitwise combination of:
2612 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2613 * included. Default is to assume a direct page view.
2615 * The generated DOM tree must depend only on the input text and the flags.
2616 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2618 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2619 * change in the DOM tree for a given text, must be passed through the section identifier
2620 * in the section edit link and thus back to extractSections().
2622 * The output of this function is currently only cached in process memory, but a persistent
2623 * cache may be implemented at a later date which takes further advantage of these strict
2624 * dependency requirements.
2628 function preprocessToDom ( $text, $flags = 0 ) {
2629 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2634 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2636 public static function splitWhitespace( $s ) {
2637 $ltrimmed = ltrim( $s );
2638 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2639 $trimmed = rtrim( $ltrimmed );
2640 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2642 $w2 = substr( $ltrimmed, -$diff );
2646 return array( $w1, $trimmed, $w2 );
2650 * Replace magic variables, templates, and template arguments
2651 * with the appropriate text. Templates are substituted recursively,
2652 * taking care to avoid infinite loops.
2654 * Note that the substitution depends on value of $mOutputType:
2655 * self::OT_WIKI: only {{subst:}} templates
2656 * self::OT_PREPROCESS: templates but not extension tags
2657 * self::OT_HTML: all templates and extension tags
2659 * @param string $tex The text to transform
2660 * @param PPFrame $frame Object describing the arguments passed to the template.
2661 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2662 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2663 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2666 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2667 # Prevent too big inclusions
2668 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2672 wfProfileIn( __METHOD__
);
2674 if ( $frame === false ) {
2675 $frame = $this->getPreprocessor()->newFrame();
2676 } elseif ( !( $frame instanceof PPFrame
) ) {
2677 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2678 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2681 $dom = $this->preprocessToDom( $text );
2682 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2683 $text = $frame->expand( $dom, $flags );
2685 wfProfileOut( __METHOD__
);
2689 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2690 static function createAssocArgs( $args ) {
2691 $assocArgs = array();
2693 foreach( $args as $arg ) {
2694 $eqpos = strpos( $arg, '=' );
2695 if ( $eqpos === false ) {
2696 $assocArgs[$index++
] = $arg;
2698 $name = trim( substr( $arg, 0, $eqpos ) );
2699 $value = trim( substr( $arg, $eqpos+
1 ) );
2700 if ( $value === false ) {
2703 if ( $name !== false ) {
2704 $assocArgs[$name] = $value;
2713 * Warn the user when a parser limitation is reached
2714 * Will warn at most once the user per limitation type
2716 * @param string $limitationType, should be one of:
2717 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2718 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2719 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2720 * @params int $current, $max When an explicit limit has been
2721 * exceeded, provide the values (optional)
2723 function limitationWarn( $limitationType, $current=null, $max=null) {
2724 $msgName = $limitationType . '-warning';
2725 //does no harm if $current and $max are present but are unnecessary for the message
2726 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2727 $this->mOutput
->addWarning( $warning );
2728 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2730 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2735 * Return the text of a template, after recursively
2736 * replacing any variables or templates within the template.
2738 * @param array $piece The parts of the template
2739 * $piece['title']: the title, i.e. the part before the |
2740 * $piece['parts']: the parameter array
2741 * $piece['lineStart']: whether the brace was at the start of a line
2742 * @param PPFrame The current frame, contains template arguments
2743 * @return string the text of the template
2746 function braceSubstitution( $piece, $frame ) {
2747 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2748 wfProfileIn( __METHOD__
);
2749 wfProfileIn( __METHOD__
.'-setup' );
2752 $found = false; # $text has been filled
2753 $nowiki = false; # wiki markup in $text should be escaped
2754 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2755 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2756 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2757 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2759 # Title object, where $text came from
2762 # $part1 is the bit before the first |, and must contain only title characters.
2763 # Various prefixes will be stripped from it later.
2764 $titleWithSpaces = $frame->expand( $piece['title'] );
2765 $part1 = trim( $titleWithSpaces );
2768 # Original title text preserved for various purposes
2769 $originalTitle = $part1;
2771 # $args is a list of argument nodes, starting from index 0, not including $part1
2772 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2773 wfProfileOut( __METHOD__
.'-setup' );
2776 wfProfileIn( __METHOD__
.'-modifiers' );
2778 $mwSubst = MagicWord
::get( 'subst' );
2779 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2780 # One of two possibilities is true:
2781 # 1) Found SUBST but not in the PST phase
2782 # 2) Didn't find SUBST and in the PST phase
2783 # In either case, return without further processing
2784 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2791 if ( !$found && $args->getLength() == 0 ) {
2792 $id = $this->mVariables
->matchStartToEnd( $part1 );
2793 if ( $id !== false ) {
2794 $text = $this->getVariableValue( $id );
2795 if (MagicWord
::getCacheTTL($id)>-1)
2796 $this->mOutput
->mContainsOldMagic
= true;
2801 # MSG, MSGNW and RAW
2804 $mwMsgnw = MagicWord
::get( 'msgnw' );
2805 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2808 # Remove obsolete MSG:
2809 $mwMsg = MagicWord
::get( 'msg' );
2810 $mwMsg->matchStartAndRemove( $part1 );
2814 $mwRaw = MagicWord
::get( 'raw' );
2815 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2816 $forceRawInterwiki = true;
2819 wfProfileOut( __METHOD__
.'-modifiers' );
2823 wfProfileIn( __METHOD__
. '-pfunc' );
2825 $colonPos = strpos( $part1, ':' );
2826 if ( $colonPos !== false ) {
2827 # Case sensitive functions
2828 $function = substr( $part1, 0, $colonPos );
2829 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2830 $function = $this->mFunctionSynonyms
[1][$function];
2832 # Case insensitive functions
2833 $function = strtolower( $function );
2834 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2835 $function = $this->mFunctionSynonyms
[0][$function];
2841 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2842 $initialArgs = array( &$this );
2843 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2844 if ( $flags & SFH_OBJECT_ARGS
) {
2845 # Add a frame parameter, and pass the arguments as an array
2846 $allArgs = $initialArgs;
2847 $allArgs[] = $frame;
2848 for ( $i = 0; $i < $args->getLength(); $i++
) {
2849 $funcArgs[] = $args->item( $i );
2851 $allArgs[] = $funcArgs;
2853 # Convert arguments to plain text
2854 for ( $i = 0; $i < $args->getLength(); $i++
) {
2855 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2857 $allArgs = array_merge( $initialArgs, $funcArgs );
2860 # Workaround for PHP bug 35229 and similar
2861 if ( !is_callable( $callback ) ) {
2862 throw new MWException( "Tag hook for $name is not callable\n" );
2864 $result = call_user_func_array( $callback, $allArgs );
2867 $preprocessFlags = 0;
2869 if ( is_array( $result ) ) {
2870 if ( isset( $result[0] ) ) {
2872 unset( $result[0] );
2875 // Extract flags into the local scope
2876 // This allows callers to set flags such as nowiki, found, etc.
2882 $text = $this->preprocessToDom( $text, $preprocessFlags );
2887 wfProfileOut( __METHOD__
. '-pfunc' );
2890 # Finish mangling title and then check for loops.
2891 # Set $title to a Title object and $titleText to the PDBK
2894 # Split the title into page and subpage
2896 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2897 if ($subpage !== '') {
2898 $ns = $this->mTitle
->getNamespace();
2900 $title = Title
::newFromText( $part1, $ns );
2902 $titleText = $title->getPrefixedText();
2903 # Check for language variants if the template is not found
2904 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2905 $wgContLang->findVariantLink( $part1, $title, true );
2907 # Do infinite loop check
2908 if ( !$frame->loopCheck( $title ) ) {
2910 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2911 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2913 # Do recursion depth check
2914 $limit = $this->mOptions
->getMaxTemplateDepth();
2915 if ( $frame->depth
>= $limit ) {
2917 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2922 # Load from database
2923 if ( !$found && $title ) {
2924 wfProfileIn( __METHOD__
. '-loadtpl' );
2925 if ( !$title->isExternal() ) {
2926 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2927 $text = SpecialPage
::capturePath( $title );
2928 if ( is_string( $text ) ) {
2931 $this->disableCache();
2933 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2934 $found = false; //access denied
2935 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2937 list( $text, $title ) = $this->getTemplateDom( $title );
2938 if ( $text !== false ) {
2944 # If the title is valid but undisplayable, make a link to it
2945 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2946 $text = "[[:$titleText]]";
2949 } elseif ( $title->isTrans() ) {
2950 // Interwiki transclusion
2951 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2952 $text = $this->interwikiTransclude( $title, 'render' );
2955 $text = $this->interwikiTransclude( $title, 'raw' );
2956 // Preprocess it like a template
2957 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2962 wfProfileOut( __METHOD__
. '-loadtpl' );
2965 # If we haven't found text to substitute by now, we're done
2966 # Recover the source wikitext and return it
2968 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2969 wfProfileOut( __METHOD__
);
2970 return array( 'object' => $text );
2973 # Expand DOM-style return values in a child frame
2974 if ( $isChildObj ) {
2975 # Clean up argument array
2976 $newFrame = $frame->newChild( $args, $title );
2979 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2980 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2981 # Expansion is eligible for the empty-frame cache
2982 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2983 $text = $this->mTplExpandCache
[$titleText];
2985 $text = $newFrame->expand( $text );
2986 $this->mTplExpandCache
[$titleText] = $text;
2989 # Uncached expansion
2990 $text = $newFrame->expand( $text );
2993 if ( $isLocalObj && $nowiki ) {
2994 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2995 $isLocalObj = false;
2998 # Replace raw HTML by a placeholder
2999 # Add a blank line preceding, to prevent it from mucking up
3000 # immediately preceding headings
3002 $text = "\n\n" . $this->insertStripItem( $text );
3004 # Escape nowiki-style return values
3005 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3006 $text = wfEscapeWikiText( $text );
3008 # Bug 529: if the template begins with a table or block-level
3009 # element, it should be treated as beginning a new line.
3010 # This behaviour is somewhat controversial.
3011 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3012 $text = "\n" . $text;
3015 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3016 # Error, oversize inclusion
3017 $text = "[[$originalTitle]]" .
3018 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3019 $this->limitationWarn( 'post-expand-template-inclusion' );
3022 if ( $isLocalObj ) {
3023 $ret = array( 'object' => $text );
3025 $ret = array( 'text' => $text );
3028 wfProfileOut( __METHOD__
);
3033 * Get the semi-parsed DOM representation of a template with a given title,
3034 * and its redirect destination title. Cached.
3036 function getTemplateDom( $title ) {
3037 $cacheTitle = $title;
3038 $titleText = $title->getPrefixedDBkey();
3040 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3041 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3042 $title = Title
::makeTitle( $ns, $dbk );
3043 $titleText = $title->getPrefixedDBkey();
3045 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3046 return array( $this->mTplDomCache
[$titleText], $title );
3049 // Cache miss, go to the database
3050 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3052 if ( $text === false ) {
3053 $this->mTplDomCache
[$titleText] = false;
3054 return array( false, $title );
3057 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3058 $this->mTplDomCache
[ $titleText ] = $dom;
3060 if (! $title->equals($cacheTitle)) {
3061 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3062 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3065 return array( $dom, $title );
3069 * Fetch the unparsed text of a template and register a reference to it.
3071 function fetchTemplateAndTitle( $title ) {
3072 $templateCb = $this->mOptions
->getTemplateCallback();
3073 $stuff = call_user_func( $templateCb, $title, $this );
3074 $text = $stuff['text'];
3075 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3076 if ( isset( $stuff['deps'] ) ) {
3077 foreach ( $stuff['deps'] as $dep ) {
3078 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3081 return array($text,$finalTitle);
3084 function fetchTemplate( $title ) {
3085 $rv = $this->fetchTemplateAndTitle($title);
3090 * Static function to get a template
3091 * Can be overridden via ParserOptions::setTemplateCallback().
3093 static function statelessFetchTemplate( $title, $parser=false ) {
3094 $text = $skip = false;
3095 $finalTitle = $title;
3098 // Loop to fetch the article, with up to 1 redirect
3099 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3100 # Give extensions a chance to select the revision instead
3101 $id = false; // Assume current
3102 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3108 'page_id' => $title->getArticleID(),
3112 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3113 $rev_id = $rev ?
$rev->getId() : 0;
3114 // If there is no current revision, there is no page
3115 if( $id === false && !$rev ) {
3116 $linkCache = LinkCache
::singleton();
3117 $linkCache->addBadLinkObj( $title );
3122 'page_id' => $title->getArticleID(),
3123 'rev_id' => $rev_id );
3126 $text = $rev->getText();
3127 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3129 $message = $wgLang->lcfirst( $title->getText() );
3130 $text = wfMsgForContentNoTrans( $message );
3131 if( wfEmptyMsg( $message, $text ) ) {
3138 if ( $text === false ) {
3142 $finalTitle = $title;
3143 $title = Title
::newFromRedirect( $text );
3147 'finalTitle' => $finalTitle,
3152 * Transclude an interwiki link.
3154 function interwikiTransclude( $title, $action ) {
3155 global $wgEnableScaryTranscluding;
3157 if (!$wgEnableScaryTranscluding)
3158 return wfMsg('scarytranscludedisabled');
3160 $url = $title->getFullUrl( "action=$action" );
3162 if (strlen($url) > 255)
3163 return wfMsg('scarytranscludetoolong');
3164 return "<div class=\"mw-iw-transclusion\">\n" . $this->fetchScaryTemplateMaybeFromCache($url) . "</div>\n";
3167 function fetchScaryTemplateMaybeFromCache($url) {
3168 global $wgTranscludeCacheExpiry;
3169 $dbr = wfGetDB(DB_SLAVE
);
3170 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3171 array('tc_url' => $url));
3173 $time = $obj->tc_time
;
3174 $text = $obj->tc_contents
;
3175 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3180 $text = Http
::get($url);
3182 return wfMsg('scarytranscludefailed', $url);
3184 $dbw = wfGetDB(DB_MASTER
);
3185 $dbw->replace('transcache', array('tc_url'), array(
3187 'tc_time' => time(),
3188 'tc_contents' => $text));
3194 * Triple brace replacement -- used for template arguments
3197 function argSubstitution( $piece, $frame ) {
3198 wfProfileIn( __METHOD__
);
3201 $parts = $piece['parts'];
3202 $nameWithSpaces = $frame->expand( $piece['title'] );
3203 $argName = trim( $nameWithSpaces );
3205 $text = $frame->getArgument( $argName );
3206 if ( $text === false && $parts->getLength() > 0
3210 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3213 # No match in frame, use the supplied default
3214 $object = $parts->item( 0 )->getChildren();
3216 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3217 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3218 $this->limitationWarn( 'post-expand-template-argument' );
3221 if ( $text === false && $object === false ) {
3223 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3225 if ( $error !== false ) {
3228 if ( $object !== false ) {
3229 $ret = array( 'object' => $object );
3231 $ret = array( 'text' => $text );
3234 wfProfileOut( __METHOD__
);
3239 * Return the text to be used for a given extension tag.
3240 * This is the ghost of strip().
3242 * @param array $params Associative array of parameters:
3243 * name PPNode for the tag name
3244 * attr PPNode for unparsed text where tag attributes are thought to be
3245 * attributes Optional associative array of parsed attributes
3246 * inner Contents of extension element
3247 * noClose Original text did not have a close tag
3248 * @param PPFrame $frame
3250 function extensionSubstitution( $params, $frame ) {
3251 global $wgRawHtml, $wgContLang;
3253 $name = $frame->expand( $params['name'] );
3254 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3255 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3257 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3259 if ( $this->ot
['html'] ) {
3260 $name = strtolower( $name );
3262 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3263 if ( isset( $params['attributes'] ) ) {
3264 $attributes = $attributes +
$params['attributes'];
3272 throw new MWException( '<html> extension tag encountered unexpectedly' );
3275 $output = Xml
::escapeTagsOnly( $content );
3278 $output = $wgContLang->armourMath(
3279 MathRenderer
::renderMath( $content, $attributes ) );
3282 $output = $this->renderImageGallery( $content, $attributes );
3285 if( isset( $this->mTagHooks
[$name] ) ) {
3286 # Workaround for PHP bug 35229 and similar
3287 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3288 throw new MWException( "Tag hook for $name is not callable\n" );
3290 $output = call_user_func_array( $this->mTagHooks
[$name],
3291 array( $content, $attributes, $this ) );
3293 $output = '<span class="error">Invalid tag extension name: ' .
3294 htmlspecialchars( $name ) . '</span>';
3298 if ( is_null( $attrText ) ) {
3301 if ( isset( $params['attributes'] ) ) {
3302 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3303 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3304 htmlspecialchars( $attrValue ) . '"';
3307 if ( $content === null ) {
3308 $output = "<$name$attrText/>";
3310 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3311 $output = "<$name$attrText>$content$close";
3315 if ( $name === 'html' ||
$name === 'nowiki' ) {
3316 $this->mStripState
->nowiki
->setPair( $marker, $output );
3318 $this->mStripState
->general
->setPair( $marker, $output );
3324 * Increment an include size counter
3326 * @param string $type The type of expansion
3327 * @param integer $size The size of the text
3328 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3330 function incrementIncludeSize( $type, $size ) {
3331 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3334 $this->mIncludeSizes
[$type] +
= $size;
3340 * Increment the expensive function count
3342 * @return boolean False if the limit has been exceeded
3344 function incrementExpensiveFunctionCount() {
3345 global $wgExpensiveParserFunctionLimit;
3346 $this->mExpensiveFunctionCount++
;
3347 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3354 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3355 * Fills $this->mDoubleUnderscores, returns the modified text
3357 function doDoubleUnderscore( $text ) {
3358 // The position of __TOC__ needs to be recorded
3359 $mw = MagicWord
::get( 'toc' );
3360 if( $mw->match( $text ) ) {
3361 $this->mShowToc
= true;
3362 $this->mForceTocPosition
= true;
3364 // Set a placeholder. At the end we'll fill it in with the TOC.
3365 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3367 // Only keep the first one.
3368 $text = $mw->replace( '', $text );
3371 // Now match and remove the rest of them
3372 $mwa = MagicWord
::getDoubleUnderscoreArray();
3373 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3375 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3376 $this->mOutput
->mNoGallery
= true;
3378 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3379 $this->mShowToc
= false;
3381 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3382 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3384 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3385 if ( $containerCategory ) {
3386 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3388 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3391 # (bug 8068) Allow control over whether robots index a page.
3393 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3394 # is not desirable, the last one on the page should win.
3395 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3396 $this->mOutput
->setIndexPolicy( 'noindex' );
3397 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3398 $this->mOutput
->setIndexPolicy( 'index' );
3405 * This function accomplishes several tasks:
3406 * 1) Auto-number headings if that option is enabled
3407 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3408 * 3) Add a Table of contents on the top for users who have enabled the option
3409 * 4) Auto-anchor headings
3411 * It loops through all headlines, collects the necessary data, then splits up the
3412 * string and re-inserts the newly formatted headlines.
3414 * @param string $text
3415 * @param boolean $isMain
3418 function formatHeadings( $text, $isMain=true ) {
3419 global $wgMaxTocLevel, $wgContLang;
3421 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3422 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3425 $showEditLink = $this->mOptions
->getEditSection();
3428 # Inhibit editsection links if requested in the page
3429 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3433 # Get all headlines for numbering them and adding funky stuff like [edit]
3434 # links - this is for later, but we need the number of headlines right now
3436 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3438 # if there are fewer than 4 headlines in the article, do not show TOC
3439 # unless it's been explicitly enabled.
3440 $enoughToc = $this->mShowToc
&&
3441 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3443 # Allow user to stipulate that a page should have a "new section"
3444 # link added via __NEWSECTIONLINK__
3445 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3446 $this->mOutput
->setNewSection( true );
3449 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3450 # override above conditions and always show TOC above first header
3451 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3452 $this->mShowToc
= true;
3456 # We need this to perform operations on the HTML
3457 $sk = $this->mOptions
->getSkin();
3463 # Ugh .. the TOC should have neat indentation levels which can be
3464 # passed to the skin functions. These are determined here
3468 $sublevelCount = array();
3469 $levelCount = array();
3475 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3476 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3479 foreach( $matches[3] as $headline ) {
3480 $isTemplate = false;
3482 $sectionIndex = false;
3484 $markerMatches = array();
3485 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3486 $serial = $markerMatches[1];
3487 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3488 $isTemplate = ($titleText != $baseTitleText);
3489 $headline = preg_replace("/^$markerRegex/", "", $headline);
3493 $prevlevel = $level;
3494 $prevtoclevel = $toclevel;
3496 $level = $matches[1][$headlineCount];
3498 if( $doNumberHeadings ||
$enoughToc ) {
3500 if ( $level > $prevlevel ) {
3501 # Increase TOC level
3503 $sublevelCount[$toclevel] = 0;
3504 if( $toclevel<$wgMaxTocLevel ) {
3505 $prevtoclevel = $toclevel;
3506 $toc .= $sk->tocIndent();
3510 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3511 # Decrease TOC level, find level to jump to
3513 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3514 # Can only go down to level 1
3517 for ($i = $toclevel; $i > 0; $i--) {
3518 if ( $levelCount[$i] == $level ) {
3519 # Found last matching level
3523 elseif ( $levelCount[$i] < $level ) {
3524 # Found first matching level below current level
3530 if( $toclevel<$wgMaxTocLevel ) {
3531 if($prevtoclevel < $wgMaxTocLevel) {
3532 # Unindent only if the previous toc level was shown :p
3533 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3534 $prevtoclevel = $toclevel;
3536 $toc .= $sk->tocLineEnd();
3541 # No change in level, end TOC line
3542 if( $toclevel<$wgMaxTocLevel ) {
3543 $toc .= $sk->tocLineEnd();
3547 $levelCount[$toclevel] = $level;
3549 # count number of headlines for each level
3550 @$sublevelCount[$toclevel]++
;
3552 for( $i = 1; $i <= $toclevel; $i++
) {
3553 if( !empty( $sublevelCount[$i] ) ) {
3557 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3563 # The safe header is a version of the header text safe to use for links
3564 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3565 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3567 # Remove link placeholders by the link text.
3568 # <!--LINK number-->
3570 # link text with suffix
3571 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3573 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3574 $tocline = preg_replace(
3575 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3579 $tocline = trim( $tocline );
3581 # For the anchor, strip out HTML-y stuff period
3582 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3583 $safeHeadline = trim( $safeHeadline );
3585 # Save headline for section edit hint before it's escaped
3586 $headlineHint = $safeHeadline;
3587 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3588 # HTML names must be case-insensitively unique (bug 10721)
3589 $arrayKey = strtolower( $safeHeadline );
3591 # count how many in assoc. array so we can track dupes in anchors
3592 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3593 $refcount[$headlineCount] = $refers[$arrayKey];
3595 # Don't number the heading if it is the only one (looks silly)
3596 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3597 # the two are different if the line contains a link
3598 $headline=$numbering . ' ' . $headline;
3601 # Create the anchor for linking from the TOC to the section
3602 $anchor = $safeHeadline;
3603 if($refcount[$headlineCount] > 1 ) {
3604 $anchor .= '_' . $refcount[$headlineCount];
3606 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3607 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3608 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3610 # give headline the correct <h#> tag
3611 if( $showEditLink && $sectionIndex !== false ) {
3613 # Put a T flag in the section identifier, to indicate to extractSections()
3614 # that sections inside <includeonly> should be counted.
3615 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3617 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3622 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3627 $this->mOutput
->setSections( $tocraw );
3629 # Never ever show TOC if no headers
3630 if( $numVisible < 1 ) {
3635 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3636 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3638 $toc = $sk->tocList( $toc );
3641 # split up and insert constructed headlines
3643 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3646 foreach( $blocks as $block ) {
3647 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3648 # This is the [edit] link that appears for the top block of text when
3649 # section editing is enabled
3651 # Disabled because it broke block formatting
3652 # For example, a bullet point in the top line
3653 # $full .= $sk->editSectionLink(0);
3656 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3657 # Top anchor now in skin
3661 if( !empty( $head[$i] ) ) {
3666 if( $this->mForceTocPosition
) {
3667 return str_replace( '<!--MWTOC-->', $toc, $full );
3674 * Transform wiki markup when saving a page by doing \r\n -> \n
3675 * conversion, substitting signatures, {{subst:}} templates, etc.
3677 * @param string $text the text to transform
3678 * @param Title &$title the Title object for the current article
3679 * @param User &$user the User object describing the current user
3680 * @param ParserOptions $options parsing options
3681 * @param bool $clearState whether to clear the parser state first
3682 * @return string the altered wiki markup
3685 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3686 $this->mOptions
= $options;
3687 $this->setTitle( $title );
3688 $this->setOutputType( self
::OT_WIKI
);
3690 if ( $clearState ) {
3691 $this->clearState();
3697 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3698 $text = $this->pstPass2( $text, $user );
3699 $text = $this->mStripState
->unstripBoth( $text );
3704 * Pre-save transform helper function
3707 function pstPass2( $text, $user ) {
3708 global $wgContLang, $wgLocaltimezone;
3710 /* Note: This is the timestamp saved as hardcoded wikitext to
3711 * the database, we use $wgContLang here in order to give
3712 * everyone the same signature and use the default one rather
3713 * than the one selected in each user's preferences.
3715 * (see also bug 12815)
3717 $ts = $this->mOptions
->getTimestamp();
3718 $tz = wfMsgForContent( 'timezone-utc' );
3719 if ( isset( $wgLocaltimezone ) ) {
3720 $unixts = wfTimestamp( TS_UNIX
, $ts );
3721 $oldtz = getenv( 'TZ' );
3722 putenv( 'TZ='.$wgLocaltimezone );
3723 $ts = date( 'YmdHis', $unixts );
3724 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3725 putenv( 'TZ='.$oldtz );
3728 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3730 # Variable replacement
3731 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3732 $text = $this->replaceVariables( $text );
3735 $sigText = $this->getUserSig( $user );
3736 $text = strtr( $text, array(
3738 '~~~~' => "$sigText $d",
3742 # Context links: [[|name]] and [[name (context)|]]
3744 global $wgLegalTitleChars;
3745 $tc = "[$wgLegalTitleChars]";
3746 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3748 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3749 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3750 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3751 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3753 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3754 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3755 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3756 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3758 $t = $this->mTitle
->getText();
3760 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3761 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3762 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3763 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3765 # if there's no context, don't bother duplicating the title
3766 $text = preg_replace( $p2, '[[\\1]]', $text );
3769 # Trim trailing whitespace
3770 $text = rtrim( $text );
3776 * Fetch the user's signature text, if any, and normalize to
3777 * validated, ready-to-insert wikitext.
3783 function getUserSig( &$user ) {
3784 global $wgMaxSigChars;
3786 $username = $user->getName();
3787 $nickname = $user->getOption( 'nickname' );
3788 $nickname = $nickname === '' ?
$username : $nickname;
3790 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3791 $nickname = $username;
3792 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3793 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3794 # Sig. might contain markup; validate this
3795 if( $this->validateSig( $nickname ) !== false ) {
3796 # Validated; clean up (if needed) and return it
3797 return $this->cleanSig( $nickname, true );
3799 # Failed to validate; fall back to the default
3800 $nickname = $username;
3801 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3805 // Make sure nickname doesnt get a sig in a sig
3806 $nickname = $this->cleanSigInSig( $nickname );
3808 # If we're still here, make it a link to the user page
3809 $userText = wfEscapeWikiText( $username );
3810 $nickText = wfEscapeWikiText( $nickname );
3811 if ( $user->isAnon() ) {
3812 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3814 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3819 * Check that the user's signature contains no bad XML
3821 * @param string $text
3822 * @return mixed An expanded string, or false if invalid.
3824 function validateSig( $text ) {
3825 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3829 * Clean up signature text
3831 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3832 * 2) Substitute all transclusions
3834 * @param string $text
3835 * @param $parsing Whether we're cleaning (preferences save) or parsing
3836 * @return string Signature text
3838 function cleanSig( $text, $parsing = false ) {
3841 $this->clearState();
3842 $this->setTitle( $wgTitle );
3843 $this->mOptions
= new ParserOptions
;
3844 $this->setOutputType
= self
::OT_PREPROCESS
;
3847 # Option to disable this feature
3848 if ( !$this->mOptions
->getCleanSignatures() ) {
3852 # FIXME: regex doesn't respect extension tags or nowiki
3853 # => Move this logic to braceSubstitution()
3854 $substWord = MagicWord
::get( 'subst' );
3855 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3856 $substText = '{{' . $substWord->getSynonym( 0 );
3858 $text = preg_replace( $substRegex, $substText, $text );
3859 $text = $this->cleanSigInSig( $text );
3860 $dom = $this->preprocessToDom( $text );
3861 $frame = $this->getPreprocessor()->newFrame();
3862 $text = $frame->expand( $dom );
3865 $text = $this->mStripState
->unstripBoth( $text );
3872 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3873 * @param string $text
3874 * @return string Signature text with /~{3,5}/ removed
3876 function cleanSigInSig( $text ) {
3877 $text = preg_replace( '/~{3,5}/', '', $text );
3882 * Set up some variables which are usually set up in parse()
3883 * so that an external function can call some class members with confidence
3886 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3887 $this->setTitle( $title );
3888 $this->mOptions
= $options;
3889 $this->setOutputType( $outputType );
3890 if ( $clearState ) {
3891 $this->clearState();
3896 * Wrapper for preprocess()
3898 * @param string $text the text to preprocess
3899 * @param ParserOptions $options options
3903 function transformMsg( $text, $options ) {
3905 static $executing = false;
3907 # Guard against infinite recursion
3913 wfProfileIn(__METHOD__
);
3914 $text = $this->preprocess( $text, $wgTitle, $options );
3917 wfProfileOut(__METHOD__
);
3922 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3923 * The callback should have the following form:
3924 * function myParserHook( $text, $params, &$parser ) { ... }
3926 * Transform and return $text. Use $parser for any required context, e.g. use
3927 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3931 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3932 * @param mixed $callback The callback function (and object) to use for the tag
3934 * @return The old value of the mTagHooks array associated with the hook
3936 function setHook( $tag, $callback ) {
3937 $tag = strtolower( $tag );
3938 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3939 $this->mTagHooks
[$tag] = $callback;
3940 if( !in_array( $tag, $this->mStripList
) ) {
3941 $this->mStripList
[] = $tag;
3947 function setTransparentTagHook( $tag, $callback ) {
3948 $tag = strtolower( $tag );
3949 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3950 $this->mTransparentTagHooks
[$tag] = $callback;
3956 * Remove all tag hooks
3958 function clearTagHooks() {
3959 $this->mTagHooks
= array();
3960 $this->mStripList
= $this->mDefaultStripList
;
3964 * Create a function, e.g. {{sum:1|2|3}}
3965 * The callback function should have the form:
3966 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3968 * Or with SFH_OBJECT_ARGS:
3969 * function myParserFunction( $parser, $frame, $args ) { ... }
3971 * The callback may either return the text result of the function, or an array with the text
3972 * in element 0, and a number of flags in the other elements. The names of the flags are
3973 * specified in the keys. Valid flags are:
3974 * found The text returned is valid, stop processing the template. This
3976 * nowiki Wiki markup in the return value should be escaped
3977 * isHTML The returned text is HTML, armour it against wikitext transformation
3981 * @param string $id The magic word ID
3982 * @param mixed $callback The callback function (and object) to use
3983 * @param integer $flags a combination of the following flags:
3984 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3986 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3987 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3988 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3989 * the arguments, and to control the way they are expanded.
3991 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3992 * arguments, for instance:
3993 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3995 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3996 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3997 * working if/when this is changed.
3999 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4002 * Please read the documentation in includes/parser/Preprocessor.php for more information
4003 * about the methods available in PPFrame and PPNode.
4005 * @return The old callback function for this name, if any
4007 function setFunctionHook( $id, $callback, $flags = 0 ) {
4008 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4009 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4011 # Add to function cache
4012 $mw = MagicWord
::get( $id );
4014 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4016 $synonyms = $mw->getSynonyms();
4017 $sensitive = intval( $mw->isCaseSensitive() );
4019 foreach ( $synonyms as $syn ) {
4021 if ( !$sensitive ) {
4022 $syn = strtolower( $syn );
4025 if ( !( $flags & SFH_NO_HASH
) ) {
4028 # Remove trailing colon
4029 if ( substr( $syn, -1, 1 ) === ':' ) {
4030 $syn = substr( $syn, 0, -1 );
4032 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4038 * Get all registered function hook identifiers
4042 function getFunctionHooks() {
4043 return array_keys( $this->mFunctionHooks
);
4047 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4048 * Placeholders created in Skin::makeLinkObj()
4049 * Returns an array of link CSS classes, indexed by PDBK.
4051 function replaceLinkHolders( &$text, $options = 0 ) {
4052 return $this->mLinkHolders
->replace( $text );
4056 * Replace <!--LINK--> link placeholders with plain text of links
4057 * (not HTML-formatted).
4058 * @param string $text
4061 function replaceLinkHoldersText( $text ) {
4062 return $this->mLinkHolders
->replaceText( $text );
4066 * Tag hook handler for 'pre'.
4068 function renderPreTag( $text, $attribs ) {
4069 // Backwards-compatibility hack
4070 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4072 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4073 return wfOpenElement( 'pre', $attribs ) .
4074 Xml
::escapeTagsOnly( $content ) .
4079 * Renders an image gallery from a text with one line per image.
4080 * text labels may be given by using |-style alternative text. E.g.
4081 * Image:one.jpg|The number "1"
4082 * Image:tree.jpg|A tree
4083 * given as text will return the HTML of a gallery with two images,
4084 * labeled 'The number "1"' and
4087 function renderImageGallery( $text, $params ) {
4088 $ig = new ImageGallery();
4089 $ig->setContextTitle( $this->mTitle
);
4090 $ig->setShowBytes( false );
4091 $ig->setShowFilename( false );
4092 $ig->setParser( $this );
4093 $ig->setHideBadImages();
4094 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4095 $ig->useSkin( $this->mOptions
->getSkin() );
4096 $ig->mRevisionId
= $this->mRevisionId
;
4098 if( isset( $params['caption'] ) ) {
4099 $caption = $params['caption'];
4100 $caption = htmlspecialchars( $caption );
4101 $caption = $this->replaceInternalLinks( $caption );
4102 $ig->setCaptionHtml( $caption );
4104 if( isset( $params['perrow'] ) ) {
4105 $ig->setPerRow( $params['perrow'] );
4107 if( isset( $params['widths'] ) ) {
4108 $ig->setWidths( $params['widths'] );
4110 if( isset( $params['heights'] ) ) {
4111 $ig->setHeights( $params['heights'] );
4114 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4116 $lines = StringUtils
::explode( "\n", $text );
4117 foreach ( $lines as $line ) {
4118 # match lines like these:
4119 # Image:someimage.jpg|This is some image
4121 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4123 if ( count( $matches ) == 0 ) {
4127 if ( strpos( $matches[0], '%' ) !== false )
4128 $matches[1] = urldecode( $matches[1] );
4129 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4131 if( is_null( $nt ) ) {
4132 # Bogus title. Ignore these so we don't bomb out later.
4135 if ( isset( $matches[3] ) ) {
4136 $label = $matches[3];
4141 $html = $this->recursiveTagParse( trim( $label ) );
4143 $ig->add( $nt, $html );
4145 # Only add real images (bug #5586)
4146 if ( $nt->getNamespace() == NS_IMAGE
) {
4147 $this->mOutput
->addImage( $nt->getDBkey() );
4150 return $ig->toHTML();
4153 function getImageParams( $handler ) {
4155 $handlerClass = get_class( $handler );
4159 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4160 // Initialise static lists
4161 static $internalParamNames = array(
4162 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4163 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4164 'bottom', 'text-bottom' ),
4165 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4166 'upright', 'border' ),
4168 static $internalParamMap;
4169 if ( !$internalParamMap ) {
4170 $internalParamMap = array();
4171 foreach ( $internalParamNames as $type => $names ) {
4172 foreach ( $names as $name ) {
4173 $magicName = str_replace( '-', '_', "img_$name" );
4174 $internalParamMap[$magicName] = array( $type, $name );
4179 // Add handler params
4180 $paramMap = $internalParamMap;
4182 $handlerParamMap = $handler->getParamMap();
4183 foreach ( $handlerParamMap as $magic => $paramName ) {
4184 $paramMap[$magic] = array( 'handler', $paramName );
4187 $this->mImageParams
[$handlerClass] = $paramMap;
4188 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4190 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4194 * Parse image options text and use it to make an image
4195 * @param Title $title
4196 * @param string $options
4197 * @param LinkHolderArray $holders
4199 function makeImage( $title, $options, $holders = false ) {
4200 # Check if the options text is of the form "options|alt text"
4202 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4203 # * left no resizing, just left align. label is used for alt= only
4204 # * right same, but right aligned
4205 # * none same, but not aligned
4206 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4207 # * center center the image
4208 # * framed Keep original image size, no magnify-button.
4209 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4210 # * upright reduce width for upright images, rounded to full __0 px
4211 # * border draw a 1px border around the image
4212 # vertical-align values (no % or length right now):
4222 $parts = StringUtils
::explode( "|", $options );
4223 $sk = $this->mOptions
->getSkin();
4225 # Give extensions a chance to select the file revision for us
4226 $skip = $time = $descQuery = false;
4227 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4230 return $sk->link( $title );
4234 $file = wfFindFile( $title, $time );
4235 $handler = $file ?
$file->getHandler() : false;
4237 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4239 # Process the input parameters
4241 $params = array( 'frame' => array(), 'handler' => array(),
4242 'horizAlign' => array(), 'vertAlign' => array() );
4243 foreach( $parts as $part ) {
4244 $part = trim( $part );
4245 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4247 if( isset( $paramMap[$magicName] ) ) {
4248 list( $type, $paramName ) = $paramMap[$magicName];
4250 // Special case; width and height come in one variable together
4251 if( $type === 'handler' && $paramName === 'width' ) {
4253 # (bug 13500) In both cases (width/height and width only),
4254 # permit trailing "px" for backward compatibility.
4255 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4256 $width = intval( $m[1] );
4257 $height = intval( $m[2] );
4258 if ( $handler->validateParam( 'width', $width ) ) {
4259 $params[$type]['width'] = $width;
4262 if ( $handler->validateParam( 'height', $height ) ) {
4263 $params[$type]['height'] = $height;
4266 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4267 $width = intval( $value );
4268 if ( $handler->validateParam( 'width', $width ) ) {
4269 $params[$type]['width'] = $width;
4272 } // else no validation -- bug 13436
4274 if ( $type === 'handler' ) {
4275 # Validate handler parameter
4276 $validated = $handler->validateParam( $paramName, $value );
4278 # Validate internal parameters
4279 switch( $paramName ) {
4281 /// @fixme - possibly check validity here?
4282 /// downstream behavior seems odd with missing manual thumbs.
4286 // Most other things appear to be empty or numeric...
4287 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4292 $params[$type][$paramName] = $value;
4296 if ( !$validated ) {
4301 # Process alignment parameters
4302 if ( $params['horizAlign'] ) {
4303 $params['frame']['align'] = key( $params['horizAlign'] );
4305 if ( $params['vertAlign'] ) {
4306 $params['frame']['valign'] = key( $params['vertAlign'] );
4309 # Strip bad stuff out of the alt text
4310 # We can't just use replaceLinkHoldersText() here, because if this function
4311 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4313 $alt = $holders->replaceText( $caption );
4315 $alt = $this->replaceLinkHoldersText( $caption );
4318 # make sure there are no placeholders in thumbnail attributes
4319 # that are later expanded to html- so expand them now and
4321 $alt = $this->mStripState
->unstripBoth( $alt );
4322 $alt = Sanitizer
::stripAllTags( $alt );
4324 $params['frame']['alt'] = $alt;
4325 $params['frame']['caption'] = $caption;
4327 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4329 # Linker does the rest
4330 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4332 # Give the handler a chance to modify the parser object
4334 $handler->parserTransformHook( $this, $file );
4341 * Set a flag in the output object indicating that the content is dynamic and
4342 * shouldn't be cached.
4344 function disableCache() {
4345 wfDebug( "Parser output marked as uncacheable.\n" );
4346 $this->mOutput
->mCacheTime
= -1;
4350 * Callback from the Sanitizer for expanding items found in HTML attribute
4351 * values, so they can be safely tested and escaped.
4352 * @param string $text
4353 * @param PPFrame $frame
4357 function attributeStripCallback( &$text, $frame = false ) {
4358 $text = $this->replaceVariables( $text, $frame );
4359 $text = $this->mStripState
->unstripBoth( $text );
4368 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4369 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4370 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4376 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4381 * Break wikitext input into sections, and either pull or replace
4382 * some particular section's text.
4384 * External callers should use the getSection and replaceSection methods.
4386 * @param string $text Page wikitext
4387 * @param string $section A section identifier string of the form:
4388 * <flag1> - <flag2> - ... - <section number>
4390 * Currently the only recognised flag is "T", which means the target section number
4391 * was derived during a template inclusion parse, in other words this is a template
4392 * section edit link. If no flags are given, it was an ordinary section edit link.
4393 * This flag is required to avoid a section numbering mismatch when a section is
4394 * enclosed by <includeonly> (bug 6563).
4396 * The section number 0 pulls the text before the first heading; other numbers will
4397 * pull the given section along with its lower-level subsections. If the section is
4398 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4400 * @param string $mode One of "get" or "replace"
4401 * @param string $newText Replacement text for section data.
4402 * @return string for "get", the extracted section text.
4403 * for "replace", the whole page with the section replaced.
4405 private function extractSections( $text, $section, $mode, $newText='' ) {
4407 $this->clearState();
4408 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4409 $this->mOptions
= new ParserOptions
;
4410 $this->setOutputType( self
::OT_WIKI
);
4412 $frame = $this->getPreprocessor()->newFrame();
4414 // Process section extraction flags
4416 $sectionParts = explode( '-', $section );
4417 $sectionIndex = array_pop( $sectionParts );
4418 foreach ( $sectionParts as $part ) {
4419 if ( $part === 'T' ) {
4420 $flags |
= self
::PTD_FOR_INCLUSION
;
4423 // Preprocess the text
4424 $root = $this->preprocessToDom( $text, $flags );
4426 // <h> nodes indicate section breaks
4427 // They can only occur at the top level, so we can find them by iterating the root's children
4428 $node = $root->getFirstChild();
4430 // Find the target section
4431 if ( $sectionIndex == 0 ) {
4432 // Section zero doesn't nest, level=big
4433 $targetLevel = 1000;
4436 if ( $node->getName() === 'h' ) {
4437 $bits = $node->splitHeading();
4438 if ( $bits['i'] == $sectionIndex ) {
4439 $targetLevel = $bits['level'];
4443 if ( $mode === 'replace' ) {
4444 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4446 $node = $node->getNextSibling();
4452 if ( $mode === 'get' ) {
4459 // Find the end of the section, including nested sections
4461 if ( $node->getName() === 'h' ) {
4462 $bits = $node->splitHeading();
4463 $curLevel = $bits['level'];
4464 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4468 if ( $mode === 'get' ) {
4469 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4471 $node = $node->getNextSibling();
4474 // Write out the remainder (in replace mode only)
4475 if ( $mode === 'replace' ) {
4476 // Output the replacement text
4477 // Add two newlines on -- trailing whitespace in $newText is conventionally
4478 // stripped by the editor, so we need both newlines to restore the paragraph gap
4479 $outText .= $newText . "\n\n";
4481 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4482 $node = $node->getNextSibling();
4486 if ( is_string( $outText ) ) {
4487 // Re-insert stripped tags
4488 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4495 * This function returns the text of a section, specified by a number ($section).
4496 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4497 * the first section before any such heading (section 0).
4499 * If a section contains subsections, these are also returned.
4501 * @param string $text text to look in
4502 * @param string $section section identifier
4503 * @param string $deftext default to return if section is not found
4504 * @return string text of the requested section
4506 public function getSection( $text, $section, $deftext='' ) {
4507 return $this->extractSections( $text, $section, "get", $deftext );
4510 public function replaceSection( $oldtext, $section, $text ) {
4511 return $this->extractSections( $oldtext, $section, "replace", $text );
4515 * Get the timestamp associated with the current revision, adjusted for
4516 * the default server-local timestamp
4518 function getRevisionTimestamp() {
4519 if ( is_null( $this->mRevisionTimestamp
) ) {
4520 wfProfileIn( __METHOD__
);
4522 $dbr = wfGetDB( DB_SLAVE
);
4523 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4524 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4526 // Normalize timestamp to internal MW format for timezone processing.
4527 // This has the added side-effect of replacing a null value with
4528 // the current time, which gives us more sensible behavior for
4530 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4532 // The cryptic '' timezone parameter tells to use the site-default
4533 // timezone offset instead of the user settings.
4535 // Since this value will be saved into the parser cache, served
4536 // to other users, and potentially even used inside links and such,
4537 // it needs to be consistent for all visitors.
4538 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4540 wfProfileOut( __METHOD__
);
4542 return $this->mRevisionTimestamp
;
4546 * Mutator for $mDefaultSort
4548 * @param $sort New value
4550 public function setDefaultSort( $sort ) {
4551 $this->mDefaultSort
= $sort;
4555 * Accessor for $mDefaultSort
4556 * Will use the title/prefixed title if none is set
4560 public function getDefaultSort() {
4561 global $wgCategoryPrefixedDefaultSortkey;
4562 if( $this->mDefaultSort
!== false ) {
4563 return $this->mDefaultSort
;
4564 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4565 !$wgCategoryPrefixedDefaultSortkey) {
4566 return $this->mTitle
->getText();
4568 return $this->mTitle
->getPrefixedText();
4573 * Try to guess the section anchor name based on a wikitext fragment
4574 * presumably extracted from a heading, for example "Header" from
4577 public function guessSectionNameFromWikiText( $text ) {
4578 # Strip out wikitext links(they break the anchor)
4579 $text = $this->stripSectionName( $text );
4580 $headline = Sanitizer
::decodeCharReferences( $text );
4582 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4583 $headline = trim( $headline );
4584 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4585 $replacearray = array(
4590 array_keys( $replacearray ),
4591 array_values( $replacearray ),
4596 * Strips a text string of wikitext for use in a section anchor
4598 * Accepts a text string and then removes all wikitext from the
4599 * string and leaves only the resultant text (i.e. the result of
4600 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4601 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4602 * to create valid section anchors by mimicing the output of the
4603 * parser when headings are parsed.
4605 * @param $text string Text string to be stripped of wikitext
4606 * for use in a Section anchor
4607 * @return Filtered text string
4609 public function stripSectionName( $text ) {
4610 # Strip internal link markup
4611 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4612 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4614 # Strip external link markup (FIXME: Not Tolerant to blank link text
4615 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4616 # on how many empty links there are on the page - need to figure that out.
4617 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4619 # Parse wikitext quotes (italics & bold)
4620 $text = $this->doQuotes($text);
4623 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4627 function srvus( $text ) {
4628 return $this->testSrvus( $text, $this->mOutputType
);
4632 * strip/replaceVariables/unstrip for preprocessor regression testing
4634 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4635 $this->clearState();
4636 if ( ! ( $title instanceof Title
) ) {
4637 $title = Title
::newFromText( $title );
4639 $this->mTitle
= $title;
4640 $this->mOptions
= $options;
4641 $this->setOutputType( $outputType );
4642 $text = $this->replaceVariables( $text );
4643 $text = $this->mStripState
->unstripBoth( $text );
4644 $text = Sanitizer
::removeHTMLtags( $text );
4648 function testPst( $text, $title, $options ) {
4650 if ( ! ( $title instanceof Title
) ) {
4651 $title = Title
::newFromText( $title );
4653 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4656 function testPreprocess( $text, $title, $options ) {
4657 if ( ! ( $title instanceof Title
) ) {
4658 $title = Title
::newFromText( $title );
4660 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4663 function markerSkipCallback( $s, $callback ) {
4666 while ( $i < strlen( $s ) ) {
4667 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4668 if ( $markerStart === false ) {
4669 $out .= call_user_func( $callback, substr( $s, $i ) );
4672 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4673 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4674 if ( $markerEnd === false ) {
4675 $out .= substr( $s, $markerStart );
4678 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4679 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4689 * @todo document, briefly.
4693 var $general, $nowiki;
4695 function __construct() {
4696 $this->general
= new ReplacementArray
;
4697 $this->nowiki
= new ReplacementArray
;
4700 function unstripGeneral( $text ) {
4701 wfProfileIn( __METHOD__
);
4704 $text = $this->general
->replace( $text );
4705 } while ( $text !== $oldText );
4706 wfProfileOut( __METHOD__
);
4710 function unstripNoWiki( $text ) {
4711 wfProfileIn( __METHOD__
);
4714 $text = $this->nowiki
->replace( $text );
4715 } while ( $text !== $oldText );
4716 wfProfileOut( __METHOD__
);
4720 function unstripBoth( $text ) {
4721 wfProfileIn( __METHOD__
);
4724 $text = $this->general
->replace( $text );
4725 $text = $this->nowiki
->replace( $text );
4726 } while ( $text !== $oldText );
4727 wfProfileOut( __METHOD__
);
4733 * @todo document, briefly.
4736 class OnlyIncludeReplacer
{
4739 function replace( $matches ) {
4740 if ( substr( $matches[1], -1 ) === "\n" ) {
4741 $this->output
.= substr( $matches[1], 0, -1 );
4743 $this->output
.= $matches[1];