5 * 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;
90 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
91 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix, $mMarkerIndex,
92 $mExtLinkBracketedRegex, $mPreprocessor, $mDefaultStripList, $mVarCache, $mConf;
95 # Cleared with clearState():
96 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
97 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
98 var $mInterwikiLinkHolders, $mLinkHolders;
99 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
100 var $mTplExpandCache; // empty-frame expansion cache
101 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
104 # These are variables reset at least once per parse regardless of $clearState
105 var $mOptions, // ParserOptions object
106 $mTitle, // Title context, used for self-link rendering and similar things
107 $mOutputType, // Output type, one of the OT_xxx constants
108 $ot, // Shortcut alias, see setOutputType()
109 $mRevisionId, // ID to display in {{REVISIONID}} tags
110 $mRevisionTimestamp, // The timestamp of the specified revision ID
111 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
120 function __construct( $conf = array() ) {
121 $this->mConf
= $conf;
122 $this->mTagHooks
= array();
123 $this->mTransparentTagHooks
= array();
124 $this->mFunctionHooks
= array();
125 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
126 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
127 $this->mMarkerSuffix
= "-QINU\x7f";
128 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
129 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
130 $this->mVarCache
= array();
131 if ( isset( $conf['preprocessorClass'] ) ) {
132 $this->mPreprocessorClass
= $conf['preprocessorClass'];
134 $this->mPreprocessorClass
= 'Preprocessor_DOM';
136 $this->mMarkerIndex
= 0;
137 $this->mFirstCall
= true;
141 * Do various kinds of initialisation on the first call of the parser
143 function firstCallInit() {
144 if ( !$this->mFirstCall
) {
147 $this->mFirstCall
= false;
149 wfProfileIn( __METHOD__
);
151 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
152 CoreParserFunctions
::register( $this );
153 $this->initialiseVariables();
155 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
156 wfProfileOut( __METHOD__
);
164 function clearState() {
165 wfProfileIn( __METHOD__
);
166 if ( $this->mFirstCall
) {
167 $this->firstCallInit();
169 $this->mOutput
= new ParserOutput
;
170 $this->mAutonumber
= 0;
171 $this->mLastSection
= '';
172 $this->mDTopen
= false;
173 $this->mIncludeCount
= array();
174 $this->mStripState
= new StripState
;
175 $this->mArgStack
= false;
176 $this->mInPre
= false;
177 $this->mInterwikiLinkHolders
= array(
181 $this->mLinkHolders
= array(
182 'namespaces' => array(),
184 'queries' => array(),
188 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
191 * Prefix for temporary replacement strings for the multipass parser.
192 * \x07 should never appear in input as it's disallowed in XML.
193 * Using it at the front also gives us a little extra robustness
194 * since it shouldn't match when butted up against identifier-like
197 * Must not consist of all title characters, or else it will change
198 * the behaviour of <nowiki> in a link.
200 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
201 # Changed to \x7f to allow XML double-parsing -- TS
202 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
205 # Clear these on every parse, bug 4549
206 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
208 $this->mShowToc
= true;
209 $this->mForceTocPosition
= false;
210 $this->mIncludeSizes
= array(
214 $this->mPPNodeCount
= 0;
215 $this->mDefaultSort
= false;
216 $this->mHeadings
= array();
217 $this->mDoubleUnderscores
= array();
220 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
221 $this->mPreprocessor
= null;
224 wfRunHooks( 'ParserClearState', array( &$this ) );
225 wfProfileOut( __METHOD__
);
228 function setOutputType( $ot ) {
229 $this->mOutputType
= $ot;
232 'html' => $ot == self
::OT_HTML
,
233 'wiki' => $ot == self
::OT_WIKI
,
234 'pre' => $ot == self
::OT_PREPROCESS
,
239 * Set the context title
241 function setTitle( $t ) {
242 if ( !$t ||
$t instanceof FakeTitle
) {
243 $t = Title
::newFromText( 'NO TITLE' );
245 if ( strval( $t->getFragment() ) !== '' ) {
246 # Strip the fragment to avoid various odd effects
247 $this->mTitle
= clone $t;
248 $this->mTitle
->setFragment( '' );
255 * Accessor for mUniqPrefix.
259 function uniqPrefix() {
260 if( !isset( $this->mUniqPrefix
) ) {
261 // @fixme this is probably *horribly wrong*
262 // LanguageConverter seems to want $wgParser's uniqPrefix, however
263 // if this is called for a parser cache hit, the parser may not
264 // have ever been initialized in the first place.
265 // Not really sure what the heck is supposed to be going on here.
267 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
269 return $this->mUniqPrefix
;
273 * Convert wikitext to HTML
274 * Do not call this function recursively.
276 * @param string $text Text we want to parse
277 * @param Title &$title A title object
278 * @param array $options
279 * @param boolean $linestart
280 * @param boolean $clearState
281 * @param int $revid number to pass in {{REVISIONID}}
282 * @return ParserOutput a ParserOutput
284 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
286 * First pass--just handle <nowiki> sections, pass the rest off
287 * to internalParse() which does all the real work.
290 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
291 $fname = 'Parser::parse-' . wfGetCaller();
292 wfProfileIn( __METHOD__
);
293 wfProfileIn( $fname );
299 $this->mOptions
= $options;
300 $this->setTitle( $title );
301 $oldRevisionId = $this->mRevisionId
;
302 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
303 if( $revid !== null ) {
304 $this->mRevisionId
= $revid;
305 $this->mRevisionTimestamp
= null;
307 $this->setOutputType( self
::OT_HTML
);
308 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
310 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
311 $text = $this->internalParse( $text );
312 $text = $this->mStripState
->unstripGeneral( $text );
314 # Clean up special characters, only run once, next-to-last before doBlockLevels
316 # french spaces, last one Guillemet-left
317 # only if there is something before the space
318 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
319 # french spaces, Guillemet-right
320 '/(\\302\\253) /' => '\\1 ',
321 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
323 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
326 $text = $this->doBlockLevels( $text, $linestart );
328 $this->replaceLinkHolders( $text );
330 # the position of the parserConvert() call should not be changed. it
331 # assumes that the links are all replaced and the only thing left
332 # is the <nowiki> mark.
333 # Side-effects: this calls $this->mOutput->setTitleText()
334 $text = $wgContLang->parserConvert( $text, $this );
336 $text = $this->mStripState
->unstripNoWiki( $text );
338 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
340 //!JF Move to its own function
342 $uniq_prefix = $this->mUniqPrefix
;
344 $elements = array_keys( $this->mTransparentTagHooks
);
345 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
347 foreach( $matches as $marker => $data ) {
348 list( $element, $content, $params, $tag ) = $data;
349 $tagName = strtolower( $element );
350 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
351 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
352 array( $content, $params, $this ) );
356 $this->mStripState
->general
->setPair( $marker, $output );
358 $text = $this->mStripState
->unstripGeneral( $text );
360 $text = Sanitizer
::normalizeCharReferences( $text );
362 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
363 $text = Parser
::tidy($text);
365 # attempt to sanitize at least some nesting problems
366 # (bug #2702 and quite a few others)
368 # ''Something [http://www.cool.com cool''] -->
369 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
370 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
371 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
372 # fix up an anchor inside another anchor, only
373 # at least for a single single nested link (bug 3695)
374 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
375 '\\1\\2</a>\\3</a>\\1\\4</a>',
376 # fix div inside inline elements- doBlockLevels won't wrap a line which
377 # contains a div, so fix it up here; replace
378 # div with escaped text
379 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
380 '\\1\\3<div\\5>\\6</div>\\8\\9',
381 # remove empty italic or bold tag pairs, some
382 # introduced by rules above
383 '/<([bi])><\/\\1>/' => '',
386 $text = preg_replace(
387 array_keys( $tidyregs ),
388 array_values( $tidyregs ),
392 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
394 # Information on include size limits, for the benefit of users who try to skirt them
395 if ( $this->mOptions
->getEnableLimitReport() ) {
396 $max = $this->mOptions
->getMaxIncludeSize();
398 "NewPP limit report\n" .
399 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
400 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
401 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
402 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
403 $text .= "\n<!-- \n$limitReport-->\n";
405 $this->mOutput
->setText( $text );
406 $this->mRevisionId
= $oldRevisionId;
407 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
408 wfProfileOut( $fname );
409 wfProfileOut( __METHOD__
);
411 return $this->mOutput
;
415 * Recursive parser entry point that can be called from an extension tag
418 function recursiveTagParse( $text ) {
419 wfProfileIn( __METHOD__
);
420 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
421 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
422 $text = $this->internalParse( $text );
423 wfProfileOut( __METHOD__
);
428 * Expand templates and variables in the text, producing valid, static wikitext.
429 * Also removes comments.
431 function preprocess( $text, $title, $options, $revid = null ) {
432 wfProfileIn( __METHOD__
);
434 $this->setOutputType( self
::OT_PREPROCESS
);
435 $this->mOptions
= $options;
436 $this->setTitle( $title );
437 if( $revid !== null ) {
438 $this->mRevisionId
= $revid;
440 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
441 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
442 $text = $this->replaceVariables( $text );
443 $text = $this->mStripState
->unstripBoth( $text );
444 wfProfileOut( __METHOD__
);
449 * Get a random string
454 function getRandomString() {
455 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
458 function &getTitle() { return $this->mTitle
; }
459 function getOptions() { return $this->mOptions
; }
461 function getFunctionLang() {
462 global $wgLang, $wgContLang;
464 $target = $this->mOptions
->getTargetLanguage();
465 if ( $target !== null ) {
468 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
473 * Get a preprocessor object
475 function getPreprocessor() {
476 if ( !isset( $this->mPreprocessor
) ) {
477 $class = $this->mPreprocessorClass
;
478 $this->mPreprocessor
= new $class( $this );
480 return $this->mPreprocessor
;
484 * Replaces all occurrences of HTML-style comments and the given tags
485 * in the text with a random marker and returns the next text. The output
486 * parameter $matches will be an associative array filled with data in
488 * 'UNIQ-xxxxx' => array(
491 * array( 'param' => 'x' ),
492 * '<element param="x">tag content</element>' ) )
494 * @param $elements list of element names. Comments are always extracted.
495 * @param $text Source text string.
496 * @param $uniq_prefix
501 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
506 $taglist = implode( '|', $elements );
507 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
509 while ( '' != $text ) {
510 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
512 if( count( $p ) < 5 ) {
515 if( count( $p ) > 5 ) {
529 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
530 $stripped .= $marker;
532 if ( $close === '/>' ) {
533 // Empty element tag, <tag />
538 if( $element == '!--' ) {
541 $end = "/(<\\/$element\\s*>)/i";
543 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
545 if( count( $q ) < 3 ) {
546 # No end tag -- let it run out to the end of the text.
555 $matches[$marker] = array( $element,
557 Sanitizer
::decodeTagAttributes( $attributes ),
558 "<$element$attributes$close$content$tail" );
564 * Get a list of strippable XML-like elements
566 function getStripList() {
568 $elements = $this->mStripList
;
570 $elements[] = 'html';
572 if( $this->mOptions
->getUseTeX() ) {
573 $elements[] = 'math';
579 * @deprecated use replaceVariables
581 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
586 * Restores pre, math, and other extensions removed by strip()
588 * always call unstripNoWiki() after this one
590 * @deprecated use $this->mStripState->unstrip()
592 function unstrip( $text, $state ) {
593 return $state->unstripGeneral( $text );
597 * Always call this after unstrip() to preserve the order
600 * @deprecated use $this->mStripState->unstrip()
602 function unstripNoWiki( $text, $state ) {
603 return $state->unstripNoWiki( $text );
607 * @deprecated use $this->mStripState->unstripBoth()
609 function unstripForHTML( $text ) {
610 return $this->mStripState
->unstripBoth( $text );
614 * Add an item to the strip state
615 * Returns the unique tag which must be inserted into the stripped text
616 * The tag will be replaced with the original text in unstrip()
620 function insertStripItem( $text ) {
621 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-{$this->mMarkerSuffix}";
622 $this->mMarkerIndex++
;
623 $this->mStripState
->general
->setPair( $rnd, $text );
628 * Interface with html tidy, used if $wgUseTidy = true.
629 * If tidy isn't able to correct the markup, the original will be
630 * returned in all its glory with a warning comment appended.
632 * Either the external tidy program or the in-process tidy extension
633 * will be used depending on availability. Override the default
634 * $wgTidyInternal setting to disable the internal if it's not working.
636 * @param string $text Hideous HTML input
637 * @return string Corrected HTML output
641 function tidy( $text ) {
642 global $wgTidyInternal;
643 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
644 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
645 '<head><title>test</title></head><body>'.$text.'</body></html>';
646 if( $wgTidyInternal ) {
647 $correctedtext = Parser
::internalTidy( $wrappedtext );
649 $correctedtext = Parser
::externalTidy( $wrappedtext );
651 if( is_null( $correctedtext ) ) {
652 wfDebug( "Tidy error detected!\n" );
653 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
655 return $correctedtext;
659 * Spawn an external HTML tidy process and get corrected markup back from it.
664 function externalTidy( $text ) {
665 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
666 $fname = 'Parser::externalTidy';
667 wfProfileIn( $fname );
672 $descriptorspec = array(
673 0 => array('pipe', 'r'),
674 1 => array('pipe', 'w'),
675 2 => array('file', wfGetNull(), 'a')
678 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
679 if (is_resource($process)) {
680 // Theoretically, this style of communication could cause a deadlock
681 // here. If the stdout buffer fills up, then writes to stdin could
682 // block. This doesn't appear to happen with tidy, because tidy only
683 // writes to stdout after it's finished reading from stdin. Search
684 // for tidyParseStdin and tidySaveStdout in console/tidy.c
685 fwrite($pipes[0], $text);
687 while (!feof($pipes[1])) {
688 $cleansource .= fgets($pipes[1], 1024);
691 proc_close($process);
694 wfProfileOut( $fname );
696 if( $cleansource == '' && $text != '') {
697 // Some kind of error happened, so we couldn't get the corrected text.
698 // Just give up; we'll use the source text and append a warning.
706 * Use the HTML tidy PECL extension to use the tidy library in-process,
707 * saving the overhead of spawning a new process.
709 * 'pear install tidy' should be able to compile the extension module.
714 function internalTidy( $text ) {
715 global $wgTidyConf, $IP, $wgDebugTidy;
716 $fname = 'Parser::internalTidy';
717 wfProfileIn( $fname );
720 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
721 $tidy->cleanRepair();
722 if( $tidy->getStatus() == 2 ) {
723 // 2 is magic number for fatal error
724 // http://www.php.net/manual/en/function.tidy-get-status.php
727 $cleansource = tidy_get_output( $tidy );
729 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
730 $cleansource .= "<!--\nTidy reports:\n" .
731 str_replace( '-->', '-->', $tidy->errorBuffer
) .
735 wfProfileOut( $fname );
740 * parse the wiki syntax used to render tables
744 function doTableStuff ( $text ) {
745 $fname = 'Parser::doTableStuff';
746 wfProfileIn( $fname );
748 $lines = explode ( "\n" , $text );
749 $td_history = array (); // Is currently a td tag open?
750 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
751 $tr_history = array (); // Is currently a tr tag open?
752 $tr_attributes = array (); // history of tr attributes
753 $has_opened_tr = array(); // Did this table open a <tr> element?
754 $indent_level = 0; // indent level of the table
755 foreach ( $lines as $key => $line )
757 $line = trim ( $line );
759 if( $line == '' ) { // empty line, go to next line
762 $first_character = $line{0};
765 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
766 // First check if we are starting a new table
767 $indent_level = strlen( $matches[1] );
769 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
770 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
772 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
773 array_push ( $td_history , false );
774 array_push ( $last_tag_history , '' );
775 array_push ( $tr_history , false );
776 array_push ( $tr_attributes , '' );
777 array_push ( $has_opened_tr , false );
778 } else if ( count ( $td_history ) == 0 ) {
779 // Don't do any of the following
781 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
782 // We are ending a table
783 $line = '</table>' . substr ( $line , 2 );
784 $last_tag = array_pop ( $last_tag_history );
786 if ( !array_pop ( $has_opened_tr ) ) {
787 $line = "<tr><td></td></tr>{$line}";
790 if ( array_pop ( $tr_history ) ) {
791 $line = "</tr>{$line}";
794 if ( array_pop ( $td_history ) ) {
795 $line = "</{$last_tag}>{$line}";
797 array_pop ( $tr_attributes );
798 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
799 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
800 // Now we have a table row
801 $line = preg_replace( '#^\|-+#', '', $line );
803 // Whats after the tag is now only attributes
804 $attributes = $this->mStripState
->unstripBoth( $line );
805 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
806 array_pop ( $tr_attributes );
807 array_push ( $tr_attributes , $attributes );
810 $last_tag = array_pop ( $last_tag_history );
811 array_pop ( $has_opened_tr );
812 array_push ( $has_opened_tr , true );
814 if ( array_pop ( $tr_history ) ) {
818 if ( array_pop ( $td_history ) ) {
819 $line = "</{$last_tag}>{$line}";
822 $lines[$key] = $line;
823 array_push ( $tr_history , false );
824 array_push ( $td_history , false );
825 array_push ( $last_tag_history , '' );
827 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
828 // This might be cell elements, td, th or captions
829 if ( substr ( $line , 0 , 2 ) == '|+' ) {
830 $first_character = '+';
831 $line = substr ( $line , 1 );
834 $line = substr ( $line , 1 );
836 if ( $first_character == '!' ) {
837 $line = str_replace ( '!!' , '||' , $line );
840 // Split up multiple cells on the same line.
841 // FIXME : This can result in improper nesting of tags processed
842 // by earlier parser steps, but should avoid splitting up eg
843 // attribute values containing literal "||".
844 $cells = StringUtils
::explodeMarkup( '||' , $line );
848 // Loop through each table cell
849 foreach ( $cells as $cell )
852 if ( $first_character != '+' )
854 $tr_after = array_pop ( $tr_attributes );
855 if ( !array_pop ( $tr_history ) ) {
856 $previous = "<tr{$tr_after}>\n";
858 array_push ( $tr_history , true );
859 array_push ( $tr_attributes , '' );
860 array_pop ( $has_opened_tr );
861 array_push ( $has_opened_tr , true );
864 $last_tag = array_pop ( $last_tag_history );
866 if ( array_pop ( $td_history ) ) {
867 $previous = "</{$last_tag}>{$previous}";
870 if ( $first_character == '|' ) {
872 } else if ( $first_character == '!' ) {
874 } else if ( $first_character == '+' ) {
875 $last_tag = 'caption';
880 array_push ( $last_tag_history , $last_tag );
882 // A cell could contain both parameters and data
883 $cell_data = explode ( '|' , $cell , 2 );
885 // Bug 553: Note that a '|' inside an invalid link should not
886 // be mistaken as delimiting cell parameters
887 if ( strpos( $cell_data[0], '[[' ) !== false ) {
888 $cell = "{$previous}<{$last_tag}>{$cell}";
889 } else if ( count ( $cell_data ) == 1 )
890 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
892 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
893 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
894 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
897 $lines[$key] .= $cell;
898 array_push ( $td_history , true );
903 // Closing open td, tr && table
904 while ( count ( $td_history ) > 0 )
906 if ( array_pop ( $td_history ) ) {
909 if ( array_pop ( $tr_history ) ) {
912 if ( !array_pop ( $has_opened_tr ) ) {
913 $lines[] = "<tr><td></td></tr>" ;
916 $lines[] = '</table>' ;
919 $output = implode ( "\n" , $lines ) ;
921 // special case: don't return empty table
922 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
926 wfProfileOut( $fname );
932 * Helper function for parse() that transforms wiki markup into
933 * HTML. Only called for $mOutputType == self::OT_HTML.
937 function internalParse( $text ) {
939 $fname = 'Parser::internalParse';
940 wfProfileIn( $fname );
942 # Hook to suspend the parser in this state
943 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
944 wfProfileOut( $fname );
948 $text = $this->replaceVariables( $text );
949 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
950 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
952 // Tables need to come after variable replacement for things to work
953 // properly; putting them before other transformations should keep
954 // exciting things like link expansions from showing up in surprising
956 $text = $this->doTableStuff( $text );
958 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
960 $text = $this->doDoubleUnderscore( $text );
961 $text = $this->doHeadings( $text );
962 if($this->mOptions
->getUseDynamicDates()) {
963 $df =& DateFormatter
::getInstance();
964 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
966 $text = $this->doAllQuotes( $text );
967 $text = $this->replaceInternalLinks( $text );
968 $text = $this->replaceExternalLinks( $text );
970 # replaceInternalLinks may sometimes leave behind
971 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
972 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
974 $text = $this->doMagicLinks( $text );
975 $text = $this->formatHeadings( $text, $isMain );
977 wfProfileOut( $fname );
982 * Replace special strings like "ISBN xxx" and "RFC xxx" with
983 * magic external links.
987 function doMagicLinks( $text ) {
988 wfProfileIn( __METHOD__
);
989 $text = preg_replace_callback(
991 <a.*?</a> | # Skip link text
992 <.*?> | # Skip stuff inside HTML elements
993 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
994 ISBN\s+(\b # ISBN, capture number as m[2]
995 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
996 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
997 [0-9Xx] # check digit
999 )!x', array( &$this, 'magicLinkCallback' ), $text );
1000 wfProfileOut( __METHOD__
);
1004 function magicLinkCallback( $m ) {
1005 if ( substr( $m[0], 0, 1 ) == '<' ) {
1008 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1010 $num = strtr( $isbn, array(
1015 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1016 $text = '<a href="' .
1017 $titleObj->escapeLocalUrl() .
1018 "\" class=\"internal\">ISBN $isbn</a>";
1020 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1024 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1026 $urlmsg = 'pubmedurl';
1029 throw new MWException( __METHOD__
.': unrecognised match type "' .
1030 substr($m[0], 0, 20 ) . '"' );
1033 $url = wfMsg( $urlmsg, $id);
1034 $sk = $this->mOptions
->getSkin();
1035 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1036 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1042 * Parse headers and return html
1046 function doHeadings( $text ) {
1047 $fname = 'Parser::doHeadings';
1048 wfProfileIn( $fname );
1049 for ( $i = 6; $i >= 1; --$i ) {
1050 $h = str_repeat( '=', $i );
1051 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1052 "<h$i>\\1</h$i>", $text );
1054 wfProfileOut( $fname );
1059 * Replace single quotes with HTML markup
1061 * @return string the altered text
1063 function doAllQuotes( $text ) {
1064 $fname = 'Parser::doAllQuotes';
1065 wfProfileIn( $fname );
1067 $lines = explode( "\n", $text );
1068 foreach ( $lines as $line ) {
1069 $outtext .= $this->doQuotes ( $line ) . "\n";
1071 $outtext = substr($outtext, 0,-1);
1072 wfProfileOut( $fname );
1077 * Helper function for doAllQuotes()
1079 public function doQuotes( $text ) {
1080 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1081 if ( count( $arr ) == 1 )
1085 # First, do some preliminary work. This may shift some apostrophes from
1086 # being mark-up to being text. It also counts the number of occurrences
1087 # of bold and italics mark-ups.
1091 foreach ( $arr as $r )
1093 if ( ( $i %
2 ) == 1 )
1095 # If there are ever four apostrophes, assume the first is supposed to
1096 # be text, and the remaining three constitute mark-up for bold text.
1097 if ( strlen( $arr[$i] ) == 4 )
1102 # If there are more than 5 apostrophes in a row, assume they're all
1103 # text except for the last 5.
1104 else if ( strlen( $arr[$i] ) > 5 )
1106 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1109 # Count the number of occurrences of bold and italics mark-ups.
1110 # We are not counting sequences of five apostrophes.
1111 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1112 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1113 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1118 # If there is an odd number of both bold and italics, it is likely
1119 # that one of the bold ones was meant to be an apostrophe followed
1120 # by italics. Which one we cannot know for certain, but it is more
1121 # likely to be one that has a single-letter word before it.
1122 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1125 $firstsingleletterword = -1;
1126 $firstmultiletterword = -1;
1128 foreach ( $arr as $r )
1130 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1132 $x1 = substr ($arr[$i-1], -1);
1133 $x2 = substr ($arr[$i-1], -2, 1);
1135 if ($firstspace == -1) $firstspace = $i;
1136 } else if ($x2 == ' ') {
1137 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1139 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1145 # If there is a single-letter word, use it!
1146 if ($firstsingleletterword > -1)
1148 $arr [ $firstsingleletterword ] = "''";
1149 $arr [ $firstsingleletterword-1 ] .= "'";
1151 # If not, but there's a multi-letter word, use that one.
1152 else if ($firstmultiletterword > -1)
1154 $arr [ $firstmultiletterword ] = "''";
1155 $arr [ $firstmultiletterword-1 ] .= "'";
1157 # ... otherwise use the first one that has neither.
1158 # (notice that it is possible for all three to be -1 if, for example,
1159 # there is only one pentuple-apostrophe in the line)
1160 else if ($firstspace > -1)
1162 $arr [ $firstspace ] = "''";
1163 $arr [ $firstspace-1 ] .= "'";
1167 # Now let's actually convert our apostrophic mush to HTML!
1172 foreach ($arr as $r)
1176 if ($state == 'both')
1183 if (strlen ($r) == 2)
1186 { $output .= '</i>'; $state = ''; }
1187 else if ($state == 'bi')
1188 { $output .= '</i>'; $state = 'b'; }
1189 else if ($state == 'ib')
1190 { $output .= '</b></i><b>'; $state = 'b'; }
1191 else if ($state == 'both')
1192 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1193 else # $state can be 'b' or ''
1194 { $output .= '<i>'; $state .= 'i'; }
1196 else if (strlen ($r) == 3)
1199 { $output .= '</b>'; $state = ''; }
1200 else if ($state == 'bi')
1201 { $output .= '</i></b><i>'; $state = 'i'; }
1202 else if ($state == 'ib')
1203 { $output .= '</b>'; $state = 'i'; }
1204 else if ($state == 'both')
1205 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1206 else # $state can be 'i' or ''
1207 { $output .= '<b>'; $state .= 'b'; }
1209 else if (strlen ($r) == 5)
1212 { $output .= '</b><i>'; $state = 'i'; }
1213 else if ($state == 'i')
1214 { $output .= '</i><b>'; $state = 'b'; }
1215 else if ($state == 'bi')
1216 { $output .= '</i></b>'; $state = ''; }
1217 else if ($state == 'ib')
1218 { $output .= '</b></i>'; $state = ''; }
1219 else if ($state == 'both')
1220 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1221 else # ($state == '')
1222 { $buffer = ''; $state = 'both'; }
1227 # Now close all remaining tags. Notice that the order is important.
1228 if ($state == 'b' ||
$state == 'ib')
1230 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1234 # There might be lonely ''''', so make sure we have a buffer
1235 if ($state == 'both' && $buffer)
1236 $output .= '<b><i>'.$buffer.'</i></b>';
1242 * Replace external links
1244 * Note: this is all very hackish and the order of execution matters a lot.
1245 * Make sure to run maintenance/parserTests.php if you change this code.
1249 function replaceExternalLinks( $text ) {
1251 $fname = 'Parser::replaceExternalLinks';
1252 wfProfileIn( $fname );
1254 $sk = $this->mOptions
->getSkin();
1256 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1258 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1261 while ( $i<count( $bits ) ) {
1263 $protocol = $bits[$i++
];
1264 $text = $bits[$i++
];
1265 $trail = $bits[$i++
];
1267 # The characters '<' and '>' (which were escaped by
1268 # removeHTMLtags()) should not be included in
1269 # URLs, per RFC 2396.
1271 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1272 $text = substr($url, $m2[0][1]) . ' ' . $text;
1273 $url = substr($url, 0, $m2[0][1]);
1276 # If the link text is an image URL, replace it with an <img> tag
1277 # This happened by accident in the original parser, but some people used it extensively
1278 $img = $this->maybeMakeExternalImage( $text );
1279 if ( $img !== false ) {
1285 # Set linktype for CSS - if URL==text, link is essentially free
1286 $linktype = ($text == $url) ?
'free' : 'text';
1288 # No link text, e.g. [http://domain.tld/some.link]
1289 if ( $text == '' ) {
1290 # Autonumber if allowed. See bug #5918
1291 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1292 $text = '[' . ++
$this->mAutonumber
. ']';
1293 $linktype = 'autonumber';
1295 # Otherwise just use the URL
1296 $text = htmlspecialchars( $url );
1300 # Have link text, e.g. [http://domain.tld/some.link text]s
1302 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1305 $text = $wgContLang->markNoConversion($text);
1307 $url = Sanitizer
::cleanUrl( $url );
1309 # Process the trail (i.e. everything after this link up until start of the next link),
1310 # replacing any non-bracketed links
1311 $trail = $this->replaceFreeExternalLinks( $trail );
1313 # Use the encoded URL
1314 # This means that users can paste URLs directly into the text
1315 # Funny characters like ö aren't valid in URLs anyway
1316 # This was changed in August 2004
1317 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1319 # Register link in the output object.
1320 # Replace unnecessary URL escape codes with the referenced character
1321 # This prevents spammers from hiding links from the filters
1322 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1323 $this->mOutput
->addExternalLink( $pasteurized );
1326 wfProfileOut( $fname );
1331 * Replace anything that looks like a URL with a link
1334 function replaceFreeExternalLinks( $text ) {
1336 $fname = 'Parser::replaceFreeExternalLinks';
1337 wfProfileIn( $fname );
1339 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1340 $s = array_shift( $bits );
1343 $sk = $this->mOptions
->getSkin();
1345 while ( $i < count( $bits ) ){
1346 $protocol = $bits[$i++
];
1347 $remainder = $bits[$i++
];
1350 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1351 # Found some characters after the protocol that look promising
1352 $url = $protocol . $m[1];
1355 # special case: handle urls as url args:
1356 # http://www.example.com/foo?=http://www.example.com/bar
1357 if(strlen($trail) == 0 &&
1359 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1360 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1363 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1368 # The characters '<' and '>' (which were escaped by
1369 # removeHTMLtags()) should not be included in
1370 # URLs, per RFC 2396.
1372 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1373 $trail = substr($url, $m2[0][1]) . $trail;
1374 $url = substr($url, 0, $m2[0][1]);
1377 # Move trailing punctuation to $trail
1379 # If there is no left bracket, then consider right brackets fair game too
1380 if ( strpos( $url, '(' ) === false ) {
1384 $numSepChars = strspn( strrev( $url ), $sep );
1385 if ( $numSepChars ) {
1386 $trail = substr( $url, -$numSepChars ) . $trail;
1387 $url = substr( $url, 0, -$numSepChars );
1390 $url = Sanitizer
::cleanUrl( $url );
1392 # Is this an external image?
1393 $text = $this->maybeMakeExternalImage( $url );
1394 if ( $text === false ) {
1395 # Not an image, make a link
1396 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1397 # Register it in the output object...
1398 # Replace unnecessary URL escape codes with their equivalent characters
1399 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1400 $this->mOutput
->addExternalLink( $pasteurized );
1402 $s .= $text . $trail;
1404 $s .= $protocol . $remainder;
1407 wfProfileOut( $fname );
1412 * Replace unusual URL escape codes with their equivalent characters
1416 * @todo This can merge genuinely required bits in the path or query string,
1417 * breaking legit URLs. A proper fix would treat the various parts of
1418 * the URL differently; as a workaround, just use the output for
1419 * statistical records, not for actual linking/output.
1421 static function replaceUnusualEscapes( $url ) {
1422 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1423 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1427 * Callback function used in replaceUnusualEscapes().
1428 * Replaces unusual URL escape codes with their equivalent character
1432 private static function replaceUnusualEscapesCallback( $matches ) {
1433 $char = urldecode( $matches[0] );
1434 $ord = ord( $char );
1435 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1436 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1437 // No, shouldn't be escaped
1440 // Yes, leave it escaped
1446 * make an image if it's allowed, either through the global
1447 * option or through the exception
1450 function maybeMakeExternalImage( $url ) {
1451 $sk = $this->mOptions
->getSkin();
1452 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1453 $imagesexception = !empty($imagesfrom);
1455 if ( $this->mOptions
->getAllowExternalImages()
1456 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1457 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1459 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1466 * Process [[ ]] wikilinks
1470 function replaceInternalLinks( $s ) {
1472 static $fname = 'Parser::replaceInternalLinks' ;
1474 wfProfileIn( $fname );
1476 wfProfileIn( $fname.'-setup' );
1478 # the % is needed to support urlencoded titles as well
1479 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1481 $sk = $this->mOptions
->getSkin();
1483 #split the entire text string on occurences of [[
1484 $a = explode( '[[', ' ' . $s );
1485 #get the first element (all text up to first [[), and remove the space we added
1486 $s = array_shift( $a );
1487 $s = substr( $s, 1 );
1489 # Match a link having the form [[namespace:link|alternate]]trail
1491 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1492 # Match cases where there is no "]]", which might still be images
1493 static $e1_img = FALSE;
1494 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1496 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1498 if ( $useLinkPrefixExtension ) {
1499 # Match the end of a line for a word that's not followed by whitespace,
1500 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1501 $e2 = wfMsgForContent( 'linkprefix' );
1504 if( is_null( $this->mTitle
) ) {
1505 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1507 $nottalk = !$this->mTitle
->isTalkPage();
1509 if ( $useLinkPrefixExtension ) {
1511 if ( preg_match( $e2, $s, $m ) ) {
1512 $first_prefix = $m[2];
1514 $first_prefix = false;
1520 if($wgContLang->hasVariants()) {
1521 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1523 $selflink = array($this->mTitle
->getPrefixedText());
1525 $useSubpages = $this->areSubpagesAllowed();
1526 wfProfileOut( $fname.'-setup' );
1528 # Loop for each link
1529 for ($k = 0; isset( $a[$k] ); $k++
) {
1531 if ( $useLinkPrefixExtension ) {
1532 wfProfileIn( $fname.'-prefixhandling' );
1533 if ( preg_match( $e2, $s, $m ) ) {
1541 $prefix = $first_prefix;
1542 $first_prefix = false;
1544 wfProfileOut( $fname.'-prefixhandling' );
1547 $might_be_img = false;
1549 wfProfileIn( "$fname-e1" );
1550 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1552 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1553 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1554 # the real problem is with the $e1 regex
1557 # Still some problems for cases where the ] is meant to be outside punctuation,
1558 # and no image is in sight. See bug 2095.
1561 substr( $m[3], 0, 1 ) === ']' &&
1562 strpos($text, '[') !== false
1565 $text .= ']'; # so that replaceExternalLinks($text) works later
1566 $m[3] = substr( $m[3], 1 );
1568 # fix up urlencoded title texts
1569 if( strpos( $m[1], '%' ) !== false ) {
1570 # Should anchors '#' also be rejected?
1571 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1574 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1575 $might_be_img = true;
1577 if ( strpos( $m[1], '%' ) !== false ) {
1578 $m[1] = urldecode($m[1]);
1581 } else { # Invalid form; output directly
1582 $s .= $prefix . '[[' . $line ;
1583 wfProfileOut( "$fname-e1" );
1586 wfProfileOut( "$fname-e1" );
1587 wfProfileIn( "$fname-misc" );
1589 # Don't allow internal links to pages containing
1590 # PROTO: where PROTO is a valid URL protocol; these
1591 # should be external links.
1592 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1593 $s .= $prefix . '[[' . $line ;
1597 # Make subpage if necessary
1598 if( $useSubpages ) {
1599 $link = $this->maybeDoSubpageLink( $m[1], $text );
1604 $noforce = (substr($m[1], 0, 1) != ':');
1606 # Strip off leading ':'
1607 $link = substr($link, 1);
1610 wfProfileOut( "$fname-misc" );
1611 wfProfileIn( "$fname-title" );
1612 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1614 $s .= $prefix . '[[' . $line;
1615 wfProfileOut( "$fname-title" );
1619 $ns = $nt->getNamespace();
1620 $iw = $nt->getInterWiki();
1621 wfProfileOut( "$fname-title" );
1623 if ($might_be_img) { # if this is actually an invalid link
1624 wfProfileIn( "$fname-might_be_img" );
1625 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1627 while (isset ($a[$k+
1]) ) {
1628 #look at the next 'line' to see if we can close it there
1629 $spliced = array_splice( $a, $k +
1, 1 );
1630 $next_line = array_shift( $spliced );
1631 $m = explode( ']]', $next_line, 3 );
1632 if ( count( $m ) == 3 ) {
1633 # the first ]] closes the inner link, the second the image
1635 $text .= "[[{$m[0]}]]{$m[1]}";
1638 } elseif ( count( $m ) == 2 ) {
1639 #if there's exactly one ]] that's fine, we'll keep looking
1640 $text .= "[[{$m[0]}]]{$m[1]}";
1642 #if $next_line is invalid too, we need look no further
1643 $text .= '[[' . $next_line;
1648 # we couldn't find the end of this imageLink, so output it raw
1649 #but don't ignore what might be perfectly normal links in the text we've examined
1650 $text = $this->replaceInternalLinks($text);
1651 $s .= "{$prefix}[[$link|$text";
1652 # note: no $trail, because without an end, there *is* no trail
1653 wfProfileOut( "$fname-might_be_img" );
1656 } else { #it's not an image, so output it raw
1657 $s .= "{$prefix}[[$link|$text";
1658 # note: no $trail, because without an end, there *is* no trail
1659 wfProfileOut( "$fname-might_be_img" );
1662 wfProfileOut( "$fname-might_be_img" );
1665 $wasblank = ( '' == $text );
1666 if( $wasblank ) $text = $link;
1668 # Link not escaped by : , create the various objects
1672 wfProfileIn( "$fname-interwiki" );
1673 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1674 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1675 $s = rtrim($s . $prefix);
1676 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1677 wfProfileOut( "$fname-interwiki" );
1680 wfProfileOut( "$fname-interwiki" );
1682 if ( $ns == NS_IMAGE
) {
1683 wfProfileIn( "$fname-image" );
1684 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1685 # recursively parse links inside the image caption
1686 # actually, this will parse them in any other parameters, too,
1687 # but it might be hard to fix that, and it doesn't matter ATM
1688 $text = $this->replaceExternalLinks($text);
1689 $text = $this->replaceInternalLinks($text);
1691 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1692 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1693 $this->mOutput
->addImage( $nt->getDBkey() );
1695 wfProfileOut( "$fname-image" );
1698 # We still need to record the image's presence on the page
1699 $this->mOutput
->addImage( $nt->getDBkey() );
1701 wfProfileOut( "$fname-image" );
1705 if ( $ns == NS_CATEGORY
) {
1706 wfProfileIn( "$fname-category" );
1707 $s = rtrim($s . "\n"); # bug 87
1710 $sortkey = $this->getDefaultSort();
1714 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1715 $sortkey = str_replace( "\n", '', $sortkey );
1716 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1717 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1720 * Strip the whitespace Category links produce, see bug 87
1721 * @todo We might want to use trim($tmp, "\n") here.
1723 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1725 wfProfileOut( "$fname-category" );
1730 # Self-link checking
1731 if( $nt->getFragment() === '' ) {
1732 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1733 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1738 # Special and Media are pseudo-namespaces; no pages actually exist in them
1739 if( $ns == NS_MEDIA
) {
1740 $link = $sk->makeMediaLinkObj( $nt, $text );
1741 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1742 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1743 $this->mOutput
->addImage( $nt->getDBkey() );
1745 } elseif( $ns == NS_SPECIAL
) {
1746 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1747 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1749 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1752 } elseif( $ns == NS_IMAGE
) {
1753 $img = wfFindFile( $nt );
1755 // Force a blue link if the file exists; may be a remote
1756 // upload on the shared repository, and we want to see its
1757 // auto-generated page.
1758 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1759 $this->mOutput
->addLink( $nt );
1763 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1765 wfProfileOut( $fname );
1770 * Make a link placeholder. The text returned can be later resolved to a real link with
1771 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1772 * parsing of interwiki links, and secondly to allow all existence checks and
1773 * article length checks (for stub links) to be bundled into a single query.
1776 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1777 wfProfileIn( __METHOD__
);
1778 if ( ! is_object($nt) ) {
1780 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1782 # Separate the link trail from the rest of the link
1783 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1785 if ( $nt->isExternal() ) {
1786 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1787 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1788 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1790 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1791 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1792 $this->mLinkHolders
['queries'][] = $query;
1793 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1794 $this->mLinkHolders
['titles'][] = $nt;
1796 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1799 wfProfileOut( __METHOD__
);
1804 * Render a forced-blue link inline; protect against double expansion of
1805 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1806 * Since this little disaster has to split off the trail text to avoid
1807 * breaking URLs in the following text without breaking trails on the
1808 * wiki links, it's been made into a horrible function.
1811 * @param string $text
1812 * @param string $query
1813 * @param string $trail
1814 * @param string $prefix
1815 * @return string HTML-wikitext mix oh yuck
1817 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1818 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1819 $sk = $this->mOptions
->getSkin();
1820 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1821 return $this->armorLinks( $link ) . $trail;
1825 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1826 * going to go through further parsing steps before inline URL expansion.
1828 * In particular this is important when using action=render, which causes
1829 * full URLs to be included.
1831 * Oh man I hate our multi-layer parser!
1833 * @param string more-or-less HTML
1834 * @return string less-or-more HTML with NOPARSE bits
1836 function armorLinks( $text ) {
1837 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1838 "{$this->mUniqPrefix}NOPARSE$1", $text );
1842 * Return true if subpage links should be expanded on this page.
1845 function areSubpagesAllowed() {
1846 # Some namespaces don't allow subpages
1847 global $wgNamespacesWithSubpages;
1848 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1852 * Handle link to subpage if necessary
1853 * @param string $target the source of the link
1854 * @param string &$text the link text, modified as necessary
1855 * @return string the full name of the link
1858 function maybeDoSubpageLink($target, &$text) {
1861 # :Foobar -- override special treatment of prefix (images, language links)
1862 # /Foobar -- convert to CurrentPage/Foobar
1863 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1864 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1865 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1867 $fname = 'Parser::maybeDoSubpageLink';
1868 wfProfileIn( $fname );
1869 $ret = $target; # default return value is no change
1871 # Some namespaces don't allow subpages,
1872 # so only perform processing if subpages are allowed
1873 if( $this->areSubpagesAllowed() ) {
1874 $hash = strpos( $target, '#' );
1875 if( $hash !== false ) {
1876 $suffix = substr( $target, $hash );
1877 $target = substr( $target, 0, $hash );
1882 $target = trim( $target );
1883 # Look at the first character
1884 if( $target != '' && $target{0} == '/' ) {
1885 # / at end means we don't want the slash to be shown
1887 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1888 if( $trailingSlashes ) {
1889 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1891 $noslash = substr( $target, 1 );
1894 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1895 if( '' === $text ) {
1896 $text = $target . $suffix;
1897 } # this might be changed for ugliness reasons
1899 # check for .. subpage backlinks
1901 $nodotdot = $target;
1902 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1904 $nodotdot = substr( $nodotdot, 3 );
1906 if($dotdotcount > 0) {
1907 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1908 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1909 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1910 # / at the end means don't show full path
1911 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1912 $nodotdot = substr( $nodotdot, 0, -1 );
1913 if( '' === $text ) {
1914 $text = $nodotdot . $suffix;
1917 $nodotdot = trim( $nodotdot );
1918 if( $nodotdot != '' ) {
1919 $ret .= '/' . $nodotdot;
1927 wfProfileOut( $fname );
1932 * Used by doBlockLevels()
1935 /* private */ function closeParagraph() {
1937 if ( '' != $this->mLastSection
) {
1938 $result = '</' . $this->mLastSection
. ">\n";
1940 $this->mInPre
= false;
1941 $this->mLastSection
= '';
1944 # getCommon() returns the length of the longest common substring
1945 # of both arguments, starting at the beginning of both.
1947 /* private */ function getCommon( $st1, $st2 ) {
1948 $fl = strlen( $st1 );
1949 $shorter = strlen( $st2 );
1950 if ( $fl < $shorter ) { $shorter = $fl; }
1952 for ( $i = 0; $i < $shorter; ++
$i ) {
1953 if ( $st1{$i} != $st2{$i} ) { break; }
1957 # These next three functions open, continue, and close the list
1958 # element appropriate to the prefix character passed into them.
1960 /* private */ function openList( $char ) {
1961 $result = $this->closeParagraph();
1963 if ( '*' == $char ) { $result .= '<ul><li>'; }
1964 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1965 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1966 else if ( ';' == $char ) {
1967 $result .= '<dl><dt>';
1968 $this->mDTopen
= true;
1970 else { $result = '<!-- ERR 1 -->'; }
1975 /* private */ function nextItem( $char ) {
1976 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1977 else if ( ':' == $char ||
';' == $char ) {
1979 if ( $this->mDTopen
) { $close = '</dt>'; }
1980 if ( ';' == $char ) {
1981 $this->mDTopen
= true;
1982 return $close . '<dt>';
1984 $this->mDTopen
= false;
1985 return $close . '<dd>';
1988 return '<!-- ERR 2 -->';
1991 /* private */ function closeList( $char ) {
1992 if ( '*' == $char ) { $text = '</li></ul>'; }
1993 else if ( '#' == $char ) { $text = '</li></ol>'; }
1994 else if ( ':' == $char ) {
1995 if ( $this->mDTopen
) {
1996 $this->mDTopen
= false;
1997 $text = '</dt></dl>';
1999 $text = '</dd></dl>';
2002 else { return '<!-- ERR 3 -->'; }
2008 * Make lists from lines starting with ':', '*', '#', etc.
2011 * @return string the lists rendered as HTML
2013 function doBlockLevels( $text, $linestart ) {
2014 $fname = 'Parser::doBlockLevels';
2015 wfProfileIn( $fname );
2017 # Parsing through the text line by line. The main thing
2018 # happening here is handling of block-level elements p, pre,
2019 # and making lists from lines starting with * # : etc.
2021 $textLines = explode( "\n", $text );
2023 $lastPrefix = $output = '';
2024 $this->mDTopen
= $inBlockElem = false;
2026 $paragraphStack = false;
2028 if ( !$linestart ) {
2029 $output .= array_shift( $textLines );
2031 foreach ( $textLines as $oLine ) {
2032 $lastPrefixLength = strlen( $lastPrefix );
2033 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2034 $preOpenMatch = preg_match('/<pre/i', $oLine );
2035 if ( !$this->mInPre
) {
2036 # Multiple prefixes may abut each other for nested lists.
2037 $prefixLength = strspn( $oLine, '*#:;' );
2038 $pref = substr( $oLine, 0, $prefixLength );
2041 $pref2 = str_replace( ';', ':', $pref );
2042 $t = substr( $oLine, $prefixLength );
2043 $this->mInPre
= !empty($preOpenMatch);
2045 # Don't interpret any other prefixes in preformatted text
2047 $pref = $pref2 = '';
2052 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2053 # Same as the last item, so no need to deal with nesting or opening stuff
2054 $output .= $this->nextItem( substr( $pref, -1 ) );
2055 $paragraphStack = false;
2057 if ( substr( $pref, -1 ) == ';') {
2058 # The one nasty exception: definition lists work like this:
2059 # ; title : definition text
2060 # So we check for : in the remainder text to split up the
2061 # title and definition, without b0rking links.
2063 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2065 $output .= $term . $this->nextItem( ':' );
2068 } elseif( $prefixLength ||
$lastPrefixLength ) {
2069 # Either open or close a level...
2070 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2071 $paragraphStack = false;
2073 while( $commonPrefixLength < $lastPrefixLength ) {
2074 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2075 --$lastPrefixLength;
2077 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2078 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2080 while ( $prefixLength > $commonPrefixLength ) {
2081 $char = substr( $pref, $commonPrefixLength, 1 );
2082 $output .= $this->openList( $char );
2084 if ( ';' == $char ) {
2085 # FIXME: This is dupe of code above
2086 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2088 $output .= $term . $this->nextItem( ':' );
2091 ++
$commonPrefixLength;
2093 $lastPrefix = $pref2;
2095 if( 0 == $prefixLength ) {
2096 wfProfileIn( "$fname-paragraph" );
2097 # No prefix (not in list)--go to paragraph mode
2098 // XXX: use a stack for nestable elements like span, table and div
2099 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2100 $closematch = preg_match(
2101 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2102 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2103 if ( $openmatch or $closematch ) {
2104 $paragraphStack = false;
2105 #Â TODO bug 5718: paragraph closed
2106 $output .= $this->closeParagraph();
2107 if ( $preOpenMatch and !$preCloseMatch ) {
2108 $this->mInPre
= true;
2110 if ( $closematch ) {
2111 $inBlockElem = false;
2113 $inBlockElem = true;
2115 } else if ( !$inBlockElem && !$this->mInPre
) {
2116 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2118 if ($this->mLastSection
!= 'pre') {
2119 $paragraphStack = false;
2120 $output .= $this->closeParagraph().'<pre>';
2121 $this->mLastSection
= 'pre';
2123 $t = substr( $t, 1 );
2126 if ( '' == trim($t) ) {
2127 if ( $paragraphStack ) {
2128 $output .= $paragraphStack.'<br />';
2129 $paragraphStack = false;
2130 $this->mLastSection
= 'p';
2132 if ($this->mLastSection
!= 'p' ) {
2133 $output .= $this->closeParagraph();
2134 $this->mLastSection
= '';
2135 $paragraphStack = '<p>';
2137 $paragraphStack = '</p><p>';
2141 if ( $paragraphStack ) {
2142 $output .= $paragraphStack;
2143 $paragraphStack = false;
2144 $this->mLastSection
= 'p';
2145 } else if ($this->mLastSection
!= 'p') {
2146 $output .= $this->closeParagraph().'<p>';
2147 $this->mLastSection
= 'p';
2152 wfProfileOut( "$fname-paragraph" );
2154 // somewhere above we forget to get out of pre block (bug 785)
2155 if($preCloseMatch && $this->mInPre
) {
2156 $this->mInPre
= false;
2158 if ($paragraphStack === false) {
2162 while ( $prefixLength ) {
2163 $output .= $this->closeList( $pref2{$prefixLength-1} );
2166 if ( '' != $this->mLastSection
) {
2167 $output .= '</' . $this->mLastSection
. '>';
2168 $this->mLastSection
= '';
2171 wfProfileOut( $fname );
2176 * Split up a string on ':', ignoring any occurences inside tags
2177 * to prevent illegal overlapping.
2178 * @param string $str the string to split
2179 * @param string &$before set to everything before the ':'
2180 * @param string &$after set to everything after the ':'
2181 * return string the position of the ':', or false if none found
2183 function findColonNoLinks($str, &$before, &$after) {
2184 $fname = 'Parser::findColonNoLinks';
2185 wfProfileIn( $fname );
2187 $pos = strpos( $str, ':' );
2188 if( $pos === false ) {
2190 wfProfileOut( $fname );
2194 $lt = strpos( $str, '<' );
2195 if( $lt === false ||
$lt > $pos ) {
2196 // Easy; no tag nesting to worry about
2197 $before = substr( $str, 0, $pos );
2198 $after = substr( $str, $pos+
1 );
2199 wfProfileOut( $fname );
2203 // Ugly state machine to walk through avoiding tags.
2204 $state = self
::COLON_STATE_TEXT
;
2206 $len = strlen( $str );
2207 for( $i = 0; $i < $len; $i++
) {
2211 // (Using the number is a performance hack for common cases)
2212 case 0: // self::COLON_STATE_TEXT:
2215 // Could be either a <start> tag or an </end> tag
2216 $state = self
::COLON_STATE_TAGSTART
;
2221 $before = substr( $str, 0, $i );
2222 $after = substr( $str, $i +
1 );
2223 wfProfileOut( $fname );
2226 // Embedded in a tag; don't break it.
2229 // Skip ahead looking for something interesting
2230 $colon = strpos( $str, ':', $i );
2231 if( $colon === false ) {
2232 // Nothing else interesting
2233 wfProfileOut( $fname );
2236 $lt = strpos( $str, '<', $i );
2237 if( $stack === 0 ) {
2238 if( $lt === false ||
$colon < $lt ) {
2240 $before = substr( $str, 0, $colon );
2241 $after = substr( $str, $colon +
1 );
2242 wfProfileOut( $fname );
2246 if( $lt === false ) {
2247 // Nothing else interesting to find; abort!
2248 // We're nested, but there's no close tags left. Abort!
2251 // Skip ahead to next tag start
2253 $state = self
::COLON_STATE_TAGSTART
;
2256 case 1: // self::COLON_STATE_TAG:
2261 $state = self
::COLON_STATE_TEXT
;
2264 // Slash may be followed by >?
2265 $state = self
::COLON_STATE_TAGSLASH
;
2271 case 2: // self::COLON_STATE_TAGSTART:
2274 $state = self
::COLON_STATE_CLOSETAG
;
2277 $state = self
::COLON_STATE_COMMENT
;
2280 // Illegal early close? This shouldn't happen D:
2281 $state = self
::COLON_STATE_TEXT
;
2284 $state = self
::COLON_STATE_TAG
;
2287 case 3: // self::COLON_STATE_CLOSETAG:
2292 wfDebug( "Invalid input in $fname; too many close tags\n" );
2293 wfProfileOut( $fname );
2296 $state = self
::COLON_STATE_TEXT
;
2299 case self
::COLON_STATE_TAGSLASH
:
2301 // Yes, a self-closed tag <blah/>
2302 $state = self
::COLON_STATE_TEXT
;
2304 // Probably we're jumping the gun, and this is an attribute
2305 $state = self
::COLON_STATE_TAG
;
2308 case 5: // self::COLON_STATE_COMMENT:
2310 $state = self
::COLON_STATE_COMMENTDASH
;
2313 case self
::COLON_STATE_COMMENTDASH
:
2315 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2317 $state = self
::COLON_STATE_COMMENT
;
2320 case self
::COLON_STATE_COMMENTDASHDASH
:
2322 $state = self
::COLON_STATE_TEXT
;
2324 $state = self
::COLON_STATE_COMMENT
;
2328 throw new MWException( "State machine error in $fname" );
2332 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2335 wfProfileOut( $fname );
2340 * Return value of a magic variable (like PAGENAME)
2344 function getVariableValue( $index ) {
2345 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2348 * Some of these require message or data lookups and can be
2349 * expensive to check many times.
2351 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2352 if ( isset( $this->mVarCache
[$index] ) ) {
2353 return $this->mVarCache
[$index];
2357 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2358 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2361 global $wgLocaltimezone;
2362 if ( isset( $wgLocaltimezone ) ) {
2363 $oldtz = getenv( 'TZ' );
2364 putenv( 'TZ='.$wgLocaltimezone );
2367 wfSuppressWarnings(); // E_STRICT system time bitching
2368 $localTimestamp = date( 'YmdHis', $ts );
2369 $localMonth = date( 'm', $ts );
2370 $localMonthName = date( 'n', $ts );
2371 $localDay = date( 'j', $ts );
2372 $localDay2 = date( 'd', $ts );
2373 $localDayOfWeek = date( 'w', $ts );
2374 $localWeek = date( 'W', $ts );
2375 $localYear = date( 'Y', $ts );
2376 $localHour = date( 'H', $ts );
2377 if ( isset( $wgLocaltimezone ) ) {
2378 putenv( 'TZ='.$oldtz );
2380 wfRestoreWarnings();
2383 case 'currentmonth':
2384 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2385 case 'currentmonthname':
2386 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2387 case 'currentmonthnamegen':
2388 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2389 case 'currentmonthabbrev':
2390 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2392 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2394 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2396 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2397 case 'localmonthname':
2398 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2399 case 'localmonthnamegen':
2400 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2401 case 'localmonthabbrev':
2402 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2404 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2406 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2408 return wfEscapeWikiText( $this->mTitle
->getText() );
2410 return $this->mTitle
->getPartialURL();
2411 case 'fullpagename':
2412 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2413 case 'fullpagenamee':
2414 return $this->mTitle
->getPrefixedURL();
2416 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2417 case 'subpagenamee':
2418 return $this->mTitle
->getSubpageUrlForm();
2419 case 'basepagename':
2420 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2421 case 'basepagenamee':
2422 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2423 case 'talkpagename':
2424 if( $this->mTitle
->canTalk() ) {
2425 $talkPage = $this->mTitle
->getTalkPage();
2426 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2430 case 'talkpagenamee':
2431 if( $this->mTitle
->canTalk() ) {
2432 $talkPage = $this->mTitle
->getTalkPage();
2433 return $talkPage->getPrefixedUrl();
2437 case 'subjectpagename':
2438 $subjPage = $this->mTitle
->getSubjectPage();
2439 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2440 case 'subjectpagenamee':
2441 $subjPage = $this->mTitle
->getSubjectPage();
2442 return $subjPage->getPrefixedUrl();
2444 // Let the edit saving system know we should parse the page
2445 // *after* a revision ID has been assigned.
2446 $this->mOutput
->setFlag( 'vary-revision' );
2447 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2448 return $this->mRevisionId
;
2450 // Let the edit saving system know we should parse the page
2451 // *after* a revision ID has been assigned. This is for null edits.
2452 $this->mOutput
->setFlag( 'vary-revision' );
2453 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2454 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2455 case 'revisionday2':
2456 // Let the edit saving system know we should parse the page
2457 // *after* a revision ID has been assigned. This is for null edits.
2458 $this->mOutput
->setFlag( 'vary-revision' );
2459 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2460 return substr( $this->getRevisionTimestamp(), 6, 2 );
2461 case 'revisionmonth':
2462 // Let the edit saving system know we should parse the page
2463 // *after* a revision ID has been assigned. This is for null edits.
2464 $this->mOutput
->setFlag( 'vary-revision' );
2465 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2466 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2467 case 'revisionyear':
2468 // Let the edit saving system know we should parse the page
2469 // *after* a revision ID has been assigned. This is for null edits.
2470 $this->mOutput
->setFlag( 'vary-revision' );
2471 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2472 return substr( $this->getRevisionTimestamp(), 0, 4 );
2473 case 'revisiontimestamp':
2474 // Let the edit saving system know we should parse the page
2475 // *after* a revision ID has been assigned. This is for null edits.
2476 $this->mOutput
->setFlag( 'vary-revision' );
2477 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2478 return $this->getRevisionTimestamp();
2480 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2482 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2484 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2486 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2487 case 'subjectspace':
2488 return $this->mTitle
->getSubjectNsText();
2489 case 'subjectspacee':
2490 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2491 case 'currentdayname':
2492 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2494 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2496 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2498 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2500 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2501 // int to remove the padding
2502 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2504 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2505 case 'localdayname':
2506 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2508 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2510 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2512 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2514 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2515 // int to remove the padding
2516 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2518 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2519 case 'numberofarticles':
2520 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2521 case 'numberoffiles':
2522 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2523 case 'numberofusers':
2524 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2525 case 'numberofpages':
2526 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2527 case 'numberofadmins':
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2529 case 'numberofedits':
2530 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2531 case 'currenttimestamp':
2532 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2533 case 'localtimestamp':
2534 return $this->mVarCache
[$index] = $localTimestamp;
2535 case 'currentversion':
2536 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2542 return $wgServerName;
2544 return $wgScriptPath;
2545 case 'directionmark':
2546 return $wgContLang->getDirMark();
2547 case 'contentlanguage':
2548 global $wgContLanguageCode;
2549 return $wgContLanguageCode;
2552 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2560 * initialise the magic variables (like CURRENTMONTHNAME)
2564 function initialiseVariables() {
2565 $fname = 'Parser::initialiseVariables';
2566 wfProfileIn( $fname );
2567 $variableIDs = MagicWord
::getVariableIDs();
2569 $this->mVariables
= new MagicWordArray( $variableIDs );
2570 wfProfileOut( $fname );
2574 * Preprocess some wikitext and return the document tree.
2575 * This is the ghost of replace_variables().
2577 * @param string $text The text to parse
2578 * @param integer flags Bitwise combination of:
2579 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2580 * included. Default is to assume a direct page view.
2582 * The generated DOM tree must depend only on the input text and the flags.
2583 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2585 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2586 * change in the DOM tree for a given text, must be passed through the section identifier
2587 * in the section edit link and thus back to extractSections().
2589 * The output of this function is currently only cached in process memory, but a persistent
2590 * cache may be implemented at a later date which takes further advantage of these strict
2591 * dependency requirements.
2595 function preprocessToDom ( $text, $flags = 0 ) {
2596 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2601 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2603 public static function splitWhitespace( $s ) {
2604 $ltrimmed = ltrim( $s );
2605 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2606 $trimmed = rtrim( $ltrimmed );
2607 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2609 $w2 = substr( $ltrimmed, -$diff );
2613 return array( $w1, $trimmed, $w2 );
2617 * Replace magic variables, templates, and template arguments
2618 * with the appropriate text. Templates are substituted recursively,
2619 * taking care to avoid infinite loops.
2621 * Note that the substitution depends on value of $mOutputType:
2622 * self::OT_WIKI: only {{subst:}} templates
2623 * self::OT_PREPROCESS: templates but not extension tags
2624 * self::OT_HTML: all templates and extension tags
2626 * @param string $tex The text to transform
2627 * @param PPFrame $frame Object describing the arguments passed to the template
2628 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2631 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2632 # Prevent too big inclusions
2633 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2637 $fname = __METHOD__
;
2638 wfProfileIn( $fname );
2640 if ( $frame === false ) {
2641 $frame = $this->getPreprocessor()->newFrame();
2642 } elseif ( !( $frame instanceof PPFrame
) ) {
2643 throw new MWException( __METHOD__
. ' called using the old argument format' );
2646 $dom = $this->preprocessToDom( $text );
2647 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2648 $text = $frame->expand( $dom, $flags );
2650 wfProfileOut( $fname );
2654 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2655 static function createAssocArgs( $args ) {
2656 $assocArgs = array();
2658 foreach( $args as $arg ) {
2659 $eqpos = strpos( $arg, '=' );
2660 if ( $eqpos === false ) {
2661 $assocArgs[$index++
] = $arg;
2663 $name = trim( substr( $arg, 0, $eqpos ) );
2664 $value = trim( substr( $arg, $eqpos+
1 ) );
2665 if ( $value === false ) {
2668 if ( $name !== false ) {
2669 $assocArgs[$name] = $value;
2678 * Return the text of a template, after recursively
2679 * replacing any variables or templates within the template.
2681 * @param array $piece The parts of the template
2682 * $piece['title']: the title, i.e. the part before the |
2683 * $piece['parts']: the parameter array
2684 * $piece['lineStart']: whether the brace was at the start of a line
2685 * @param PPFrame The current frame, contains template arguments
2686 * @return string the text of the template
2689 function braceSubstitution( $piece, $frame ) {
2690 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2691 $fname = __METHOD__
;
2692 wfProfileIn( $fname );
2693 wfProfileIn( __METHOD__
.'-setup' );
2696 $found = false; # $text has been filled
2697 $nowiki = false; # wiki markup in $text should be escaped
2698 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2699 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2700 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2701 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2703 # Title object, where $text came from
2706 # $part1 is the bit before the first |, and must contain only title characters.
2707 # Various prefixes will be stripped from it later.
2708 $titleWithSpaces = $frame->expand( $piece['title'] );
2709 $part1 = trim( $titleWithSpaces );
2712 # Original title text preserved for various purposes
2713 $originalTitle = $part1;
2715 # $args is a list of argument nodes, starting from index 0, not including $part1
2716 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2717 wfProfileOut( __METHOD__
.'-setup' );
2720 wfProfileIn( __METHOD__
.'-modifiers' );
2722 $mwSubst =& MagicWord
::get( 'subst' );
2723 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2724 # One of two possibilities is true:
2725 # 1) Found SUBST but not in the PST phase
2726 # 2) Didn't find SUBST and in the PST phase
2727 # In either case, return without further processing
2728 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2735 if ( !$found && $args->getLength() == 0 ) {
2736 $id = $this->mVariables
->matchStartToEnd( $part1 );
2737 if ( $id !== false ) {
2738 $text = $this->getVariableValue( $id );
2739 if (MagicWord
::getCacheTTL($id)>-1)
2740 $this->mOutput
->mContainsOldMagic
= true;
2745 # MSG, MSGNW and RAW
2748 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2749 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2752 # Remove obsolete MSG:
2753 $mwMsg =& MagicWord
::get( 'msg' );
2754 $mwMsg->matchStartAndRemove( $part1 );
2758 $mwRaw =& MagicWord
::get( 'raw' );
2759 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2760 $forceRawInterwiki = true;
2763 wfProfileOut( __METHOD__
.'-modifiers' );
2767 wfProfileIn( __METHOD__
. '-pfunc' );
2769 $colonPos = strpos( $part1, ':' );
2770 if ( $colonPos !== false ) {
2771 # Case sensitive functions
2772 $function = substr( $part1, 0, $colonPos );
2773 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2774 $function = $this->mFunctionSynonyms
[1][$function];
2776 # Case insensitive functions
2777 $function = strtolower( $function );
2778 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2779 $function = $this->mFunctionSynonyms
[0][$function];
2785 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2786 $initialArgs = array( &$this );
2787 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2788 if ( $flags & SFH_OBJECT_ARGS
) {
2789 # Add a frame parameter, and pass the arguments as an array
2790 $allArgs = $initialArgs;
2791 $allArgs[] = $frame;
2792 for ( $i = 0; $i < $args->getLength(); $i++
) {
2793 $funcArgs[] = $args->item( $i );
2795 $allArgs[] = $funcArgs;
2797 # Convert arguments to plain text
2798 for ( $i = 0; $i < $args->getLength(); $i++
) {
2799 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2801 $allArgs = array_merge( $initialArgs, $funcArgs );
2804 # Workaround for PHP bug 35229 and similar
2805 if ( !is_callable( $callback ) ) {
2806 throw new MWException( "Tag hook for $name is not callable\n" );
2808 $result = call_user_func_array( $callback, $allArgs );
2811 if ( is_array( $result ) ) {
2812 if ( isset( $result[0] ) ) {
2814 unset( $result[0] );
2817 // Extract flags into the local scope
2818 // This allows callers to set flags such as nowiki, found, etc.
2825 wfProfileOut( __METHOD__
. '-pfunc' );
2828 # Finish mangling title and then check for loops.
2829 # Set $title to a Title object and $titleText to the PDBK
2832 # Split the title into page and subpage
2834 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2835 if ($subpage !== '') {
2836 $ns = $this->mTitle
->getNamespace();
2838 $title = Title
::newFromText( $part1, $ns );
2840 $titleText = $title->getPrefixedText();
2841 # Check for language variants if the template is not found
2842 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2843 $wgContLang->findVariantLink($part1, $title);
2845 # Do infinite loop check
2846 if ( !$frame->loopCheck( $title ) ) {
2848 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2849 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2851 # Do recursion depth check
2852 $limit = $this->mOptions
->getMaxTemplateDepth();
2853 if ( $frame->depth
>= $limit ) {
2855 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2860 # Load from database
2861 if ( !$found && $title ) {
2862 wfProfileIn( __METHOD__
. '-loadtpl' );
2863 if ( !$title->isExternal() ) {
2864 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2865 $text = SpecialPage
::capturePath( $title );
2866 if ( is_string( $text ) ) {
2869 $this->disableCache();
2871 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2872 $found = false; //access denied
2873 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2875 list( $text, $title ) = $this->getTemplateDom( $title );
2876 if ( $text !== false ) {
2882 # If the title is valid but undisplayable, make a link to it
2883 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2884 $text = "[[:$titleText]]";
2887 } elseif ( $title->isTrans() ) {
2888 // Interwiki transclusion
2889 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2890 $text = $this->interwikiTransclude( $title, 'render' );
2893 $text = $this->interwikiTransclude( $title, 'raw' );
2894 // Preprocess it like a template
2895 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2900 wfProfileOut( __METHOD__
. '-loadtpl' );
2903 # If we haven't found text to substitute by now, we're done
2904 # Recover the source wikitext and return it
2906 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2907 wfProfileOut( $fname );
2908 return array( 'object' => $text );
2911 # Expand DOM-style return values in a child frame
2912 if ( $isChildObj ) {
2913 # Clean up argument array
2914 $newFrame = $frame->newChild( $args, $title );
2917 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2918 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2919 # Expansion is eligible for the empty-frame cache
2920 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2921 $text = $this->mTplExpandCache
[$titleText];
2923 $text = $newFrame->expand( $text );
2924 $this->mTplExpandCache
[$titleText] = $text;
2927 # Uncached expansion
2928 $text = $newFrame->expand( $text );
2931 if ( $isLocalObj && $nowiki ) {
2932 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2933 $isLocalObj = false;
2936 # Replace raw HTML by a placeholder
2937 # Add a blank line preceding, to prevent it from mucking up
2938 # immediately preceding headings
2940 $text = "\n\n" . $this->insertStripItem( $text );
2942 # Escape nowiki-style return values
2943 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2944 $text = wfEscapeWikiText( $text );
2946 # Bug 529: if the template begins with a table or block-level
2947 # element, it should be treated as beginning a new line.
2948 # This behaviour is somewhat controversial.
2949 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2950 $text = "\n" . $text;
2953 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2954 # Error, oversize inclusion
2955 $text = "[[$originalTitle]]" .
2956 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2959 if ( $isLocalObj ) {
2960 $ret = array( 'object' => $text );
2962 $ret = array( 'text' => $text );
2965 wfProfileOut( $fname );
2970 * Get the semi-parsed DOM representation of a template with a given title,
2971 * and its redirect destination title. Cached.
2973 function getTemplateDom( $title ) {
2974 $cacheTitle = $title;
2975 $titleText = $title->getPrefixedDBkey();
2977 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2978 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2979 $title = Title
::makeTitle( $ns, $dbk );
2980 $titleText = $title->getPrefixedDBkey();
2982 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2983 return array( $this->mTplDomCache
[$titleText], $title );
2986 // Cache miss, go to the database
2987 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2989 if ( $text === false ) {
2990 $this->mTplDomCache
[$titleText] = false;
2991 return array( false, $title );
2994 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2995 $this->mTplDomCache
[ $titleText ] = $dom;
2997 if (! $title->equals($cacheTitle)) {
2998 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
2999 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3002 return array( $dom, $title );
3006 * Fetch the unparsed text of a template and register a reference to it.
3008 function fetchTemplateAndTitle( $title ) {
3009 $templateCb = $this->mOptions
->getTemplateCallback();
3010 $stuff = call_user_func( $templateCb, $title );
3011 $text = $stuff['text'];
3012 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3013 if ( isset( $stuff['deps'] ) ) {
3014 foreach ( $stuff['deps'] as $dep ) {
3015 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3018 return array($text,$finalTitle);
3021 function fetchTemplate( $title ) {
3022 $rv = $this->fetchTemplateAndTitle($title);
3027 * Static function to get a template
3028 * Can be overridden via ParserOptions::setTemplateCallback().
3030 static function statelessFetchTemplate( $title ) {
3031 $text = $skip = false;
3032 $finalTitle = $title;
3035 // Loop to fetch the article, with up to 1 redirect
3036 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3037 # Give extensions a chance to select the revision instead
3038 $id = false; // Assume current
3039 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3045 'page_id' => $title->getArticleID(),
3049 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3050 $rev_id = $rev ?
$rev->getId() : 0;
3054 'page_id' => $title->getArticleID(),
3055 'rev_id' => $rev_id );
3058 $text = $rev->getText();
3059 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3061 $message = $wgLang->lcfirst( $title->getText() );
3062 $text = wfMsgForContentNoTrans( $message );
3063 if( wfEmptyMsg( $message, $text ) ) {
3070 if ( $text === false ) {
3074 $finalTitle = $title;
3075 $title = Title
::newFromRedirect( $text );
3079 'finalTitle' => $finalTitle,
3084 * Transclude an interwiki link.
3086 function interwikiTransclude( $title, $action ) {
3087 global $wgEnableScaryTranscluding;
3089 if (!$wgEnableScaryTranscluding)
3090 return wfMsg('scarytranscludedisabled');
3092 $url = $title->getFullUrl( "action=$action" );
3094 if (strlen($url) > 255)
3095 return wfMsg('scarytranscludetoolong');
3096 return $this->fetchScaryTemplateMaybeFromCache($url);
3099 function fetchScaryTemplateMaybeFromCache($url) {
3100 global $wgTranscludeCacheExpiry;
3101 $dbr = wfGetDB(DB_SLAVE
);
3102 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3103 array('tc_url' => $url));
3105 $time = $obj->tc_time
;
3106 $text = $obj->tc_contents
;
3107 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3112 $text = Http
::get($url);
3114 return wfMsg('scarytranscludefailed', $url);
3116 $dbw = wfGetDB(DB_MASTER
);
3117 $dbw->replace('transcache', array('tc_url'), array(
3119 'tc_time' => time(),
3120 'tc_contents' => $text));
3126 * Triple brace replacement -- used for template arguments
3129 function argSubstitution( $piece, $frame ) {
3130 wfProfileIn( __METHOD__
);
3133 $parts = $piece['parts'];
3134 $nameWithSpaces = $frame->expand( $piece['title'] );
3135 $argName = trim( $nameWithSpaces );
3137 $text = $frame->getArgument( $argName );
3138 if ( $text === false && $parts->getLength() > 0
3142 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3145 # No match in frame, use the supplied default
3146 $object = $parts->item( 0 )->getChildren();
3148 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3149 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3152 if ( $text === false && $object === false ) {
3154 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3156 if ( $error !== false ) {
3159 if ( $object !== false ) {
3160 $ret = array( 'object' => $object );
3162 $ret = array( 'text' => $text );
3165 wfProfileOut( __METHOD__
);
3170 * Return the text to be used for a given extension tag.
3171 * This is the ghost of strip().
3173 * @param array $params Associative array of parameters:
3174 * name PPNode for the tag name
3175 * attr PPNode for unparsed text where tag attributes are thought to be
3176 * attributes Optional associative array of parsed attributes
3177 * inner Contents of extension element
3178 * noClose Original text did not have a close tag
3179 * @param PPFrame $frame
3181 function extensionSubstitution( $params, $frame ) {
3182 global $wgRawHtml, $wgContLang;
3184 $name = $frame->expand( $params['name'] );
3185 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3186 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3188 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . $this->mMarkerSuffix
;
3190 if ( $this->ot
['html'] ) {
3191 $name = strtolower( $name );
3193 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3194 if ( isset( $params['attributes'] ) ) {
3195 $attributes = $attributes +
$params['attributes'];
3203 throw new MWException( '<html> extension tag encountered unexpectedly' );
3206 $output = Xml
::escapeTagsOnly( $content );
3209 $output = $wgContLang->armourMath(
3210 MathRenderer
::renderMath( $content, $attributes ) );
3213 $output = $this->renderImageGallery( $content, $attributes );
3216 if( isset( $this->mTagHooks
[$name] ) ) {
3217 # Workaround for PHP bug 35229 and similar
3218 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3219 throw new MWException( "Tag hook for $name is not callable\n" );
3221 $output = call_user_func_array( $this->mTagHooks
[$name],
3222 array( $content, $attributes, $this ) );
3224 throw new MWException( "Invalid call hook $name" );
3228 if ( is_null( $attrText ) ) {
3231 if ( isset( $params['attributes'] ) ) {
3232 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3233 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3234 htmlspecialchars( $attrValue ) . '"';
3237 if ( $content === null ) {
3238 $output = "<$name$attrText/>";
3240 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3241 $output = "<$name$attrText>$content$close";
3245 if ( $name == 'html' ||
$name == 'nowiki' ) {
3246 $this->mStripState
->nowiki
->setPair( $marker, $output );
3248 $this->mStripState
->general
->setPair( $marker, $output );
3254 * Increment an include size counter
3256 * @param string $type The type of expansion
3257 * @param integer $size The size of the text
3258 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3260 function incrementIncludeSize( $type, $size ) {
3261 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3264 $this->mIncludeSizes
[$type] +
= $size;
3270 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3271 * Fills $this->mDoubleUnderscores, returns the modified text
3273 function doDoubleUnderscore( $text ) {
3274 // The position of __TOC__ needs to be recorded
3275 $mw = MagicWord
::get( 'toc' );
3276 if( $mw->match( $text ) ) {
3277 $this->mShowToc
= true;
3278 $this->mForceTocPosition
= true;
3280 // Set a placeholder. At the end we'll fill it in with the TOC.
3281 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3283 // Only keep the first one.
3284 $text = $mw->replace( '', $text );
3287 // Now match and remove the rest of them
3288 $mwa = MagicWord
::getDoubleUnderscoreArray();
3289 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3291 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3292 $this->mOutput
->mNoGallery
= true;
3294 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3295 $this->mShowToc
= false;
3297 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3298 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3300 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3301 if ( $containerCategory ) {
3302 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3304 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3311 * This function accomplishes several tasks:
3312 * 1) Auto-number headings if that option is enabled
3313 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3314 * 3) Add a Table of contents on the top for users who have enabled the option
3315 * 4) Auto-anchor headings
3317 * It loops through all headlines, collects the necessary data, then splits up the
3318 * string and re-inserts the newly formatted headlines.
3320 * @param string $text
3321 * @param boolean $isMain
3324 function formatHeadings( $text, $isMain=true ) {
3325 global $wgMaxTocLevel, $wgContLang;
3327 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3328 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3331 $showEditLink = $this->mOptions
->getEditSection();
3334 # Inhibit editsection links if requested in the page
3335 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3339 # Get all headlines for numbering them and adding funky stuff like [edit]
3340 # links - this is for later, but we need the number of headlines right now
3342 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3344 # if there are fewer than 4 headlines in the article, do not show TOC
3345 # unless it's been explicitly enabled.
3346 $enoughToc = $this->mShowToc
&&
3347 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3349 # Allow user to stipulate that a page should have a "new section"
3350 # link added via __NEWSECTIONLINK__
3351 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3352 $this->mOutput
->setNewSection( true );
3355 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3356 # override above conditions and always show TOC above first header
3357 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3358 $this->mShowToc
= true;
3362 # We need this to perform operations on the HTML
3363 $sk = $this->mOptions
->getSkin();
3369 # Ugh .. the TOC should have neat indentation levels which can be
3370 # passed to the skin functions. These are determined here
3374 $sublevelCount = array();
3375 $levelCount = array();
3381 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3382 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3385 foreach( $matches[3] as $headline ) {
3386 $isTemplate = false;
3388 $sectionIndex = false;
3390 $markerMatches = array();
3391 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3392 $serial = $markerMatches[1];
3393 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3394 $isTemplate = ($titleText != $baseTitleText);
3395 $headline = preg_replace("/^$markerRegex/", "", $headline);
3399 $prevlevel = $level;
3400 $prevtoclevel = $toclevel;
3402 $level = $matches[1][$headlineCount];
3404 if( $doNumberHeadings ||
$enoughToc ) {
3406 if ( $level > $prevlevel ) {
3407 # Increase TOC level
3409 $sublevelCount[$toclevel] = 0;
3410 if( $toclevel<$wgMaxTocLevel ) {
3411 $prevtoclevel = $toclevel;
3412 $toc .= $sk->tocIndent();
3416 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3417 # Decrease TOC level, find level to jump to
3419 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3420 # Can only go down to level 1
3423 for ($i = $toclevel; $i > 0; $i--) {
3424 if ( $levelCount[$i] == $level ) {
3425 # Found last matching level
3429 elseif ( $levelCount[$i] < $level ) {
3430 # Found first matching level below current level
3436 if( $toclevel<$wgMaxTocLevel ) {
3437 if($prevtoclevel < $wgMaxTocLevel) {
3438 # Unindent only if the previous toc level was shown :p
3439 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3441 $toc .= $sk->tocLineEnd();
3446 # No change in level, end TOC line
3447 if( $toclevel<$wgMaxTocLevel ) {
3448 $toc .= $sk->tocLineEnd();
3452 $levelCount[$toclevel] = $level;
3454 # count number of headlines for each level
3455 @$sublevelCount[$toclevel]++
;
3457 for( $i = 1; $i <= $toclevel; $i++
) {
3458 if( !empty( $sublevelCount[$i] ) ) {
3462 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3468 # The safe header is a version of the header text safe to use for links
3469 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3470 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3472 # Remove link placeholders by the link text.
3473 # <!--LINK number-->
3475 # link text with suffix
3476 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3477 "\$this->mLinkHolders['texts'][\$1]",
3479 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3480 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3483 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3484 $tocline = preg_replace(
3485 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3489 $tocline = trim( $tocline );
3491 # For the anchor, strip out HTML-y stuff period
3492 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3493 $safeHeadline = trim( $safeHeadline );
3495 # Save headline for section edit hint before it's escaped
3496 $headlineHint = $safeHeadline;
3497 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3498 # HTML names must be case-insensitively unique (bug 10721)
3499 $arrayKey = strtolower( $safeHeadline );
3501 # XXX : Is $refers[$headlineCount] ever accessed, actually ?
3502 $refers[$headlineCount] = $safeHeadline;
3504 # count how many in assoc. array so we can track dupes in anchors
3505 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3506 $refcount[$headlineCount] = $refers[$arrayKey];
3508 # Don't number the heading if it is the only one (looks silly)
3509 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3510 # the two are different if the line contains a link
3511 $headline=$numbering . ' ' . $headline;
3514 # Create the anchor for linking from the TOC to the section
3515 $anchor = $safeHeadline;
3516 if($refcount[$headlineCount] > 1 ) {
3517 $anchor .= '_' . $refcount[$headlineCount];
3519 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3520 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3521 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3523 # give headline the correct <h#> tag
3524 if( $showEditLink && $sectionIndex !== false ) {
3526 # Put a T flag in the section identifier, to indicate to extractSections()
3527 # that sections inside <includeonly> should be counted.
3528 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3530 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3535 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3540 $this->mOutput
->setSections( $tocraw );
3542 # Never ever show TOC if no headers
3543 if( $numVisible < 1 ) {
3548 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3549 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3551 $toc = $sk->tocList( $toc );
3554 # split up and insert constructed headlines
3556 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3559 foreach( $blocks as $block ) {
3560 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3561 # This is the [edit] link that appears for the top block of text when
3562 # section editing is enabled
3564 # Disabled because it broke block formatting
3565 # For example, a bullet point in the top line
3566 # $full .= $sk->editSectionLink(0);
3569 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3570 # Top anchor now in skin
3574 if( !empty( $head[$i] ) ) {
3579 if( $this->mForceTocPosition
) {
3580 return str_replace( '<!--MWTOC-->', $toc, $full );
3587 * Transform wiki markup when saving a page by doing \r\n -> \n
3588 * conversion, substitting signatures, {{subst:}} templates, etc.
3590 * @param string $text the text to transform
3591 * @param Title &$title the Title object for the current article
3592 * @param User &$user the User object describing the current user
3593 * @param ParserOptions $options parsing options
3594 * @param bool $clearState whether to clear the parser state first
3595 * @return string the altered wiki markup
3598 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3599 $this->mOptions
= $options;
3600 $this->setTitle( $title );
3601 $this->setOutputType( self
::OT_WIKI
);
3603 if ( $clearState ) {
3604 $this->clearState();
3610 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3611 $text = $this->pstPass2( $text, $user );
3612 $text = $this->mStripState
->unstripBoth( $text );
3617 * Pre-save transform helper function
3620 function pstPass2( $text, $user ) {
3621 global $wgContLang, $wgLocaltimezone;
3623 /* Note: This is the timestamp saved as hardcoded wikitext to
3624 * the database, we use $wgContLang here in order to give
3625 * everyone the same signature and use the default one rather
3626 * than the one selected in each user's preferences.
3628 * (see also bug 12815)
3630 $ts = $this->mOptions
->getTimestamp();
3632 if ( isset( $wgLocaltimezone ) ) {
3633 $unixts = wfTimestamp( TS_UNIX
, $ts );
3634 $oldtz = getenv( 'TZ' );
3635 putenv( 'TZ='.$wgLocaltimezone );
3636 $ts = date( 'YmdHis', $unixts );
3637 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3638 putenv( 'TZ='.$oldtz );
3640 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3642 # Variable replacement
3643 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3644 $text = $this->replaceVariables( $text );
3647 $sigText = $this->getUserSig( $user );
3648 $text = strtr( $text, array(
3650 '~~~~' => "$sigText $d",
3654 # Context links: [[|name]] and [[name (context)|]]
3656 global $wgLegalTitleChars;
3657 $tc = "[$wgLegalTitleChars]";
3658 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3660 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3661 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3662 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3664 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3665 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3666 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3668 $t = $this->mTitle
->getText();
3670 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3671 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3672 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3673 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3675 # if there's no context, don't bother duplicating the title
3676 $text = preg_replace( $p2, '[[\\1]]', $text );
3679 # Trim trailing whitespace
3680 $text = rtrim( $text );
3686 * Fetch the user's signature text, if any, and normalize to
3687 * validated, ready-to-insert wikitext.
3693 function getUserSig( &$user ) {
3694 global $wgMaxSigChars;
3696 $username = $user->getName();
3697 $nickname = $user->getOption( 'nickname' );
3698 $nickname = $nickname === '' ?
$username : $nickname;
3700 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3701 $nickname = $username;
3702 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3703 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3704 # Sig. might contain markup; validate this
3705 if( $this->validateSig( $nickname ) !== false ) {
3706 # Validated; clean up (if needed) and return it
3707 return $this->cleanSig( $nickname, true );
3709 # Failed to validate; fall back to the default
3710 $nickname = $username;
3711 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3715 // Make sure nickname doesnt get a sig in a sig
3716 $nickname = $this->cleanSigInSig( $nickname );
3718 # If we're still here, make it a link to the user page
3719 $userText = wfEscapeWikiText( $username );
3720 $nickText = wfEscapeWikiText( $nickname );
3721 if ( $user->isAnon() ) {
3722 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3724 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3729 * Check that the user's signature contains no bad XML
3731 * @param string $text
3732 * @return mixed An expanded string, or false if invalid.
3734 function validateSig( $text ) {
3735 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3739 * Clean up signature text
3741 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3742 * 2) Substitute all transclusions
3744 * @param string $text
3745 * @param $parsing Whether we're cleaning (preferences save) or parsing
3746 * @return string Signature text
3748 function cleanSig( $text, $parsing = false ) {
3751 $this->clearState();
3752 $this->setTitle( $wgTitle );
3753 $this->mOptions
= new ParserOptions
;
3754 $this->setOutputType
= self
::OT_PREPROCESS
;
3757 # FIXME: regex doesn't respect extension tags or nowiki
3758 # => Move this logic to braceSubstitution()
3759 $substWord = MagicWord
::get( 'subst' );
3760 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3761 $substText = '{{' . $substWord->getSynonym( 0 );
3763 $text = preg_replace( $substRegex, $substText, $text );
3764 $text = $this->cleanSigInSig( $text );
3765 $dom = $this->preprocessToDom( $text );
3766 $frame = $this->getPreprocessor()->newFrame();
3767 $text = $frame->expand( $dom );
3770 $text = $this->mStripState
->unstripBoth( $text );
3777 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3778 * @param string $text
3779 * @return string Signature text with /~{3,5}/ removed
3781 function cleanSigInSig( $text ) {
3782 $text = preg_replace( '/~{3,5}/', '', $text );
3787 * Set up some variables which are usually set up in parse()
3788 * so that an external function can call some class members with confidence
3791 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3792 $this->setTitle( $title );
3793 $this->mOptions
= $options;
3794 $this->setOutputType( $outputType );
3795 if ( $clearState ) {
3796 $this->clearState();
3801 * Wrapper for preprocess()
3803 * @param string $text the text to preprocess
3804 * @param ParserOptions $options options
3808 function transformMsg( $text, $options ) {
3810 static $executing = false;
3812 $fname = "Parser::transformMsg";
3814 # Guard against infinite recursion
3820 wfProfileIn($fname);
3821 $text = $this->preprocess( $text, $wgTitle, $options );
3824 wfProfileOut($fname);
3829 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3830 * The callback should have the following form:
3831 * function myParserHook( $text, $params, &$parser ) { ... }
3833 * Transform and return $text. Use $parser for any required context, e.g. use
3834 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3838 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3839 * @param mixed $callback The callback function (and object) to use for the tag
3841 * @return The old value of the mTagHooks array associated with the hook
3843 function setHook( $tag, $callback ) {
3844 $tag = strtolower( $tag );
3845 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3846 $this->mTagHooks
[$tag] = $callback;
3847 if( !in_array( $tag, $this->mStripList
) ) {
3848 $this->mStripList
[] = $tag;
3854 function setTransparentTagHook( $tag, $callback ) {
3855 $tag = strtolower( $tag );
3856 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3857 $this->mTransparentTagHooks
[$tag] = $callback;
3863 * Remove all tag hooks
3865 function clearTagHooks() {
3866 $this->mTagHooks
= array();
3867 $this->mStripList
= $this->mDefaultStripList
;
3871 * Create a function, e.g. {{sum:1|2|3}}
3872 * The callback function should have the form:
3873 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3875 * The callback may either return the text result of the function, or an array with the text
3876 * in element 0, and a number of flags in the other elements. The names of the flags are
3877 * specified in the keys. Valid flags are:
3878 * found The text returned is valid, stop processing the template. This
3880 * nowiki Wiki markup in the return value should be escaped
3881 * isHTML The returned text is HTML, armour it against wikitext transformation
3885 * @param string $id The magic word ID
3886 * @param mixed $callback The callback function (and object) to use
3887 * @param integer $flags a combination of the following flags:
3888 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3890 * @return The old callback function for this name, if any
3892 function setFunctionHook( $id, $callback, $flags = 0 ) {
3893 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3894 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3896 # Add to function cache
3897 $mw = MagicWord
::get( $id );
3899 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3901 $synonyms = $mw->getSynonyms();
3902 $sensitive = intval( $mw->isCaseSensitive() );
3904 foreach ( $synonyms as $syn ) {
3906 if ( !$sensitive ) {
3907 $syn = strtolower( $syn );
3910 if ( !( $flags & SFH_NO_HASH
) ) {
3913 # Remove trailing colon
3914 if ( substr( $syn, -1, 1 ) == ':' ) {
3915 $syn = substr( $syn, 0, -1 );
3917 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3923 * Get all registered function hook identifiers
3927 function getFunctionHooks() {
3928 return array_keys( $this->mFunctionHooks
);
3932 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3933 * Placeholders created in Skin::makeLinkObj()
3934 * Returns an array of link CSS classes, indexed by PDBK.
3935 * $options is a bit field, RLH_FOR_UPDATE to select for update
3937 function replaceLinkHolders( &$text, $options = 0 ) {
3941 $fname = 'Parser::replaceLinkHolders';
3942 wfProfileIn( $fname );
3946 $linkcolour_ids = array();
3947 $sk = $this->mOptions
->getSkin();
3948 $linkCache =& LinkCache
::singleton();
3950 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3951 wfProfileIn( $fname.'-check' );
3952 $dbr = wfGetDB( DB_SLAVE
);
3953 $page = $dbr->tableName( 'page' );
3954 $threshold = $wgUser->getOption('stubthreshold');
3957 asort( $this->mLinkHolders
['namespaces'] );
3962 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3964 $title = $this->mLinkHolders
['titles'][$key];
3966 # Skip invalid entries.
3967 # Result will be ugly, but prevents crash.
3968 if ( is_null( $title ) ) {
3971 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3973 # Check if it's a static known link, e.g. interwiki
3974 if ( $title->isAlwaysKnown() ) {
3975 $colours[$pdbk] = '';
3976 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3977 $colours[$pdbk] = '';
3978 $this->mOutput
->addLink( $title, $id );
3979 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3980 $colours[$pdbk] = 'new';
3981 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
3982 $colours[$pdbk] = 'new';
3984 # Not in the link cache, add it to the query
3985 if ( !isset( $current ) ) {
3987 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect";
3988 if ( $threshold > 0 ) {
3989 $query .= ', page_len';
3991 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3992 } elseif ( $current != $ns ) {
3994 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3999 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4004 if ( $options & RLH_FOR_UPDATE
) {
4005 $query .= ' FOR UPDATE';
4008 $res = $dbr->query( $query, $fname );
4010 # Fetch data and form into an associative array
4011 # non-existent = broken
4012 while ( $s = $dbr->fetchObject($res) ) {
4013 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4014 $pdbk = $title->getPrefixedDBkey();
4015 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4016 $this->mOutput
->addLink( $title, $s->page_id
);
4017 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4018 //add id to the extension todolist
4019 $linkcolour_ids[$s->page_id
] = $pdbk;
4021 //pass an array of page_ids to an extension
4022 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4024 wfProfileOut( $fname.'-check' );
4026 # Do a second query for different language variants of links and categories
4027 if($wgContLang->hasVariants()){
4028 $linkBatch = new LinkBatch();
4029 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4030 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4031 $varCategories = array(); // category replacements oldDBkey => newDBkey
4033 $categories = $this->mOutput
->getCategoryLinks();
4035 // Add variants of links to link batch
4036 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4037 $title = $this->mLinkHolders
['titles'][$key];
4038 if ( is_null( $title ) )
4041 $pdbk = $title->getPrefixedDBkey();
4042 $titleText = $title->getText();
4044 // generate all variants of the link title text
4045 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4047 // if link was not found (in first query), add all variants to query
4048 if ( !isset($colours[$pdbk]) ){
4049 foreach($allTextVariants as $textVariant){
4050 if($textVariant != $titleText){
4051 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4052 if(is_null($variantTitle)) continue;
4053 $linkBatch->addObj( $variantTitle );
4054 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4060 // process categories, check if a category exists in some variant
4061 foreach( $categories as $category ){
4062 $variants = $wgContLang->convertLinkToAllVariants($category);
4063 foreach($variants as $variant){
4064 if($variant != $category){
4065 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4066 if(is_null($variantTitle)) continue;
4067 $linkBatch->addObj( $variantTitle );
4068 $categoryMap[$variant] = $category;
4074 if(!$linkBatch->isEmpty()){
4076 $titleClause = $linkBatch->constructSet('page', $dbr);
4078 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect";
4079 if ( $threshold > 0 ) {
4080 $variantQuery .= ', page_len';
4083 $variantQuery .= " FROM $page WHERE $titleClause";
4084 if ( $options & RLH_FOR_UPDATE
) {
4085 $variantQuery .= ' FOR UPDATE';
4088 $varRes = $dbr->query( $variantQuery, $fname );
4090 // for each found variants, figure out link holders and replace
4091 while ( $s = $dbr->fetchObject($varRes) ) {
4093 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4094 $varPdbk = $variantTitle->getPrefixedDBkey();
4095 $vardbk = $variantTitle->getDBkey();
4097 $holderKeys = array();
4098 if(isset($variantMap[$varPdbk])){
4099 $holderKeys = $variantMap[$varPdbk];
4100 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4101 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4104 // loop over link holders
4105 foreach($holderKeys as $key){
4106 $title = $this->mLinkHolders
['titles'][$key];
4107 if ( is_null( $title ) ) continue;
4109 $pdbk = $title->getPrefixedDBkey();
4111 if(!isset($colours[$pdbk])){
4112 // found link in some of the variants, replace the link holder data
4113 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4114 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4116 // set pdbk and colour
4117 $pdbks[$key] = $varPdbk;
4118 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4119 $linkcolour_ids[$s->page_id
] = $pdbk;
4121 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4124 // check if the object is a variant of a category
4125 if(isset($categoryMap[$vardbk])){
4126 $oldkey = $categoryMap[$vardbk];
4127 if($oldkey != $vardbk)
4128 $varCategories[$oldkey]=$vardbk;
4132 // rebuild the categories in original order (if there are replacements)
4133 if(count($varCategories)>0){
4135 $originalCats = $this->mOutput
->getCategories();
4136 foreach($originalCats as $cat => $sortkey){
4137 // make the replacement
4138 if( array_key_exists($cat,$varCategories) )
4139 $newCats[$varCategories[$cat]] = $sortkey;
4140 else $newCats[$cat] = $sortkey;
4142 $this->mOutput
->setCategoryLinks($newCats);
4147 # Construct search and replace arrays
4148 wfProfileIn( $fname.'-construct' );
4149 $replacePairs = array();
4150 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4151 $pdbk = $pdbks[$key];
4152 $searchkey = "<!--LINK $key-->";
4153 $title = $this->mLinkHolders
['titles'][$key];
4154 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4155 $linkCache->addBadLinkObj( $title );
4156 $colours[$pdbk] = 'new';
4157 $this->mOutput
->addLink( $title, 0 );
4158 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4159 $this->mLinkHolders
['texts'][$key],
4160 $this->mLinkHolders
['queries'][$key] );
4162 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4163 $this->mLinkHolders
['texts'][$key],
4164 $this->mLinkHolders
['queries'][$key] );
4167 $replacer = new HashtableReplacer( $replacePairs, 1 );
4168 wfProfileOut( $fname.'-construct' );
4171 wfProfileIn( $fname.'-replace' );
4172 $text = preg_replace_callback(
4173 '/(<!--LINK .*?-->)/',
4177 wfProfileOut( $fname.'-replace' );
4180 # Now process interwiki link holders
4181 # This is quite a bit simpler than internal links
4182 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4183 wfProfileIn( $fname.'-interwiki' );
4184 # Make interwiki link HTML
4185 $replacePairs = array();
4186 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4187 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4188 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4190 $replacer = new HashtableReplacer( $replacePairs, 1 );
4192 $text = preg_replace_callback(
4193 '/<!--IWLINK (.*?)-->/',
4196 wfProfileOut( $fname.'-interwiki' );
4199 wfProfileOut( $fname );
4204 * Replace <!--LINK--> link placeholders with plain text of links
4205 * (not HTML-formatted).
4206 * @param string $text
4209 function replaceLinkHoldersText( $text ) {
4210 $fname = 'Parser::replaceLinkHoldersText';
4211 wfProfileIn( $fname );
4213 $text = preg_replace_callback(
4214 '/<!--(LINK|IWLINK) (.*?)-->/',
4215 array( &$this, 'replaceLinkHoldersTextCallback' ),
4218 wfProfileOut( $fname );
4223 * @param array $matches
4227 function replaceLinkHoldersTextCallback( $matches ) {
4228 $type = $matches[1];
4230 if( $type == 'LINK' ) {
4231 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4232 return $this->mLinkHolders
['texts'][$key];
4234 } elseif( $type == 'IWLINK' ) {
4235 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4236 return $this->mInterwikiLinkHolders
['texts'][$key];
4243 * Tag hook handler for 'pre'.
4245 function renderPreTag( $text, $attribs ) {
4246 // Backwards-compatibility hack
4247 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4249 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4250 return wfOpenElement( 'pre', $attribs ) .
4251 Xml
::escapeTagsOnly( $content ) .
4256 * Renders an image gallery from a text with one line per image.
4257 * text labels may be given by using |-style alternative text. E.g.
4258 * Image:one.jpg|The number "1"
4259 * Image:tree.jpg|A tree
4260 * given as text will return the HTML of a gallery with two images,
4261 * labeled 'The number "1"' and
4264 function renderImageGallery( $text, $params ) {
4265 $ig = new ImageGallery();
4266 $ig->setContextTitle( $this->mTitle
);
4267 $ig->setShowBytes( false );
4268 $ig->setShowFilename( false );
4269 $ig->setParser( $this );
4270 $ig->setHideBadImages();
4271 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4272 $ig->useSkin( $this->mOptions
->getSkin() );
4273 $ig->mRevisionId
= $this->mRevisionId
;
4275 if( isset( $params['caption'] ) ) {
4276 $caption = $params['caption'];
4277 $caption = htmlspecialchars( $caption );
4278 $caption = $this->replaceInternalLinks( $caption );
4279 $ig->setCaptionHtml( $caption );
4281 if( isset( $params['perrow'] ) ) {
4282 $ig->setPerRow( $params['perrow'] );
4284 if( isset( $params['widths'] ) ) {
4285 $ig->setWidths( $params['widths'] );
4287 if( isset( $params['heights'] ) ) {
4288 $ig->setHeights( $params['heights'] );
4291 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4293 $lines = explode( "\n", $text );
4294 foreach ( $lines as $line ) {
4295 # match lines like these:
4296 # Image:someimage.jpg|This is some image
4298 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4300 if ( count( $matches ) == 0 ) {
4303 $tp = Title
::newFromText( $matches[1] );
4305 if( is_null( $nt ) ) {
4306 # Bogus title. Ignore these so we don't bomb out later.
4309 if ( isset( $matches[3] ) ) {
4310 $label = $matches[3];
4315 $html = $this->recursiveTagParse( trim( $label ) );
4317 $ig->add( $nt, $html );
4319 # Only add real images (bug #5586)
4320 if ( $nt->getNamespace() == NS_IMAGE
) {
4321 $this->mOutput
->addImage( $nt->getDBkey() );
4324 return $ig->toHTML();
4327 function getImageParams( $handler ) {
4329 $handlerClass = get_class( $handler );
4333 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4334 // Initialise static lists
4335 static $internalParamNames = array(
4336 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4337 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4338 'bottom', 'text-bottom' ),
4339 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4340 'upright', 'border' ),
4342 static $internalParamMap;
4343 if ( !$internalParamMap ) {
4344 $internalParamMap = array();
4345 foreach ( $internalParamNames as $type => $names ) {
4346 foreach ( $names as $name ) {
4347 $magicName = str_replace( '-', '_', "img_$name" );
4348 $internalParamMap[$magicName] = array( $type, $name );
4353 // Add handler params
4354 $paramMap = $internalParamMap;
4356 $handlerParamMap = $handler->getParamMap();
4357 foreach ( $handlerParamMap as $magic => $paramName ) {
4358 $paramMap[$magic] = array( 'handler', $paramName );
4361 $this->mImageParams
[$handlerClass] = $paramMap;
4362 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4364 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4368 * Parse image options text and use it to make an image
4370 function makeImage( $title, $options ) {
4371 # @TODO: let the MediaHandler specify its transform parameters
4373 # Check if the options text is of the form "options|alt text"
4375 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4376 # * left no resizing, just left align. label is used for alt= only
4377 # * right same, but right aligned
4378 # * none same, but not aligned
4379 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4380 # * center center the image
4381 # * framed Keep original image size, no magnify-button.
4382 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4383 # * upright reduce width for upright images, rounded to full __0 px
4384 # * border draw a 1px border around the image
4385 # vertical-align values (no % or length right now):
4395 $parts = array_map( 'trim', explode( '|', $options) );
4396 $sk = $this->mOptions
->getSkin();
4398 # Give extensions a chance to select the file revision for us
4399 $skip = $time = false;
4400 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4403 return $sk->makeLinkObj( $title );
4407 $file = wfFindFile( $title, $time );
4408 $handler = $file ?
$file->getHandler() : false;
4410 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4412 # Process the input parameters
4414 $params = array( 'frame' => array(), 'handler' => array(),
4415 'horizAlign' => array(), 'vertAlign' => array() );
4416 foreach( $parts as $part ) {
4417 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4418 if ( isset( $paramMap[$magicName] ) ) {
4419 list( $type, $paramName ) = $paramMap[$magicName];
4420 $params[$type][$paramName] = $value;
4422 // Special case; width and height come in one variable together
4423 if( $type == 'handler' && $paramName == 'width' ) {
4425 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4426 $params[$type]['width'] = intval( $m[1] );
4427 $params[$type]['height'] = intval( $m[2] );
4429 $params[$type]['width'] = intval( $value );
4437 # Process alignment parameters
4438 if ( $params['horizAlign'] ) {
4439 $params['frame']['align'] = key( $params['horizAlign'] );
4441 if ( $params['vertAlign'] ) {
4442 $params['frame']['valign'] = key( $params['vertAlign'] );
4445 # Validate the handler parameters
4447 foreach ( $params['handler'] as $name => $value ) {
4448 if ( !$handler->validateParam( $name, $value ) ) {
4449 unset( $params['handler'][$name] );
4454 # Strip bad stuff out of the alt text
4455 $alt = $this->replaceLinkHoldersText( $caption );
4457 # make sure there are no placeholders in thumbnail attributes
4458 # that are later expanded to html- so expand them now and
4460 $alt = $this->mStripState
->unstripBoth( $alt );
4461 $alt = Sanitizer
::stripAllTags( $alt );
4463 $params['frame']['alt'] = $alt;
4464 $params['frame']['caption'] = $caption;
4466 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4468 # Linker does the rest
4469 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time );
4471 # Give the handler a chance to modify the parser object
4473 $handler->parserTransformHook( $this, $file );
4480 * Set a flag in the output object indicating that the content is dynamic and
4481 * shouldn't be cached.
4483 function disableCache() {
4484 wfDebug( "Parser output marked as uncacheable.\n" );
4485 $this->mOutput
->mCacheTime
= -1;
4489 * Callback from the Sanitizer for expanding items found in HTML attribute
4490 * values, so they can be safely tested and escaped.
4491 * @param string $text
4492 * @param PPFrame $frame
4496 function attributeStripCallback( &$text, $frame = false ) {
4497 $text = $this->replaceVariables( $text, $frame );
4498 $text = $this->mStripState
->unstripBoth( $text );
4507 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4508 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4509 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4515 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4520 * Break wikitext input into sections, and either pull or replace
4521 * some particular section's text.
4523 * External callers should use the getSection and replaceSection methods.
4525 * @param string $text Page wikitext
4526 * @param string $section A section identifier string of the form:
4527 * <flag1> - <flag2> - ... - <section number>
4529 * Currently the only recognised flag is "T", which means the target section number
4530 * was derived during a template inclusion parse, in other words this is a template
4531 * section edit link. If no flags are given, it was an ordinary section edit link.
4532 * This flag is required to avoid a section numbering mismatch when a section is
4533 * enclosed by <includeonly> (bug 6563).
4535 * The section number 0 pulls the text before the first heading; other numbers will
4536 * pull the given section along with its lower-level subsections. If the section is
4537 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4539 * @param string $mode One of "get" or "replace"
4540 * @param string $newText Replacement text for section data.
4541 * @return string for "get", the extracted section text.
4542 * for "replace", the whole page with the section replaced.
4544 private function extractSections( $text, $section, $mode, $newText='' ) {
4546 $this->clearState();
4547 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4548 $this->mOptions
= new ParserOptions
;
4549 $this->setOutputType( self
::OT_WIKI
);
4551 $frame = $this->getPreprocessor()->newFrame();
4553 // Process section extraction flags
4555 $sectionParts = explode( '-', $section );
4556 $sectionIndex = array_pop( $sectionParts );
4557 foreach ( $sectionParts as $part ) {
4558 if ( $part == 'T' ) {
4559 $flags |
= self
::PTD_FOR_INCLUSION
;
4562 // Preprocess the text
4563 $root = $this->preprocessToDom( $text, $flags );
4565 // <h> nodes indicate section breaks
4566 // They can only occur at the top level, so we can find them by iterating the root's children
4567 $node = $root->getFirstChild();
4569 // Find the target section
4570 if ( $sectionIndex == 0 ) {
4571 // Section zero doesn't nest, level=big
4572 $targetLevel = 1000;
4575 if ( $node->getName() == 'h' ) {
4576 $bits = $node->splitHeading();
4577 if ( $bits['i'] == $sectionIndex ) {
4578 $targetLevel = $bits['level'];
4582 if ( $mode == 'replace' ) {
4583 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4585 $node = $node->getNextSibling();
4591 if ( $mode == 'get' ) {
4598 // Find the end of the section, including nested sections
4600 if ( $node->getName() == 'h' ) {
4601 $bits = $node->splitHeading();
4602 $curLevel = $bits['level'];
4603 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4607 if ( $mode == 'get' ) {
4608 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4610 $node = $node->getNextSibling();
4613 // Write out the remainder (in replace mode only)
4614 if ( $mode == 'replace' ) {
4615 // Output the replacement text
4616 // Add two newlines on -- trailing whitespace in $newText is conventionally
4617 // stripped by the editor, so we need both newlines to restore the paragraph gap
4618 $outText .= $newText . "\n\n";
4620 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4621 $node = $node->getNextSibling();
4625 if ( is_string( $outText ) ) {
4626 // Re-insert stripped tags
4627 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4634 * This function returns the text of a section, specified by a number ($section).
4635 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4636 * the first section before any such heading (section 0).
4638 * If a section contains subsections, these are also returned.
4640 * @param string $text text to look in
4641 * @param string $section section identifier
4642 * @param string $deftext default to return if section is not found
4643 * @return string text of the requested section
4645 public function getSection( $text, $section, $deftext='' ) {
4646 return $this->extractSections( $text, $section, "get", $deftext );
4649 public function replaceSection( $oldtext, $section, $text ) {
4650 return $this->extractSections( $oldtext, $section, "replace", $text );
4654 * Get the timestamp associated with the current revision, adjusted for
4655 * the default server-local timestamp
4657 function getRevisionTimestamp() {
4658 if ( is_null( $this->mRevisionTimestamp
) ) {
4659 wfProfileIn( __METHOD__
);
4661 $dbr = wfGetDB( DB_SLAVE
);
4662 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4663 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4665 // Normalize timestamp to internal MW format for timezone processing.
4666 // This has the added side-effect of replacing a null value with
4667 // the current time, which gives us more sensible behavior for
4669 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4671 // The cryptic '' timezone parameter tells to use the site-default
4672 // timezone offset instead of the user settings.
4674 // Since this value will be saved into the parser cache, served
4675 // to other users, and potentially even used inside links and such,
4676 // it needs to be consistent for all visitors.
4677 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4679 wfProfileOut( __METHOD__
);
4681 return $this->mRevisionTimestamp
;
4685 * Mutator for $mDefaultSort
4687 * @param $sort New value
4689 public function setDefaultSort( $sort ) {
4690 $this->mDefaultSort
= $sort;
4694 * Accessor for $mDefaultSort
4695 * Will use the title/prefixed title if none is set
4699 public function getDefaultSort() {
4700 if( $this->mDefaultSort
!== false ) {
4701 return $this->mDefaultSort
;
4703 return $this->mTitle
->getNamespace() == NS_CATEGORY
4704 ?
$this->mTitle
->getText()
4705 : $this->mTitle
->getPrefixedText();
4710 * Try to guess the section anchor name based on a wikitext fragment
4711 * presumably extracted from a heading, for example "Header" from
4714 public function guessSectionNameFromWikiText( $text ) {
4715 # Strip out wikitext links(they break the anchor)
4716 $text = $this->stripSectionName( $text );
4717 $headline = Sanitizer
::decodeCharReferences( $text );
4719 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4720 $headline = trim( $headline );
4721 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4722 $replacearray = array(
4727 array_keys( $replacearray ),
4728 array_values( $replacearray ),
4733 * Strips a text string of wikitext for use in a section anchor
4735 * Accepts a text string and then removes all wikitext from the
4736 * string and leaves only the resultant text (i.e. the result of
4737 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4738 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4739 * to create valid section anchors by mimicing the output of the
4740 * parser when headings are parsed.
4742 * @param $text string Text string to be stripped of wikitext
4743 * for use in a Section anchor
4744 * @return Filtered text string
4746 public function stripSectionName( $text ) {
4747 # Strip internal link markup
4748 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4749 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4751 # Strip external link markup (FIXME: Not Tolerant to blank link text
4752 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4753 # on how many empty links there are on the page - need to figure that out.
4754 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4756 # Parse wikitext quotes (italics & bold)
4757 $text = $this->doQuotes($text);
4760 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4764 function srvus( $text ) {
4765 return $this->testSrvus( $text, $this->mOutputType
);
4769 * strip/replaceVariables/unstrip for preprocessor regression testing
4771 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4772 $this->clearState();
4773 if ( ! ( $title instanceof Title
) ) {
4774 $title = Title
::newFromText( $title );
4776 $this->mTitle
= $title;
4777 $this->mOptions
= $options;
4778 $this->setOutputType( $outputType );
4779 $text = $this->replaceVariables( $text );
4780 $text = $this->mStripState
->unstripBoth( $text );
4781 $text = Sanitizer
::removeHTMLtags( $text );
4785 function testPst( $text, $title, $options ) {
4787 if ( ! ( $title instanceof Title
) ) {
4788 $title = Title
::newFromText( $title );
4790 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4793 function testPreprocess( $text, $title, $options ) {
4794 if ( ! ( $title instanceof Title
) ) {
4795 $title = Title
::newFromText( $title );
4797 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4800 function markerSkipCallback( $s, $callback ) {
4803 while ( $i < strlen( $s ) ) {
4804 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4805 if ( $markerStart === false ) {
4806 $out .= call_user_func( $callback, substr( $s, $i ) );
4809 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4810 $markerEnd = strpos( $s, $this->mMarkerSuffix
, $markerStart );
4811 if ( $markerEnd === false ) {
4812 $out .= substr( $s, $markerStart );
4815 $markerEnd +
= strlen( $this->mMarkerSuffix
);
4816 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4826 * @todo document, briefly.
4827 * @addtogroup Parser
4830 var $general, $nowiki;
4832 function __construct() {
4833 $this->general
= new ReplacementArray
;
4834 $this->nowiki
= new ReplacementArray
;
4837 function unstripGeneral( $text ) {
4838 wfProfileIn( __METHOD__
);
4841 $text = $this->general
->replace( $text );
4842 } while ( $text != $oldText );
4843 wfProfileOut( __METHOD__
);
4847 function unstripNoWiki( $text ) {
4848 wfProfileIn( __METHOD__
);
4851 $text = $this->nowiki
->replace( $text );
4852 } while ( $text != $oldText );
4853 wfProfileOut( __METHOD__
);
4857 function unstripBoth( $text ) {
4858 wfProfileIn( __METHOD__
);
4861 $text = $this->general
->replace( $text );
4862 $text = $this->nowiki
->replace( $text );
4863 } while ( $text != $oldText );
4864 wfProfileOut( __METHOD__
);
4870 * @todo document, briefly.
4871 * @addtogroup Parser
4873 class OnlyIncludeReplacer
{
4876 function replace( $matches ) {
4877 if ( substr( $matches[1], -1 ) == "\n" ) {
4878 $this->output
.= substr( $matches[1], 0, -1 );
4880 $this->output
.= $matches[1];