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;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
107 # These are variables reset at least once per parse regardless of $clearState
108 var $mOptions, // ParserOptions object
109 $mTitle, // Title context, used for self-link rendering and similar things
110 $mOutputType, // Output type, one of the OT_xxx constants
111 $ot, // Shortcut alias, see setOutputType()
112 $mRevisionId, // ID to display in {{REVISIONID}} tags
113 $mRevisionTimestamp, // The timestamp of the specified revision ID
114 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
123 function __construct( $conf = array() ) {
124 $this->mConf
= $conf;
125 $this->mTagHooks
= array();
126 $this->mTransparentTagHooks
= array();
127 $this->mFunctionHooks
= array();
128 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
129 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
130 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
131 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
132 $this->mVarCache
= array();
133 if ( isset( $conf['preprocessorClass'] ) ) {
134 $this->mPreprocessorClass
= $conf['preprocessorClass'];
136 $this->mPreprocessorClass
= 'Preprocessor_DOM';
138 $this->mMarkerIndex
= 0;
139 $this->mFirstCall
= true;
143 * Do various kinds of initialisation on the first call of the parser
145 function firstCallInit() {
146 if ( !$this->mFirstCall
) {
149 $this->mFirstCall
= false;
151 wfProfileIn( __METHOD__
);
153 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
154 CoreParserFunctions
::register( $this );
155 $this->initialiseVariables();
157 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
158 wfProfileOut( __METHOD__
);
166 function clearState() {
167 wfProfileIn( __METHOD__
);
168 if ( $this->mFirstCall
) {
169 $this->firstCallInit();
171 $this->mOutput
= new ParserOutput
;
172 $this->mAutonumber
= 0;
173 $this->mLastSection
= '';
174 $this->mDTopen
= false;
175 $this->mIncludeCount
= array();
176 $this->mStripState
= new StripState
;
177 $this->mArgStack
= false;
178 $this->mInPre
= false;
179 $this->mInterwikiLinkHolders
= array(
183 $this->mLinkHolders
= array(
184 'namespaces' => array(),
186 'queries' => array(),
190 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
193 * Prefix for temporary replacement strings for the multipass parser.
194 * \x07 should never appear in input as it's disallowed in XML.
195 * Using it at the front also gives us a little extra robustness
196 * since it shouldn't match when butted up against identifier-like
199 * Must not consist of all title characters, or else it will change
200 * the behaviour of <nowiki> in a link.
202 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
203 # Changed to \x7f to allow XML double-parsing -- TS
204 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
207 # Clear these on every parse, bug 4549
208 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
210 $this->mShowToc
= true;
211 $this->mForceTocPosition
= false;
212 $this->mIncludeSizes
= array(
216 $this->mPPNodeCount
= 0;
217 $this->mDefaultSort
= false;
218 $this->mHeadings
= array();
219 $this->mDoubleUnderscores
= array();
222 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
223 $this->mPreprocessor
= null;
226 wfRunHooks( 'ParserClearState', array( &$this ) );
227 wfProfileOut( __METHOD__
);
230 function setOutputType( $ot ) {
231 $this->mOutputType
= $ot;
234 'html' => $ot == self
::OT_HTML
,
235 'wiki' => $ot == self
::OT_WIKI
,
236 'pre' => $ot == self
::OT_PREPROCESS
,
241 * Set the context title
243 function setTitle( $t ) {
244 if ( !$t ||
$t instanceof FakeTitle
) {
245 $t = Title
::newFromText( 'NO TITLE' );
247 if ( strval( $t->getFragment() ) !== '' ) {
248 # Strip the fragment to avoid various odd effects
249 $this->mTitle
= clone $t;
250 $this->mTitle
->setFragment( '' );
257 * Accessor for mUniqPrefix.
261 function uniqPrefix() {
262 if( !isset( $this->mUniqPrefix
) ) {
263 // @fixme this is probably *horribly wrong*
264 // LanguageConverter seems to want $wgParser's uniqPrefix, however
265 // if this is called for a parser cache hit, the parser may not
266 // have ever been initialized in the first place.
267 // Not really sure what the heck is supposed to be going on here.
269 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
271 return $this->mUniqPrefix
;
275 * Convert wikitext to HTML
276 * Do not call this function recursively.
278 * @param string $text Text we want to parse
279 * @param Title &$title A title object
280 * @param array $options
281 * @param boolean $linestart
282 * @param boolean $clearState
283 * @param int $revid number to pass in {{REVISIONID}}
284 * @return ParserOutput a ParserOutput
286 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
288 * First pass--just handle <nowiki> sections, pass the rest off
289 * to internalParse() which does all the real work.
292 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
293 $fname = 'Parser::parse-' . wfGetCaller();
294 wfProfileIn( __METHOD__
);
295 wfProfileIn( $fname );
301 $this->mOptions
= $options;
302 $this->setTitle( $title );
303 $oldRevisionId = $this->mRevisionId
;
304 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
305 if( $revid !== null ) {
306 $this->mRevisionId
= $revid;
307 $this->mRevisionTimestamp
= null;
309 $this->setOutputType( self
::OT_HTML
);
310 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
312 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
313 $text = $this->internalParse( $text );
314 $text = $this->mStripState
->unstripGeneral( $text );
316 # Clean up special characters, only run once, next-to-last before doBlockLevels
318 # french spaces, last one Guillemet-left
319 # only if there is something before the space
320 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
321 # french spaces, Guillemet-right
322 '/(\\302\\253) /' => '\\1 ',
323 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
325 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
328 $text = $this->doBlockLevels( $text, $linestart );
330 $this->replaceLinkHolders( $text );
332 # the position of the parserConvert() call should not be changed. it
333 # assumes that the links are all replaced and the only thing left
334 # is the <nowiki> mark.
335 # Side-effects: this calls $this->mOutput->setTitleText()
336 $text = $wgContLang->parserConvert( $text, $this );
338 $text = $this->mStripState
->unstripNoWiki( $text );
340 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
342 //!JF Move to its own function
344 $uniq_prefix = $this->mUniqPrefix
;
346 $elements = array_keys( $this->mTransparentTagHooks
);
347 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
349 foreach( $matches as $marker => $data ) {
350 list( $element, $content, $params, $tag ) = $data;
351 $tagName = strtolower( $element );
352 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
353 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
354 array( $content, $params, $this ) );
358 $this->mStripState
->general
->setPair( $marker, $output );
360 $text = $this->mStripState
->unstripGeneral( $text );
362 $text = Sanitizer
::normalizeCharReferences( $text );
364 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
365 $text = Parser
::tidy($text);
367 # attempt to sanitize at least some nesting problems
368 # (bug #2702 and quite a few others)
370 # ''Something [http://www.cool.com cool''] -->
371 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
372 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
373 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
374 # fix up an anchor inside another anchor, only
375 # at least for a single single nested link (bug 3695)
376 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
377 '\\1\\2</a>\\3</a>\\1\\4</a>',
378 # fix div inside inline elements- doBlockLevels won't wrap a line which
379 # contains a div, so fix it up here; replace
380 # div with escaped text
381 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
382 '\\1\\3<div\\5>\\6</div>\\8\\9',
383 # remove empty italic or bold tag pairs, some
384 # introduced by rules above
385 '/<([bi])><\/\\1>/' => '',
388 $text = preg_replace(
389 array_keys( $tidyregs ),
390 array_values( $tidyregs ),
394 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
396 # Information on include size limits, for the benefit of users who try to skirt them
397 if ( $this->mOptions
->getEnableLimitReport() ) {
398 $max = $this->mOptions
->getMaxIncludeSize();
400 "NewPP limit report\n" .
401 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
402 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
403 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
404 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
405 $text .= "\n<!-- \n$limitReport-->\n";
407 $this->mOutput
->setText( $text );
408 $this->mRevisionId
= $oldRevisionId;
409 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
410 wfProfileOut( $fname );
411 wfProfileOut( __METHOD__
);
413 return $this->mOutput
;
417 * Recursive parser entry point that can be called from an extension tag
420 function recursiveTagParse( $text ) {
421 wfProfileIn( __METHOD__
);
422 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
423 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
424 $text = $this->internalParse( $text );
425 wfProfileOut( __METHOD__
);
430 * Expand templates and variables in the text, producing valid, static wikitext.
431 * Also removes comments.
433 function preprocess( $text, $title, $options, $revid = null ) {
434 wfProfileIn( __METHOD__
);
436 $this->setOutputType( self
::OT_PREPROCESS
);
437 $this->mOptions
= $options;
438 $this->setTitle( $title );
439 if( $revid !== null ) {
440 $this->mRevisionId
= $revid;
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->replaceVariables( $text );
445 $text = $this->mStripState
->unstripBoth( $text );
446 wfProfileOut( __METHOD__
);
451 * Get a random string
456 function getRandomString() {
457 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
460 function &getTitle() { return $this->mTitle
; }
461 function getOptions() { return $this->mOptions
; }
463 function getFunctionLang() {
464 global $wgLang, $wgContLang;
466 $target = $this->mOptions
->getTargetLanguage();
467 if ( $target !== null ) {
470 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
475 * Get a preprocessor object
477 function getPreprocessor() {
478 if ( !isset( $this->mPreprocessor
) ) {
479 $class = $this->mPreprocessorClass
;
480 $this->mPreprocessor
= new $class( $this );
482 return $this->mPreprocessor
;
486 * Replaces all occurrences of HTML-style comments and the given tags
487 * in the text with a random marker and returns the next text. The output
488 * parameter $matches will be an associative array filled with data in
490 * 'UNIQ-xxxxx' => array(
493 * array( 'param' => 'x' ),
494 * '<element param="x">tag content</element>' ) )
496 * @param $elements list of element names. Comments are always extracted.
497 * @param $text Source text string.
498 * @param $uniq_prefix
503 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
508 $taglist = implode( '|', $elements );
509 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
511 while ( '' != $text ) {
512 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
514 if( count( $p ) < 5 ) {
517 if( count( $p ) > 5 ) {
531 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
532 $stripped .= $marker;
534 if ( $close === '/>' ) {
535 // Empty element tag, <tag />
540 if( $element == '!--' ) {
543 $end = "/(<\\/$element\\s*>)/i";
545 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
547 if( count( $q ) < 3 ) {
548 # No end tag -- let it run out to the end of the text.
557 $matches[$marker] = array( $element,
559 Sanitizer
::decodeTagAttributes( $attributes ),
560 "<$element$attributes$close$content$tail" );
566 * Get a list of strippable XML-like elements
568 function getStripList() {
570 $elements = $this->mStripList
;
572 $elements[] = 'html';
574 if( $this->mOptions
->getUseTeX() ) {
575 $elements[] = 'math';
581 * @deprecated use replaceVariables
583 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
588 * Restores pre, math, and other extensions removed by strip()
590 * always call unstripNoWiki() after this one
592 * @deprecated use $this->mStripState->unstrip()
594 function unstrip( $text, $state ) {
595 return $state->unstripGeneral( $text );
599 * Always call this after unstrip() to preserve the order
602 * @deprecated use $this->mStripState->unstrip()
604 function unstripNoWiki( $text, $state ) {
605 return $state->unstripNoWiki( $text );
609 * @deprecated use $this->mStripState->unstripBoth()
611 function unstripForHTML( $text ) {
612 return $this->mStripState
->unstripBoth( $text );
616 * Add an item to the strip state
617 * Returns the unique tag which must be inserted into the stripped text
618 * The tag will be replaced with the original text in unstrip()
622 function insertStripItem( $text ) {
623 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
624 $this->mMarkerIndex++
;
625 $this->mStripState
->general
->setPair( $rnd, $text );
630 * Interface with html tidy, used if $wgUseTidy = true.
631 * If tidy isn't able to correct the markup, the original will be
632 * returned in all its glory with a warning comment appended.
634 * Either the external tidy program or the in-process tidy extension
635 * will be used depending on availability. Override the default
636 * $wgTidyInternal setting to disable the internal if it's not working.
638 * @param string $text Hideous HTML input
639 * @return string Corrected HTML output
643 function tidy( $text ) {
644 global $wgTidyInternal;
645 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
646 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
647 '<head><title>test</title></head><body>'.$text.'</body></html>';
648 if( $wgTidyInternal ) {
649 $correctedtext = Parser
::internalTidy( $wrappedtext );
651 $correctedtext = Parser
::externalTidy( $wrappedtext );
653 if( is_null( $correctedtext ) ) {
654 wfDebug( "Tidy error detected!\n" );
655 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
657 return $correctedtext;
661 * Spawn an external HTML tidy process and get corrected markup back from it.
666 function externalTidy( $text ) {
667 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
668 $fname = 'Parser::externalTidy';
669 wfProfileIn( $fname );
674 $descriptorspec = array(
675 0 => array('pipe', 'r'),
676 1 => array('pipe', 'w'),
677 2 => array('file', wfGetNull(), 'a')
680 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
681 if (is_resource($process)) {
682 // Theoretically, this style of communication could cause a deadlock
683 // here. If the stdout buffer fills up, then writes to stdin could
684 // block. This doesn't appear to happen with tidy, because tidy only
685 // writes to stdout after it's finished reading from stdin. Search
686 // for tidyParseStdin and tidySaveStdout in console/tidy.c
687 fwrite($pipes[0], $text);
689 while (!feof($pipes[1])) {
690 $cleansource .= fgets($pipes[1], 1024);
693 proc_close($process);
696 wfProfileOut( $fname );
698 if( $cleansource == '' && $text != '') {
699 // Some kind of error happened, so we couldn't get the corrected text.
700 // Just give up; we'll use the source text and append a warning.
708 * Use the HTML tidy PECL extension to use the tidy library in-process,
709 * saving the overhead of spawning a new process.
711 * 'pear install tidy' should be able to compile the extension module.
716 function internalTidy( $text ) {
717 global $wgTidyConf, $IP, $wgDebugTidy;
718 $fname = 'Parser::internalTidy';
719 wfProfileIn( $fname );
722 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
723 $tidy->cleanRepair();
724 if( $tidy->getStatus() == 2 ) {
725 // 2 is magic number for fatal error
726 // http://www.php.net/manual/en/function.tidy-get-status.php
729 $cleansource = tidy_get_output( $tidy );
731 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
732 $cleansource .= "<!--\nTidy reports:\n" .
733 str_replace( '-->', '-->', $tidy->errorBuffer
) .
737 wfProfileOut( $fname );
742 * parse the wiki syntax used to render tables
746 function doTableStuff ( $text ) {
747 $fname = 'Parser::doTableStuff';
748 wfProfileIn( $fname );
750 $lines = explode ( "\n" , $text );
751 $td_history = array (); // Is currently a td tag open?
752 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
753 $tr_history = array (); // Is currently a tr tag open?
754 $tr_attributes = array (); // history of tr attributes
755 $has_opened_tr = array(); // Did this table open a <tr> element?
756 $indent_level = 0; // indent level of the table
757 foreach ( $lines as $key => $line )
759 $line = trim ( $line );
761 if( $line == '' ) { // empty line, go to next line
764 $first_character = $line{0};
767 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
768 // First check if we are starting a new table
769 $indent_level = strlen( $matches[1] );
771 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
772 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
774 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
775 array_push ( $td_history , false );
776 array_push ( $last_tag_history , '' );
777 array_push ( $tr_history , false );
778 array_push ( $tr_attributes , '' );
779 array_push ( $has_opened_tr , false );
780 } else if ( count ( $td_history ) == 0 ) {
781 // Don't do any of the following
783 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
784 // We are ending a table
785 $line = '</table>' . substr ( $line , 2 );
786 $last_tag = array_pop ( $last_tag_history );
788 if ( !array_pop ( $has_opened_tr ) ) {
789 $line = "<tr><td></td></tr>{$line}";
792 if ( array_pop ( $tr_history ) ) {
793 $line = "</tr>{$line}";
796 if ( array_pop ( $td_history ) ) {
797 $line = "</{$last_tag}>{$line}";
799 array_pop ( $tr_attributes );
800 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
801 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
802 // Now we have a table row
803 $line = preg_replace( '#^\|-+#', '', $line );
805 // Whats after the tag is now only attributes
806 $attributes = $this->mStripState
->unstripBoth( $line );
807 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
808 array_pop ( $tr_attributes );
809 array_push ( $tr_attributes , $attributes );
812 $last_tag = array_pop ( $last_tag_history );
813 array_pop ( $has_opened_tr );
814 array_push ( $has_opened_tr , true );
816 if ( array_pop ( $tr_history ) ) {
820 if ( array_pop ( $td_history ) ) {
821 $line = "</{$last_tag}>{$line}";
824 $lines[$key] = $line;
825 array_push ( $tr_history , false );
826 array_push ( $td_history , false );
827 array_push ( $last_tag_history , '' );
829 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
830 // This might be cell elements, td, th or captions
831 if ( substr ( $line , 0 , 2 ) == '|+' ) {
832 $first_character = '+';
833 $line = substr ( $line , 1 );
836 $line = substr ( $line , 1 );
838 if ( $first_character == '!' ) {
839 $line = str_replace ( '!!' , '||' , $line );
842 // Split up multiple cells on the same line.
843 // FIXME : This can result in improper nesting of tags processed
844 // by earlier parser steps, but should avoid splitting up eg
845 // attribute values containing literal "||".
846 $cells = StringUtils
::explodeMarkup( '||' , $line );
850 // Loop through each table cell
851 foreach ( $cells as $cell )
854 if ( $first_character != '+' )
856 $tr_after = array_pop ( $tr_attributes );
857 if ( !array_pop ( $tr_history ) ) {
858 $previous = "<tr{$tr_after}>\n";
860 array_push ( $tr_history , true );
861 array_push ( $tr_attributes , '' );
862 array_pop ( $has_opened_tr );
863 array_push ( $has_opened_tr , true );
866 $last_tag = array_pop ( $last_tag_history );
868 if ( array_pop ( $td_history ) ) {
869 $previous = "</{$last_tag}>{$previous}";
872 if ( $first_character == '|' ) {
874 } else if ( $first_character == '!' ) {
876 } else if ( $first_character == '+' ) {
877 $last_tag = 'caption';
882 array_push ( $last_tag_history , $last_tag );
884 // A cell could contain both parameters and data
885 $cell_data = explode ( '|' , $cell , 2 );
887 // Bug 553: Note that a '|' inside an invalid link should not
888 // be mistaken as delimiting cell parameters
889 if ( strpos( $cell_data[0], '[[' ) !== false ) {
890 $cell = "{$previous}<{$last_tag}>{$cell}";
891 } else if ( count ( $cell_data ) == 1 )
892 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
894 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
895 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
896 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
899 $lines[$key] .= $cell;
900 array_push ( $td_history , true );
905 // Closing open td, tr && table
906 while ( count ( $td_history ) > 0 )
908 if ( array_pop ( $td_history ) ) {
911 if ( array_pop ( $tr_history ) ) {
914 if ( !array_pop ( $has_opened_tr ) ) {
915 $lines[] = "<tr><td></td></tr>" ;
918 $lines[] = '</table>' ;
921 $output = implode ( "\n" , $lines ) ;
923 // special case: don't return empty table
924 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
928 wfProfileOut( $fname );
934 * Helper function for parse() that transforms wiki markup into
935 * HTML. Only called for $mOutputType == self::OT_HTML.
939 function internalParse( $text ) {
941 $fname = 'Parser::internalParse';
942 wfProfileIn( $fname );
944 # Hook to suspend the parser in this state
945 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
946 wfProfileOut( $fname );
950 $text = $this->replaceVariables( $text );
951 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
952 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
954 // Tables need to come after variable replacement for things to work
955 // properly; putting them before other transformations should keep
956 // exciting things like link expansions from showing up in surprising
958 $text = $this->doTableStuff( $text );
960 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
962 $text = $this->doDoubleUnderscore( $text );
963 $text = $this->doHeadings( $text );
964 if($this->mOptions
->getUseDynamicDates()) {
965 $df =& DateFormatter
::getInstance();
966 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
968 $text = $this->doAllQuotes( $text );
969 $text = $this->replaceInternalLinks( $text );
970 $text = $this->replaceExternalLinks( $text );
972 # replaceInternalLinks may sometimes leave behind
973 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
974 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
976 $text = $this->doMagicLinks( $text );
977 $text = $this->formatHeadings( $text, $isMain );
979 wfProfileOut( $fname );
984 * Replace special strings like "ISBN xxx" and "RFC xxx" with
985 * magic external links.
989 function doMagicLinks( $text ) {
990 wfProfileIn( __METHOD__
);
991 $text = preg_replace_callback(
993 <a.*?</a> | # Skip link text
994 <.*?> | # Skip stuff inside HTML elements
995 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
996 ISBN\s+(\b # ISBN, capture number as m[2]
997 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
998 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
999 [0-9Xx] # check digit
1001 )!x', array( &$this, 'magicLinkCallback' ), $text );
1002 wfProfileOut( __METHOD__
);
1006 function magicLinkCallback( $m ) {
1007 if ( substr( $m[0], 0, 1 ) == '<' ) {
1010 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1012 $num = strtr( $isbn, array(
1017 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1018 $text = '<a href="' .
1019 $titleObj->escapeLocalUrl() .
1020 "\" class=\"internal\">ISBN $isbn</a>";
1022 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1026 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1028 $urlmsg = 'pubmedurl';
1031 throw new MWException( __METHOD__
.': unrecognised match type "' .
1032 substr($m[0], 0, 20 ) . '"' );
1035 $url = wfMsg( $urlmsg, $id);
1036 $sk = $this->mOptions
->getSkin();
1037 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1038 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1044 * Parse headers and return html
1048 function doHeadings( $text ) {
1049 $fname = 'Parser::doHeadings';
1050 wfProfileIn( $fname );
1051 for ( $i = 6; $i >= 1; --$i ) {
1052 $h = str_repeat( '=', $i );
1053 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1054 "<h$i>\\1</h$i>", $text );
1056 wfProfileOut( $fname );
1061 * Replace single quotes with HTML markup
1063 * @return string the altered text
1065 function doAllQuotes( $text ) {
1066 $fname = 'Parser::doAllQuotes';
1067 wfProfileIn( $fname );
1069 $lines = explode( "\n", $text );
1070 foreach ( $lines as $line ) {
1071 $outtext .= $this->doQuotes ( $line ) . "\n";
1073 $outtext = substr($outtext, 0,-1);
1074 wfProfileOut( $fname );
1079 * Helper function for doAllQuotes()
1081 public function doQuotes( $text ) {
1082 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1083 if ( count( $arr ) == 1 )
1087 # First, do some preliminary work. This may shift some apostrophes from
1088 # being mark-up to being text. It also counts the number of occurrences
1089 # of bold and italics mark-ups.
1093 foreach ( $arr as $r )
1095 if ( ( $i %
2 ) == 1 )
1097 # If there are ever four apostrophes, assume the first is supposed to
1098 # be text, and the remaining three constitute mark-up for bold text.
1099 if ( strlen( $arr[$i] ) == 4 )
1104 # If there are more than 5 apostrophes in a row, assume they're all
1105 # text except for the last 5.
1106 else if ( strlen( $arr[$i] ) > 5 )
1108 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1111 # Count the number of occurrences of bold and italics mark-ups.
1112 # We are not counting sequences of five apostrophes.
1113 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1114 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1115 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1120 # If there is an odd number of both bold and italics, it is likely
1121 # that one of the bold ones was meant to be an apostrophe followed
1122 # by italics. Which one we cannot know for certain, but it is more
1123 # likely to be one that has a single-letter word before it.
1124 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1127 $firstsingleletterword = -1;
1128 $firstmultiletterword = -1;
1130 foreach ( $arr as $r )
1132 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1134 $x1 = substr ($arr[$i-1], -1);
1135 $x2 = substr ($arr[$i-1], -2, 1);
1137 if ($firstspace == -1) $firstspace = $i;
1138 } else if ($x2 == ' ') {
1139 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1141 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1147 # If there is a single-letter word, use it!
1148 if ($firstsingleletterword > -1)
1150 $arr [ $firstsingleletterword ] = "''";
1151 $arr [ $firstsingleletterword-1 ] .= "'";
1153 # If not, but there's a multi-letter word, use that one.
1154 else if ($firstmultiletterword > -1)
1156 $arr [ $firstmultiletterword ] = "''";
1157 $arr [ $firstmultiletterword-1 ] .= "'";
1159 # ... otherwise use the first one that has neither.
1160 # (notice that it is possible for all three to be -1 if, for example,
1161 # there is only one pentuple-apostrophe in the line)
1162 else if ($firstspace > -1)
1164 $arr [ $firstspace ] = "''";
1165 $arr [ $firstspace-1 ] .= "'";
1169 # Now let's actually convert our apostrophic mush to HTML!
1174 foreach ($arr as $r)
1178 if ($state == 'both')
1185 if (strlen ($r) == 2)
1188 { $output .= '</i>'; $state = ''; }
1189 else if ($state == 'bi')
1190 { $output .= '</i>'; $state = 'b'; }
1191 else if ($state == 'ib')
1192 { $output .= '</b></i><b>'; $state = 'b'; }
1193 else if ($state == 'both')
1194 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1195 else # $state can be 'b' or ''
1196 { $output .= '<i>'; $state .= 'i'; }
1198 else if (strlen ($r) == 3)
1201 { $output .= '</b>'; $state = ''; }
1202 else if ($state == 'bi')
1203 { $output .= '</i></b><i>'; $state = 'i'; }
1204 else if ($state == 'ib')
1205 { $output .= '</b>'; $state = 'i'; }
1206 else if ($state == 'both')
1207 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1208 else # $state can be 'i' or ''
1209 { $output .= '<b>'; $state .= 'b'; }
1211 else if (strlen ($r) == 5)
1214 { $output .= '</b><i>'; $state = 'i'; }
1215 else if ($state == 'i')
1216 { $output .= '</i><b>'; $state = 'b'; }
1217 else if ($state == 'bi')
1218 { $output .= '</i></b>'; $state = ''; }
1219 else if ($state == 'ib')
1220 { $output .= '</b></i>'; $state = ''; }
1221 else if ($state == 'both')
1222 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1223 else # ($state == '')
1224 { $buffer = ''; $state = 'both'; }
1229 # Now close all remaining tags. Notice that the order is important.
1230 if ($state == 'b' ||
$state == 'ib')
1232 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1236 # There might be lonely ''''', so make sure we have a buffer
1237 if ($state == 'both' && $buffer)
1238 $output .= '<b><i>'.$buffer.'</i></b>';
1244 * Replace external links
1246 * Note: this is all very hackish and the order of execution matters a lot.
1247 * Make sure to run maintenance/parserTests.php if you change this code.
1251 function replaceExternalLinks( $text ) {
1253 $fname = 'Parser::replaceExternalLinks';
1254 wfProfileIn( $fname );
1256 $sk = $this->mOptions
->getSkin();
1258 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1260 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1263 while ( $i<count( $bits ) ) {
1265 $protocol = $bits[$i++
];
1266 $text = $bits[$i++
];
1267 $trail = $bits[$i++
];
1269 # The characters '<' and '>' (which were escaped by
1270 # removeHTMLtags()) should not be included in
1271 # URLs, per RFC 2396.
1273 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1274 $text = substr($url, $m2[0][1]) . ' ' . $text;
1275 $url = substr($url, 0, $m2[0][1]);
1278 # If the link text is an image URL, replace it with an <img> tag
1279 # This happened by accident in the original parser, but some people used it extensively
1280 $img = $this->maybeMakeExternalImage( $text );
1281 if ( $img !== false ) {
1287 # Set linktype for CSS - if URL==text, link is essentially free
1288 $linktype = ($text == $url) ?
'free' : 'text';
1290 # No link text, e.g. [http://domain.tld/some.link]
1291 if ( $text == '' ) {
1292 # Autonumber if allowed. See bug #5918
1293 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1294 $text = '[' . ++
$this->mAutonumber
. ']';
1295 $linktype = 'autonumber';
1297 # Otherwise just use the URL
1298 $text = htmlspecialchars( $url );
1302 # Have link text, e.g. [http://domain.tld/some.link text]s
1304 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1307 $text = $wgContLang->markNoConversion($text);
1309 $url = Sanitizer
::cleanUrl( $url );
1311 # Process the trail (i.e. everything after this link up until start of the next link),
1312 # replacing any non-bracketed links
1313 $trail = $this->replaceFreeExternalLinks( $trail );
1315 # Use the encoded URL
1316 # This means that users can paste URLs directly into the text
1317 # Funny characters like ö aren't valid in URLs anyway
1318 # This was changed in August 2004
1319 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1321 # Register link in the output object.
1322 # Replace unnecessary URL escape codes with the referenced character
1323 # This prevents spammers from hiding links from the filters
1324 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1325 $this->mOutput
->addExternalLink( $pasteurized );
1328 wfProfileOut( $fname );
1333 * Replace anything that looks like a URL with a link
1336 function replaceFreeExternalLinks( $text ) {
1338 $fname = 'Parser::replaceFreeExternalLinks';
1339 wfProfileIn( $fname );
1341 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1342 $s = array_shift( $bits );
1345 $sk = $this->mOptions
->getSkin();
1347 while ( $i < count( $bits ) ){
1348 $protocol = $bits[$i++
];
1349 $remainder = $bits[$i++
];
1352 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1353 # Found some characters after the protocol that look promising
1354 $url = $protocol . $m[1];
1357 # special case: handle urls as url args:
1358 # http://www.example.com/foo?=http://www.example.com/bar
1359 if(strlen($trail) == 0 &&
1361 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1362 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1365 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1370 # The characters '<' and '>' (which were escaped by
1371 # removeHTMLtags()) should not be included in
1372 # URLs, per RFC 2396.
1374 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1375 $trail = substr($url, $m2[0][1]) . $trail;
1376 $url = substr($url, 0, $m2[0][1]);
1379 # Move trailing punctuation to $trail
1381 # If there is no left bracket, then consider right brackets fair game too
1382 if ( strpos( $url, '(' ) === false ) {
1386 $numSepChars = strspn( strrev( $url ), $sep );
1387 if ( $numSepChars ) {
1388 $trail = substr( $url, -$numSepChars ) . $trail;
1389 $url = substr( $url, 0, -$numSepChars );
1392 $url = Sanitizer
::cleanUrl( $url );
1394 # Is this an external image?
1395 $text = $this->maybeMakeExternalImage( $url );
1396 if ( $text === false ) {
1397 # Not an image, make a link
1398 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1399 # Register it in the output object...
1400 # Replace unnecessary URL escape codes with their equivalent characters
1401 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1402 $this->mOutput
->addExternalLink( $pasteurized );
1404 $s .= $text . $trail;
1406 $s .= $protocol . $remainder;
1409 wfProfileOut( $fname );
1414 * Replace unusual URL escape codes with their equivalent characters
1418 * @todo This can merge genuinely required bits in the path or query string,
1419 * breaking legit URLs. A proper fix would treat the various parts of
1420 * the URL differently; as a workaround, just use the output for
1421 * statistical records, not for actual linking/output.
1423 static function replaceUnusualEscapes( $url ) {
1424 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1425 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1429 * Callback function used in replaceUnusualEscapes().
1430 * Replaces unusual URL escape codes with their equivalent character
1434 private static function replaceUnusualEscapesCallback( $matches ) {
1435 $char = urldecode( $matches[0] );
1436 $ord = ord( $char );
1437 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1438 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1439 // No, shouldn't be escaped
1442 // Yes, leave it escaped
1448 * make an image if it's allowed, either through the global
1449 * option or through the exception
1452 function maybeMakeExternalImage( $url ) {
1453 $sk = $this->mOptions
->getSkin();
1454 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1455 $imagesexception = !empty($imagesfrom);
1457 if ( $this->mOptions
->getAllowExternalImages()
1458 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1459 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1461 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1468 * Process [[ ]] wikilinks
1472 function replaceInternalLinks( $s ) {
1474 static $fname = 'Parser::replaceInternalLinks' ;
1476 wfProfileIn( $fname );
1478 wfProfileIn( $fname.'-setup' );
1480 # the % is needed to support urlencoded titles as well
1481 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1483 $sk = $this->mOptions
->getSkin();
1485 #split the entire text string on occurences of [[
1486 $a = explode( '[[', ' ' . $s );
1487 #get the first element (all text up to first [[), and remove the space we added
1488 $s = array_shift( $a );
1489 $s = substr( $s, 1 );
1491 # Match a link having the form [[namespace:link|alternate]]trail
1493 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1494 # Match cases where there is no "]]", which might still be images
1495 static $e1_img = FALSE;
1496 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1498 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1500 if ( $useLinkPrefixExtension ) {
1501 # Match the end of a line for a word that's not followed by whitespace,
1502 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1503 $e2 = wfMsgForContent( 'linkprefix' );
1506 if( is_null( $this->mTitle
) ) {
1507 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1509 $nottalk = !$this->mTitle
->isTalkPage();
1511 if ( $useLinkPrefixExtension ) {
1513 if ( preg_match( $e2, $s, $m ) ) {
1514 $first_prefix = $m[2];
1516 $first_prefix = false;
1522 if($wgContLang->hasVariants()) {
1523 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1525 $selflink = array($this->mTitle
->getPrefixedText());
1527 $useSubpages = $this->areSubpagesAllowed();
1528 wfProfileOut( $fname.'-setup' );
1530 # Loop for each link
1531 for ($k = 0; isset( $a[$k] ); $k++
) {
1533 if ( $useLinkPrefixExtension ) {
1534 wfProfileIn( $fname.'-prefixhandling' );
1535 if ( preg_match( $e2, $s, $m ) ) {
1543 $prefix = $first_prefix;
1544 $first_prefix = false;
1546 wfProfileOut( $fname.'-prefixhandling' );
1549 $might_be_img = false;
1551 wfProfileIn( "$fname-e1" );
1552 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1554 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1555 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1556 # the real problem is with the $e1 regex
1559 # Still some problems for cases where the ] is meant to be outside punctuation,
1560 # and no image is in sight. See bug 2095.
1563 substr( $m[3], 0, 1 ) === ']' &&
1564 strpos($text, '[') !== false
1567 $text .= ']'; # so that replaceExternalLinks($text) works later
1568 $m[3] = substr( $m[3], 1 );
1570 # fix up urlencoded title texts
1571 if( strpos( $m[1], '%' ) !== false ) {
1572 # Should anchors '#' also be rejected?
1573 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1576 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1577 $might_be_img = true;
1579 if ( strpos( $m[1], '%' ) !== false ) {
1580 $m[1] = urldecode($m[1]);
1583 } else { # Invalid form; output directly
1584 $s .= $prefix . '[[' . $line ;
1585 wfProfileOut( "$fname-e1" );
1588 wfProfileOut( "$fname-e1" );
1589 wfProfileIn( "$fname-misc" );
1591 # Don't allow internal links to pages containing
1592 # PROTO: where PROTO is a valid URL protocol; these
1593 # should be external links.
1594 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1595 $s .= $prefix . '[[' . $line ;
1599 # Make subpage if necessary
1600 if( $useSubpages ) {
1601 $link = $this->maybeDoSubpageLink( $m[1], $text );
1606 $noforce = (substr($m[1], 0, 1) != ':');
1608 # Strip off leading ':'
1609 $link = substr($link, 1);
1612 wfProfileOut( "$fname-misc" );
1613 wfProfileIn( "$fname-title" );
1614 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1616 $s .= $prefix . '[[' . $line;
1617 wfProfileOut( "$fname-title" );
1621 $ns = $nt->getNamespace();
1622 $iw = $nt->getInterWiki();
1623 wfProfileOut( "$fname-title" );
1625 if ($might_be_img) { # if this is actually an invalid link
1626 wfProfileIn( "$fname-might_be_img" );
1627 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1629 while (isset ($a[$k+
1]) ) {
1630 #look at the next 'line' to see if we can close it there
1631 $spliced = array_splice( $a, $k +
1, 1 );
1632 $next_line = array_shift( $spliced );
1633 $m = explode( ']]', $next_line, 3 );
1634 if ( count( $m ) == 3 ) {
1635 # the first ]] closes the inner link, the second the image
1637 $text .= "[[{$m[0]}]]{$m[1]}";
1640 } elseif ( count( $m ) == 2 ) {
1641 #if there's exactly one ]] that's fine, we'll keep looking
1642 $text .= "[[{$m[0]}]]{$m[1]}";
1644 #if $next_line is invalid too, we need look no further
1645 $text .= '[[' . $next_line;
1650 # we couldn't find the end of this imageLink, so output it raw
1651 #but don't ignore what might be perfectly normal links in the text we've examined
1652 $text = $this->replaceInternalLinks($text);
1653 $s .= "{$prefix}[[$link|$text";
1654 # note: no $trail, because without an end, there *is* no trail
1655 wfProfileOut( "$fname-might_be_img" );
1658 } else { #it's not an image, so output it raw
1659 $s .= "{$prefix}[[$link|$text";
1660 # note: no $trail, because without an end, there *is* no trail
1661 wfProfileOut( "$fname-might_be_img" );
1664 wfProfileOut( "$fname-might_be_img" );
1667 $wasblank = ( '' == $text );
1668 if( $wasblank ) $text = $link;
1670 # Link not escaped by : , create the various objects
1674 wfProfileIn( "$fname-interwiki" );
1675 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1676 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1677 $s = rtrim($s . $prefix);
1678 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1679 wfProfileOut( "$fname-interwiki" );
1682 wfProfileOut( "$fname-interwiki" );
1684 if ( $ns == NS_IMAGE
) {
1685 wfProfileIn( "$fname-image" );
1686 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1687 # recursively parse links inside the image caption
1688 # actually, this will parse them in any other parameters, too,
1689 # but it might be hard to fix that, and it doesn't matter ATM
1690 $text = $this->replaceExternalLinks($text);
1691 $text = $this->replaceInternalLinks($text);
1693 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1694 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1695 $this->mOutput
->addImage( $nt->getDBkey() );
1697 wfProfileOut( "$fname-image" );
1700 # We still need to record the image's presence on the page
1701 $this->mOutput
->addImage( $nt->getDBkey() );
1703 wfProfileOut( "$fname-image" );
1707 if ( $ns == NS_CATEGORY
) {
1708 wfProfileIn( "$fname-category" );
1709 $s = rtrim($s . "\n"); # bug 87
1712 $sortkey = $this->getDefaultSort();
1716 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1717 $sortkey = str_replace( "\n", '', $sortkey );
1718 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1719 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1722 * Strip the whitespace Category links produce, see bug 87
1723 * @todo We might want to use trim($tmp, "\n") here.
1725 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1727 wfProfileOut( "$fname-category" );
1732 # Self-link checking
1733 if( $nt->getFragment() === '' ) {
1734 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1735 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1740 # Special and Media are pseudo-namespaces; no pages actually exist in them
1741 if( $ns == NS_MEDIA
) {
1742 $link = $sk->makeMediaLinkObj( $nt, $text );
1743 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1744 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1745 $this->mOutput
->addImage( $nt->getDBkey() );
1747 } elseif( $ns == NS_SPECIAL
) {
1748 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1749 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1751 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1754 } elseif( $ns == NS_IMAGE
) {
1755 $img = wfFindFile( $nt );
1757 // Force a blue link if the file exists; may be a remote
1758 // upload on the shared repository, and we want to see its
1759 // auto-generated page.
1760 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1761 $this->mOutput
->addLink( $nt );
1765 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1767 wfProfileOut( $fname );
1772 * Make a link placeholder. The text returned can be later resolved to a real link with
1773 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1774 * parsing of interwiki links, and secondly to allow all existence checks and
1775 * article length checks (for stub links) to be bundled into a single query.
1778 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1779 wfProfileIn( __METHOD__
);
1780 if ( ! is_object($nt) ) {
1782 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1784 # Separate the link trail from the rest of the link
1785 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1787 if ( $nt->isExternal() ) {
1788 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1789 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1790 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1792 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1793 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1794 $this->mLinkHolders
['queries'][] = $query;
1795 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1796 $this->mLinkHolders
['titles'][] = $nt;
1798 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1801 wfProfileOut( __METHOD__
);
1806 * Render a forced-blue link inline; protect against double expansion of
1807 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1808 * Since this little disaster has to split off the trail text to avoid
1809 * breaking URLs in the following text without breaking trails on the
1810 * wiki links, it's been made into a horrible function.
1813 * @param string $text
1814 * @param string $query
1815 * @param string $trail
1816 * @param string $prefix
1817 * @return string HTML-wikitext mix oh yuck
1819 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1820 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1821 $sk = $this->mOptions
->getSkin();
1822 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1823 return $this->armorLinks( $link ) . $trail;
1827 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1828 * going to go through further parsing steps before inline URL expansion.
1830 * In particular this is important when using action=render, which causes
1831 * full URLs to be included.
1833 * Oh man I hate our multi-layer parser!
1835 * @param string more-or-less HTML
1836 * @return string less-or-more HTML with NOPARSE bits
1838 function armorLinks( $text ) {
1839 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1840 "{$this->mUniqPrefix}NOPARSE$1", $text );
1844 * Return true if subpage links should be expanded on this page.
1847 function areSubpagesAllowed() {
1848 # Some namespaces don't allow subpages
1849 global $wgNamespacesWithSubpages;
1850 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1854 * Handle link to subpage if necessary
1855 * @param string $target the source of the link
1856 * @param string &$text the link text, modified as necessary
1857 * @return string the full name of the link
1860 function maybeDoSubpageLink($target, &$text) {
1863 # :Foobar -- override special treatment of prefix (images, language links)
1864 # /Foobar -- convert to CurrentPage/Foobar
1865 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1866 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1867 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1869 $fname = 'Parser::maybeDoSubpageLink';
1870 wfProfileIn( $fname );
1871 $ret = $target; # default return value is no change
1873 # Some namespaces don't allow subpages,
1874 # so only perform processing if subpages are allowed
1875 if( $this->areSubpagesAllowed() ) {
1876 $hash = strpos( $target, '#' );
1877 if( $hash !== false ) {
1878 $suffix = substr( $target, $hash );
1879 $target = substr( $target, 0, $hash );
1884 $target = trim( $target );
1885 # Look at the first character
1886 if( $target != '' && $target{0} == '/' ) {
1887 # / at end means we don't want the slash to be shown
1889 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1890 if( $trailingSlashes ) {
1891 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1893 $noslash = substr( $target, 1 );
1896 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1897 if( '' === $text ) {
1898 $text = $target . $suffix;
1899 } # this might be changed for ugliness reasons
1901 # check for .. subpage backlinks
1903 $nodotdot = $target;
1904 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1906 $nodotdot = substr( $nodotdot, 3 );
1908 if($dotdotcount > 0) {
1909 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1910 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1911 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1912 # / at the end means don't show full path
1913 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1914 $nodotdot = substr( $nodotdot, 0, -1 );
1915 if( '' === $text ) {
1916 $text = $nodotdot . $suffix;
1919 $nodotdot = trim( $nodotdot );
1920 if( $nodotdot != '' ) {
1921 $ret .= '/' . $nodotdot;
1929 wfProfileOut( $fname );
1934 * Used by doBlockLevels()
1937 /* private */ function closeParagraph() {
1939 if ( '' != $this->mLastSection
) {
1940 $result = '</' . $this->mLastSection
. ">\n";
1942 $this->mInPre
= false;
1943 $this->mLastSection
= '';
1946 # getCommon() returns the length of the longest common substring
1947 # of both arguments, starting at the beginning of both.
1949 /* private */ function getCommon( $st1, $st2 ) {
1950 $fl = strlen( $st1 );
1951 $shorter = strlen( $st2 );
1952 if ( $fl < $shorter ) { $shorter = $fl; }
1954 for ( $i = 0; $i < $shorter; ++
$i ) {
1955 if ( $st1{$i} != $st2{$i} ) { break; }
1959 # These next three functions open, continue, and close the list
1960 # element appropriate to the prefix character passed into them.
1962 /* private */ function openList( $char ) {
1963 $result = $this->closeParagraph();
1965 if ( '*' == $char ) { $result .= '<ul><li>'; }
1966 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1967 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1968 else if ( ';' == $char ) {
1969 $result .= '<dl><dt>';
1970 $this->mDTopen
= true;
1972 else { $result = '<!-- ERR 1 -->'; }
1977 /* private */ function nextItem( $char ) {
1978 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1979 else if ( ':' == $char ||
';' == $char ) {
1981 if ( $this->mDTopen
) { $close = '</dt>'; }
1982 if ( ';' == $char ) {
1983 $this->mDTopen
= true;
1984 return $close . '<dt>';
1986 $this->mDTopen
= false;
1987 return $close . '<dd>';
1990 return '<!-- ERR 2 -->';
1993 /* private */ function closeList( $char ) {
1994 if ( '*' == $char ) { $text = '</li></ul>'; }
1995 else if ( '#' == $char ) { $text = '</li></ol>'; }
1996 else if ( ':' == $char ) {
1997 if ( $this->mDTopen
) {
1998 $this->mDTopen
= false;
1999 $text = '</dt></dl>';
2001 $text = '</dd></dl>';
2004 else { return '<!-- ERR 3 -->'; }
2010 * Make lists from lines starting with ':', '*', '#', etc.
2013 * @return string the lists rendered as HTML
2015 function doBlockLevels( $text, $linestart ) {
2016 $fname = 'Parser::doBlockLevels';
2017 wfProfileIn( $fname );
2019 # Parsing through the text line by line. The main thing
2020 # happening here is handling of block-level elements p, pre,
2021 # and making lists from lines starting with * # : etc.
2023 $textLines = explode( "\n", $text );
2025 $lastPrefix = $output = '';
2026 $this->mDTopen
= $inBlockElem = false;
2028 $paragraphStack = false;
2030 if ( !$linestart ) {
2031 $output .= array_shift( $textLines );
2033 foreach ( $textLines as $oLine ) {
2034 $lastPrefixLength = strlen( $lastPrefix );
2035 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2036 $preOpenMatch = preg_match('/<pre/i', $oLine );
2037 if ( !$this->mInPre
) {
2038 # Multiple prefixes may abut each other for nested lists.
2039 $prefixLength = strspn( $oLine, '*#:;' );
2040 $pref = substr( $oLine, 0, $prefixLength );
2043 $pref2 = str_replace( ';', ':', $pref );
2044 $t = substr( $oLine, $prefixLength );
2045 $this->mInPre
= !empty($preOpenMatch);
2047 # Don't interpret any other prefixes in preformatted text
2049 $pref = $pref2 = '';
2054 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2055 # Same as the last item, so no need to deal with nesting or opening stuff
2056 $output .= $this->nextItem( substr( $pref, -1 ) );
2057 $paragraphStack = false;
2059 if ( substr( $pref, -1 ) == ';') {
2060 # The one nasty exception: definition lists work like this:
2061 # ; title : definition text
2062 # So we check for : in the remainder text to split up the
2063 # title and definition, without b0rking links.
2065 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2067 $output .= $term . $this->nextItem( ':' );
2070 } elseif( $prefixLength ||
$lastPrefixLength ) {
2071 # Either open or close a level...
2072 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2073 $paragraphStack = false;
2075 while( $commonPrefixLength < $lastPrefixLength ) {
2076 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2077 --$lastPrefixLength;
2079 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2080 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2082 while ( $prefixLength > $commonPrefixLength ) {
2083 $char = substr( $pref, $commonPrefixLength, 1 );
2084 $output .= $this->openList( $char );
2086 if ( ';' == $char ) {
2087 # FIXME: This is dupe of code above
2088 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2090 $output .= $term . $this->nextItem( ':' );
2093 ++
$commonPrefixLength;
2095 $lastPrefix = $pref2;
2097 if( 0 == $prefixLength ) {
2098 wfProfileIn( "$fname-paragraph" );
2099 # No prefix (not in list)--go to paragraph mode
2100 // XXX: use a stack for nestable elements like span, table and div
2101 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2102 $closematch = preg_match(
2103 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2104 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2105 if ( $openmatch or $closematch ) {
2106 $paragraphStack = false;
2107 #Â TODO bug 5718: paragraph closed
2108 $output .= $this->closeParagraph();
2109 if ( $preOpenMatch and !$preCloseMatch ) {
2110 $this->mInPre
= true;
2112 if ( $closematch ) {
2113 $inBlockElem = false;
2115 $inBlockElem = true;
2117 } else if ( !$inBlockElem && !$this->mInPre
) {
2118 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2120 if ($this->mLastSection
!= 'pre') {
2121 $paragraphStack = false;
2122 $output .= $this->closeParagraph().'<pre>';
2123 $this->mLastSection
= 'pre';
2125 $t = substr( $t, 1 );
2128 if ( '' == trim($t) ) {
2129 if ( $paragraphStack ) {
2130 $output .= $paragraphStack.'<br />';
2131 $paragraphStack = false;
2132 $this->mLastSection
= 'p';
2134 if ($this->mLastSection
!= 'p' ) {
2135 $output .= $this->closeParagraph();
2136 $this->mLastSection
= '';
2137 $paragraphStack = '<p>';
2139 $paragraphStack = '</p><p>';
2143 if ( $paragraphStack ) {
2144 $output .= $paragraphStack;
2145 $paragraphStack = false;
2146 $this->mLastSection
= 'p';
2147 } else if ($this->mLastSection
!= 'p') {
2148 $output .= $this->closeParagraph().'<p>';
2149 $this->mLastSection
= 'p';
2154 wfProfileOut( "$fname-paragraph" );
2156 // somewhere above we forget to get out of pre block (bug 785)
2157 if($preCloseMatch && $this->mInPre
) {
2158 $this->mInPre
= false;
2160 if ($paragraphStack === false) {
2164 while ( $prefixLength ) {
2165 $output .= $this->closeList( $pref2{$prefixLength-1} );
2168 if ( '' != $this->mLastSection
) {
2169 $output .= '</' . $this->mLastSection
. '>';
2170 $this->mLastSection
= '';
2173 wfProfileOut( $fname );
2178 * Split up a string on ':', ignoring any occurences inside tags
2179 * to prevent illegal overlapping.
2180 * @param string $str the string to split
2181 * @param string &$before set to everything before the ':'
2182 * @param string &$after set to everything after the ':'
2183 * return string the position of the ':', or false if none found
2185 function findColonNoLinks($str, &$before, &$after) {
2186 $fname = 'Parser::findColonNoLinks';
2187 wfProfileIn( $fname );
2189 $pos = strpos( $str, ':' );
2190 if( $pos === false ) {
2192 wfProfileOut( $fname );
2196 $lt = strpos( $str, '<' );
2197 if( $lt === false ||
$lt > $pos ) {
2198 // Easy; no tag nesting to worry about
2199 $before = substr( $str, 0, $pos );
2200 $after = substr( $str, $pos+
1 );
2201 wfProfileOut( $fname );
2205 // Ugly state machine to walk through avoiding tags.
2206 $state = self
::COLON_STATE_TEXT
;
2208 $len = strlen( $str );
2209 for( $i = 0; $i < $len; $i++
) {
2213 // (Using the number is a performance hack for common cases)
2214 case 0: // self::COLON_STATE_TEXT:
2217 // Could be either a <start> tag or an </end> tag
2218 $state = self
::COLON_STATE_TAGSTART
;
2223 $before = substr( $str, 0, $i );
2224 $after = substr( $str, $i +
1 );
2225 wfProfileOut( $fname );
2228 // Embedded in a tag; don't break it.
2231 // Skip ahead looking for something interesting
2232 $colon = strpos( $str, ':', $i );
2233 if( $colon === false ) {
2234 // Nothing else interesting
2235 wfProfileOut( $fname );
2238 $lt = strpos( $str, '<', $i );
2239 if( $stack === 0 ) {
2240 if( $lt === false ||
$colon < $lt ) {
2242 $before = substr( $str, 0, $colon );
2243 $after = substr( $str, $colon +
1 );
2244 wfProfileOut( $fname );
2248 if( $lt === false ) {
2249 // Nothing else interesting to find; abort!
2250 // We're nested, but there's no close tags left. Abort!
2253 // Skip ahead to next tag start
2255 $state = self
::COLON_STATE_TAGSTART
;
2258 case 1: // self::COLON_STATE_TAG:
2263 $state = self
::COLON_STATE_TEXT
;
2266 // Slash may be followed by >?
2267 $state = self
::COLON_STATE_TAGSLASH
;
2273 case 2: // self::COLON_STATE_TAGSTART:
2276 $state = self
::COLON_STATE_CLOSETAG
;
2279 $state = self
::COLON_STATE_COMMENT
;
2282 // Illegal early close? This shouldn't happen D:
2283 $state = self
::COLON_STATE_TEXT
;
2286 $state = self
::COLON_STATE_TAG
;
2289 case 3: // self::COLON_STATE_CLOSETAG:
2294 wfDebug( "Invalid input in $fname; too many close tags\n" );
2295 wfProfileOut( $fname );
2298 $state = self
::COLON_STATE_TEXT
;
2301 case self
::COLON_STATE_TAGSLASH
:
2303 // Yes, a self-closed tag <blah/>
2304 $state = self
::COLON_STATE_TEXT
;
2306 // Probably we're jumping the gun, and this is an attribute
2307 $state = self
::COLON_STATE_TAG
;
2310 case 5: // self::COLON_STATE_COMMENT:
2312 $state = self
::COLON_STATE_COMMENTDASH
;
2315 case self
::COLON_STATE_COMMENTDASH
:
2317 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2319 $state = self
::COLON_STATE_COMMENT
;
2322 case self
::COLON_STATE_COMMENTDASHDASH
:
2324 $state = self
::COLON_STATE_TEXT
;
2326 $state = self
::COLON_STATE_COMMENT
;
2330 throw new MWException( "State machine error in $fname" );
2334 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2337 wfProfileOut( $fname );
2342 * Return value of a magic variable (like PAGENAME)
2346 function getVariableValue( $index ) {
2347 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2350 * Some of these require message or data lookups and can be
2351 * expensive to check many times.
2353 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2354 if ( isset( $this->mVarCache
[$index] ) ) {
2355 return $this->mVarCache
[$index];
2359 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2360 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2363 global $wgLocaltimezone;
2364 if ( isset( $wgLocaltimezone ) ) {
2365 $oldtz = getenv( 'TZ' );
2366 putenv( 'TZ='.$wgLocaltimezone );
2369 wfSuppressWarnings(); // E_STRICT system time bitching
2370 $localTimestamp = date( 'YmdHis', $ts );
2371 $localMonth = date( 'm', $ts );
2372 $localMonthName = date( 'n', $ts );
2373 $localDay = date( 'j', $ts );
2374 $localDay2 = date( 'd', $ts );
2375 $localDayOfWeek = date( 'w', $ts );
2376 $localWeek = date( 'W', $ts );
2377 $localYear = date( 'Y', $ts );
2378 $localHour = date( 'H', $ts );
2379 if ( isset( $wgLocaltimezone ) ) {
2380 putenv( 'TZ='.$oldtz );
2382 wfRestoreWarnings();
2385 case 'currentmonth':
2386 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2387 case 'currentmonthname':
2388 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2389 case 'currentmonthnamegen':
2390 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2391 case 'currentmonthabbrev':
2392 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2394 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2396 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2398 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2399 case 'localmonthname':
2400 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2401 case 'localmonthnamegen':
2402 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2403 case 'localmonthabbrev':
2404 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2406 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2408 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2410 return wfEscapeWikiText( $this->mTitle
->getText() );
2412 return $this->mTitle
->getPartialURL();
2413 case 'fullpagename':
2414 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2415 case 'fullpagenamee':
2416 return $this->mTitle
->getPrefixedURL();
2418 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2419 case 'subpagenamee':
2420 return $this->mTitle
->getSubpageUrlForm();
2421 case 'basepagename':
2422 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2423 case 'basepagenamee':
2424 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2425 case 'talkpagename':
2426 if( $this->mTitle
->canTalk() ) {
2427 $talkPage = $this->mTitle
->getTalkPage();
2428 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2432 case 'talkpagenamee':
2433 if( $this->mTitle
->canTalk() ) {
2434 $talkPage = $this->mTitle
->getTalkPage();
2435 return $talkPage->getPrefixedUrl();
2439 case 'subjectpagename':
2440 $subjPage = $this->mTitle
->getSubjectPage();
2441 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2442 case 'subjectpagenamee':
2443 $subjPage = $this->mTitle
->getSubjectPage();
2444 return $subjPage->getPrefixedUrl();
2446 // Let the edit saving system know we should parse the page
2447 // *after* a revision ID has been assigned.
2448 $this->mOutput
->setFlag( 'vary-revision' );
2449 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2450 return $this->mRevisionId
;
2452 // Let the edit saving system know we should parse the page
2453 // *after* a revision ID has been assigned. This is for null edits.
2454 $this->mOutput
->setFlag( 'vary-revision' );
2455 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2456 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2457 case 'revisionday2':
2458 // Let the edit saving system know we should parse the page
2459 // *after* a revision ID has been assigned. This is for null edits.
2460 $this->mOutput
->setFlag( 'vary-revision' );
2461 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2462 return substr( $this->getRevisionTimestamp(), 6, 2 );
2463 case 'revisionmonth':
2464 // Let the edit saving system know we should parse the page
2465 // *after* a revision ID has been assigned. This is for null edits.
2466 $this->mOutput
->setFlag( 'vary-revision' );
2467 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2468 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2469 case 'revisionyear':
2470 // Let the edit saving system know we should parse the page
2471 // *after* a revision ID has been assigned. This is for null edits.
2472 $this->mOutput
->setFlag( 'vary-revision' );
2473 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2474 return substr( $this->getRevisionTimestamp(), 0, 4 );
2475 case 'revisiontimestamp':
2476 // Let the edit saving system know we should parse the page
2477 // *after* a revision ID has been assigned. This is for null edits.
2478 $this->mOutput
->setFlag( 'vary-revision' );
2479 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2480 return $this->getRevisionTimestamp();
2482 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2484 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2486 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2488 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2489 case 'subjectspace':
2490 return $this->mTitle
->getSubjectNsText();
2491 case 'subjectspacee':
2492 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2493 case 'currentdayname':
2494 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2496 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2498 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2500 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2502 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2503 // int to remove the padding
2504 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2506 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2507 case 'localdayname':
2508 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2510 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2512 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2514 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2516 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2517 // int to remove the padding
2518 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2520 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2521 case 'numberofarticles':
2522 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2523 case 'numberoffiles':
2524 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2525 case 'numberofusers':
2526 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2527 case 'numberofpages':
2528 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2529 case 'numberofadmins':
2530 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2531 case 'numberofedits':
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2533 case 'currenttimestamp':
2534 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2535 case 'localtimestamp':
2536 return $this->mVarCache
[$index] = $localTimestamp;
2537 case 'currentversion':
2538 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2544 return $wgServerName;
2546 return $wgScriptPath;
2547 case 'directionmark':
2548 return $wgContLang->getDirMark();
2549 case 'contentlanguage':
2550 global $wgContLanguageCode;
2551 return $wgContLanguageCode;
2554 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2562 * initialise the magic variables (like CURRENTMONTHNAME)
2566 function initialiseVariables() {
2567 $fname = 'Parser::initialiseVariables';
2568 wfProfileIn( $fname );
2569 $variableIDs = MagicWord
::getVariableIDs();
2571 $this->mVariables
= new MagicWordArray( $variableIDs );
2572 wfProfileOut( $fname );
2576 * Preprocess some wikitext and return the document tree.
2577 * This is the ghost of replace_variables().
2579 * @param string $text The text to parse
2580 * @param integer flags Bitwise combination of:
2581 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2582 * included. Default is to assume a direct page view.
2584 * The generated DOM tree must depend only on the input text and the flags.
2585 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2587 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2588 * change in the DOM tree for a given text, must be passed through the section identifier
2589 * in the section edit link and thus back to extractSections().
2591 * The output of this function is currently only cached in process memory, but a persistent
2592 * cache may be implemented at a later date which takes further advantage of these strict
2593 * dependency requirements.
2597 function preprocessToDom ( $text, $flags = 0 ) {
2598 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2603 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2605 public static function splitWhitespace( $s ) {
2606 $ltrimmed = ltrim( $s );
2607 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2608 $trimmed = rtrim( $ltrimmed );
2609 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2611 $w2 = substr( $ltrimmed, -$diff );
2615 return array( $w1, $trimmed, $w2 );
2619 * Replace magic variables, templates, and template arguments
2620 * with the appropriate text. Templates are substituted recursively,
2621 * taking care to avoid infinite loops.
2623 * Note that the substitution depends on value of $mOutputType:
2624 * self::OT_WIKI: only {{subst:}} templates
2625 * self::OT_PREPROCESS: templates but not extension tags
2626 * self::OT_HTML: all templates and extension tags
2628 * @param string $tex The text to transform
2629 * @param PPFrame $frame Object describing the arguments passed to the template
2630 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2633 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2634 # Prevent too big inclusions
2635 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2639 $fname = __METHOD__
;
2640 wfProfileIn( $fname );
2642 if ( $frame === false ) {
2643 $frame = $this->getPreprocessor()->newFrame();
2644 } elseif ( !( $frame instanceof PPFrame
) ) {
2645 throw new MWException( __METHOD__
. ' called using the old argument format' );
2648 $dom = $this->preprocessToDom( $text );
2649 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2650 $text = $frame->expand( $dom, $flags );
2652 wfProfileOut( $fname );
2656 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2657 static function createAssocArgs( $args ) {
2658 $assocArgs = array();
2660 foreach( $args as $arg ) {
2661 $eqpos = strpos( $arg, '=' );
2662 if ( $eqpos === false ) {
2663 $assocArgs[$index++
] = $arg;
2665 $name = trim( substr( $arg, 0, $eqpos ) );
2666 $value = trim( substr( $arg, $eqpos+
1 ) );
2667 if ( $value === false ) {
2670 if ( $name !== false ) {
2671 $assocArgs[$name] = $value;
2680 * Return the text of a template, after recursively
2681 * replacing any variables or templates within the template.
2683 * @param array $piece The parts of the template
2684 * $piece['title']: the title, i.e. the part before the |
2685 * $piece['parts']: the parameter array
2686 * $piece['lineStart']: whether the brace was at the start of a line
2687 * @param PPFrame The current frame, contains template arguments
2688 * @return string the text of the template
2691 function braceSubstitution( $piece, $frame ) {
2692 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2693 $fname = __METHOD__
;
2694 wfProfileIn( $fname );
2695 wfProfileIn( __METHOD__
.'-setup' );
2698 $found = false; # $text has been filled
2699 $nowiki = false; # wiki markup in $text should be escaped
2700 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2701 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2702 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2703 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2705 # Title object, where $text came from
2708 # $part1 is the bit before the first |, and must contain only title characters.
2709 # Various prefixes will be stripped from it later.
2710 $titleWithSpaces = $frame->expand( $piece['title'] );
2711 $part1 = trim( $titleWithSpaces );
2714 # Original title text preserved for various purposes
2715 $originalTitle = $part1;
2717 # $args is a list of argument nodes, starting from index 0, not including $part1
2718 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2719 wfProfileOut( __METHOD__
.'-setup' );
2722 wfProfileIn( __METHOD__
.'-modifiers' );
2724 $mwSubst =& MagicWord
::get( 'subst' );
2725 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2726 # One of two possibilities is true:
2727 # 1) Found SUBST but not in the PST phase
2728 # 2) Didn't find SUBST and in the PST phase
2729 # In either case, return without further processing
2730 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2737 if ( !$found && $args->getLength() == 0 ) {
2738 $id = $this->mVariables
->matchStartToEnd( $part1 );
2739 if ( $id !== false ) {
2740 $text = $this->getVariableValue( $id );
2741 if (MagicWord
::getCacheTTL($id)>-1)
2742 $this->mOutput
->mContainsOldMagic
= true;
2747 # MSG, MSGNW and RAW
2750 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2751 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2754 # Remove obsolete MSG:
2755 $mwMsg =& MagicWord
::get( 'msg' );
2756 $mwMsg->matchStartAndRemove( $part1 );
2760 $mwRaw =& MagicWord
::get( 'raw' );
2761 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2762 $forceRawInterwiki = true;
2765 wfProfileOut( __METHOD__
.'-modifiers' );
2769 wfProfileIn( __METHOD__
. '-pfunc' );
2771 $colonPos = strpos( $part1, ':' );
2772 if ( $colonPos !== false ) {
2773 # Case sensitive functions
2774 $function = substr( $part1, 0, $colonPos );
2775 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2776 $function = $this->mFunctionSynonyms
[1][$function];
2778 # Case insensitive functions
2779 $function = strtolower( $function );
2780 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2781 $function = $this->mFunctionSynonyms
[0][$function];
2787 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2788 $initialArgs = array( &$this );
2789 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2790 if ( $flags & SFH_OBJECT_ARGS
) {
2791 # Add a frame parameter, and pass the arguments as an array
2792 $allArgs = $initialArgs;
2793 $allArgs[] = $frame;
2794 for ( $i = 0; $i < $args->getLength(); $i++
) {
2795 $funcArgs[] = $args->item( $i );
2797 $allArgs[] = $funcArgs;
2799 # Convert arguments to plain text
2800 for ( $i = 0; $i < $args->getLength(); $i++
) {
2801 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2803 $allArgs = array_merge( $initialArgs, $funcArgs );
2806 # Workaround for PHP bug 35229 and similar
2807 if ( !is_callable( $callback ) ) {
2808 throw new MWException( "Tag hook for $name is not callable\n" );
2810 $result = call_user_func_array( $callback, $allArgs );
2813 if ( is_array( $result ) ) {
2814 if ( isset( $result[0] ) ) {
2816 unset( $result[0] );
2819 // Extract flags into the local scope
2820 // This allows callers to set flags such as nowiki, found, etc.
2827 wfProfileOut( __METHOD__
. '-pfunc' );
2830 # Finish mangling title and then check for loops.
2831 # Set $title to a Title object and $titleText to the PDBK
2834 # Split the title into page and subpage
2836 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2837 if ($subpage !== '') {
2838 $ns = $this->mTitle
->getNamespace();
2840 $title = Title
::newFromText( $part1, $ns );
2842 $titleText = $title->getPrefixedText();
2843 # Check for language variants if the template is not found
2844 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2845 $wgContLang->findVariantLink($part1, $title);
2847 # Do infinite loop check
2848 if ( !$frame->loopCheck( $title ) ) {
2850 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2851 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2853 # Do recursion depth check
2854 $limit = $this->mOptions
->getMaxTemplateDepth();
2855 if ( $frame->depth
>= $limit ) {
2857 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2862 # Load from database
2863 if ( !$found && $title ) {
2864 wfProfileIn( __METHOD__
. '-loadtpl' );
2865 if ( !$title->isExternal() ) {
2866 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2867 $text = SpecialPage
::capturePath( $title );
2868 if ( is_string( $text ) ) {
2871 $this->disableCache();
2873 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2874 $found = false; //access denied
2875 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2877 list( $text, $title ) = $this->getTemplateDom( $title );
2878 if ( $text !== false ) {
2884 # If the title is valid but undisplayable, make a link to it
2885 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2886 $text = "[[:$titleText]]";
2889 } elseif ( $title->isTrans() ) {
2890 // Interwiki transclusion
2891 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2892 $text = $this->interwikiTransclude( $title, 'render' );
2895 $text = $this->interwikiTransclude( $title, 'raw' );
2896 // Preprocess it like a template
2897 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2902 wfProfileOut( __METHOD__
. '-loadtpl' );
2905 # If we haven't found text to substitute by now, we're done
2906 # Recover the source wikitext and return it
2908 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2909 wfProfileOut( $fname );
2910 return array( 'object' => $text );
2913 # Expand DOM-style return values in a child frame
2914 if ( $isChildObj ) {
2915 # Clean up argument array
2916 $newFrame = $frame->newChild( $args, $title );
2919 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2920 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2921 # Expansion is eligible for the empty-frame cache
2922 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2923 $text = $this->mTplExpandCache
[$titleText];
2925 $text = $newFrame->expand( $text );
2926 $this->mTplExpandCache
[$titleText] = $text;
2929 # Uncached expansion
2930 $text = $newFrame->expand( $text );
2933 if ( $isLocalObj && $nowiki ) {
2934 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2935 $isLocalObj = false;
2938 # Replace raw HTML by a placeholder
2939 # Add a blank line preceding, to prevent it from mucking up
2940 # immediately preceding headings
2942 $text = "\n\n" . $this->insertStripItem( $text );
2944 # Escape nowiki-style return values
2945 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2946 $text = wfEscapeWikiText( $text );
2948 # Bug 529: if the template begins with a table or block-level
2949 # element, it should be treated as beginning a new line.
2950 # This behaviour is somewhat controversial.
2951 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2952 $text = "\n" . $text;
2955 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2956 # Error, oversize inclusion
2957 $text = "[[$originalTitle]]" .
2958 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2961 if ( $isLocalObj ) {
2962 $ret = array( 'object' => $text );
2964 $ret = array( 'text' => $text );
2967 wfProfileOut( $fname );
2972 * Get the semi-parsed DOM representation of a template with a given title,
2973 * and its redirect destination title. Cached.
2975 function getTemplateDom( $title ) {
2976 $cacheTitle = $title;
2977 $titleText = $title->getPrefixedDBkey();
2979 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2980 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2981 $title = Title
::makeTitle( $ns, $dbk );
2982 $titleText = $title->getPrefixedDBkey();
2984 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2985 return array( $this->mTplDomCache
[$titleText], $title );
2988 // Cache miss, go to the database
2989 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2991 if ( $text === false ) {
2992 $this->mTplDomCache
[$titleText] = false;
2993 return array( false, $title );
2996 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2997 $this->mTplDomCache
[ $titleText ] = $dom;
2999 if (! $title->equals($cacheTitle)) {
3000 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3001 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3004 return array( $dom, $title );
3008 * Fetch the unparsed text of a template and register a reference to it.
3010 function fetchTemplateAndTitle( $title ) {
3011 $templateCb = $this->mOptions
->getTemplateCallback();
3012 $stuff = call_user_func( $templateCb, $title );
3013 $text = $stuff['text'];
3014 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3015 if ( isset( $stuff['deps'] ) ) {
3016 foreach ( $stuff['deps'] as $dep ) {
3017 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3020 return array($text,$finalTitle);
3023 function fetchTemplate( $title ) {
3024 $rv = $this->fetchTemplateAndTitle($title);
3029 * Static function to get a template
3030 * Can be overridden via ParserOptions::setTemplateCallback().
3032 static function statelessFetchTemplate( $title ) {
3033 $text = $skip = false;
3034 $finalTitle = $title;
3037 // Loop to fetch the article, with up to 1 redirect
3038 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3039 # Give extensions a chance to select the revision instead
3040 $id = false; // Assume current
3041 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3047 'page_id' => $title->getArticleID(),
3051 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3052 $rev_id = $rev ?
$rev->getId() : 0;
3056 'page_id' => $title->getArticleID(),
3057 'rev_id' => $rev_id );
3060 $text = $rev->getText();
3061 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3063 $message = $wgLang->lcfirst( $title->getText() );
3064 $text = wfMsgForContentNoTrans( $message );
3065 if( wfEmptyMsg( $message, $text ) ) {
3072 if ( $text === false ) {
3076 $finalTitle = $title;
3077 $title = Title
::newFromRedirect( $text );
3081 'finalTitle' => $finalTitle,
3086 * Transclude an interwiki link.
3088 function interwikiTransclude( $title, $action ) {
3089 global $wgEnableScaryTranscluding;
3091 if (!$wgEnableScaryTranscluding)
3092 return wfMsg('scarytranscludedisabled');
3094 $url = $title->getFullUrl( "action=$action" );
3096 if (strlen($url) > 255)
3097 return wfMsg('scarytranscludetoolong');
3098 return $this->fetchScaryTemplateMaybeFromCache($url);
3101 function fetchScaryTemplateMaybeFromCache($url) {
3102 global $wgTranscludeCacheExpiry;
3103 $dbr = wfGetDB(DB_SLAVE
);
3104 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3105 array('tc_url' => $url));
3107 $time = $obj->tc_time
;
3108 $text = $obj->tc_contents
;
3109 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3114 $text = Http
::get($url);
3116 return wfMsg('scarytranscludefailed', $url);
3118 $dbw = wfGetDB(DB_MASTER
);
3119 $dbw->replace('transcache', array('tc_url'), array(
3121 'tc_time' => time(),
3122 'tc_contents' => $text));
3128 * Triple brace replacement -- used for template arguments
3131 function argSubstitution( $piece, $frame ) {
3132 wfProfileIn( __METHOD__
);
3135 $parts = $piece['parts'];
3136 $nameWithSpaces = $frame->expand( $piece['title'] );
3137 $argName = trim( $nameWithSpaces );
3139 $text = $frame->getArgument( $argName );
3140 if ( $text === false && $parts->getLength() > 0
3144 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3147 # No match in frame, use the supplied default
3148 $object = $parts->item( 0 )->getChildren();
3150 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3151 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3154 if ( $text === false && $object === false ) {
3156 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3158 if ( $error !== false ) {
3161 if ( $object !== false ) {
3162 $ret = array( 'object' => $object );
3164 $ret = array( 'text' => $text );
3167 wfProfileOut( __METHOD__
);
3172 * Return the text to be used for a given extension tag.
3173 * This is the ghost of strip().
3175 * @param array $params Associative array of parameters:
3176 * name PPNode for the tag name
3177 * attr PPNode for unparsed text where tag attributes are thought to be
3178 * attributes Optional associative array of parsed attributes
3179 * inner Contents of extension element
3180 * noClose Original text did not have a close tag
3181 * @param PPFrame $frame
3183 function extensionSubstitution( $params, $frame ) {
3184 global $wgRawHtml, $wgContLang;
3186 $name = $frame->expand( $params['name'] );
3187 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3188 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3190 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3192 if ( $this->ot
['html'] ) {
3193 $name = strtolower( $name );
3195 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3196 if ( isset( $params['attributes'] ) ) {
3197 $attributes = $attributes +
$params['attributes'];
3205 throw new MWException( '<html> extension tag encountered unexpectedly' );
3208 $output = Xml
::escapeTagsOnly( $content );
3211 $output = $wgContLang->armourMath(
3212 MathRenderer
::renderMath( $content, $attributes ) );
3215 $output = $this->renderImageGallery( $content, $attributes );
3218 if( isset( $this->mTagHooks
[$name] ) ) {
3219 # Workaround for PHP bug 35229 and similar
3220 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3221 throw new MWException( "Tag hook for $name is not callable\n" );
3223 $output = call_user_func_array( $this->mTagHooks
[$name],
3224 array( $content, $attributes, $this ) );
3226 throw new MWException( "Invalid call hook $name" );
3230 if ( is_null( $attrText ) ) {
3233 if ( isset( $params['attributes'] ) ) {
3234 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3235 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3236 htmlspecialchars( $attrValue ) . '"';
3239 if ( $content === null ) {
3240 $output = "<$name$attrText/>";
3242 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3243 $output = "<$name$attrText>$content$close";
3247 if ( $name == 'html' ||
$name == 'nowiki' ) {
3248 $this->mStripState
->nowiki
->setPair( $marker, $output );
3250 $this->mStripState
->general
->setPair( $marker, $output );
3256 * Increment an include size counter
3258 * @param string $type The type of expansion
3259 * @param integer $size The size of the text
3260 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3262 function incrementIncludeSize( $type, $size ) {
3263 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3266 $this->mIncludeSizes
[$type] +
= $size;
3272 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3273 * Fills $this->mDoubleUnderscores, returns the modified text
3275 function doDoubleUnderscore( $text ) {
3276 // The position of __TOC__ needs to be recorded
3277 $mw = MagicWord
::get( 'toc' );
3278 if( $mw->match( $text ) ) {
3279 $this->mShowToc
= true;
3280 $this->mForceTocPosition
= true;
3282 // Set a placeholder. At the end we'll fill it in with the TOC.
3283 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3285 // Only keep the first one.
3286 $text = $mw->replace( '', $text );
3289 // Now match and remove the rest of them
3290 $mwa = MagicWord
::getDoubleUnderscoreArray();
3291 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3293 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3294 $this->mOutput
->mNoGallery
= true;
3296 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3297 $this->mShowToc
= false;
3299 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3300 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3302 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3303 if ( $containerCategory ) {
3304 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3306 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3313 * This function accomplishes several tasks:
3314 * 1) Auto-number headings if that option is enabled
3315 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3316 * 3) Add a Table of contents on the top for users who have enabled the option
3317 * 4) Auto-anchor headings
3319 * It loops through all headlines, collects the necessary data, then splits up the
3320 * string and re-inserts the newly formatted headlines.
3322 * @param string $text
3323 * @param boolean $isMain
3326 function formatHeadings( $text, $isMain=true ) {
3327 global $wgMaxTocLevel, $wgContLang;
3329 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3330 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3333 $showEditLink = $this->mOptions
->getEditSection();
3336 # Inhibit editsection links if requested in the page
3337 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3341 # Get all headlines for numbering them and adding funky stuff like [edit]
3342 # links - this is for later, but we need the number of headlines right now
3344 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3346 # if there are fewer than 4 headlines in the article, do not show TOC
3347 # unless it's been explicitly enabled.
3348 $enoughToc = $this->mShowToc
&&
3349 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3351 # Allow user to stipulate that a page should have a "new section"
3352 # link added via __NEWSECTIONLINK__
3353 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3354 $this->mOutput
->setNewSection( true );
3357 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3358 # override above conditions and always show TOC above first header
3359 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3360 $this->mShowToc
= true;
3364 # We need this to perform operations on the HTML
3365 $sk = $this->mOptions
->getSkin();
3371 # Ugh .. the TOC should have neat indentation levels which can be
3372 # passed to the skin functions. These are determined here
3376 $sublevelCount = array();
3377 $levelCount = array();
3383 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3384 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3387 foreach( $matches[3] as $headline ) {
3388 $isTemplate = false;
3390 $sectionIndex = false;
3392 $markerMatches = array();
3393 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3394 $serial = $markerMatches[1];
3395 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3396 $isTemplate = ($titleText != $baseTitleText);
3397 $headline = preg_replace("/^$markerRegex/", "", $headline);
3401 $prevlevel = $level;
3402 $prevtoclevel = $toclevel;
3404 $level = $matches[1][$headlineCount];
3406 if( $doNumberHeadings ||
$enoughToc ) {
3408 if ( $level > $prevlevel ) {
3409 # Increase TOC level
3411 $sublevelCount[$toclevel] = 0;
3412 if( $toclevel<$wgMaxTocLevel ) {
3413 $prevtoclevel = $toclevel;
3414 $toc .= $sk->tocIndent();
3418 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3419 # Decrease TOC level, find level to jump to
3421 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3422 # Can only go down to level 1
3425 for ($i = $toclevel; $i > 0; $i--) {
3426 if ( $levelCount[$i] == $level ) {
3427 # Found last matching level
3431 elseif ( $levelCount[$i] < $level ) {
3432 # Found first matching level below current level
3438 if( $toclevel<$wgMaxTocLevel ) {
3439 if($prevtoclevel < $wgMaxTocLevel) {
3440 # Unindent only if the previous toc level was shown :p
3441 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3442 $prevtoclevel = $toclevel;
3444 $toc .= $sk->tocLineEnd();
3449 # No change in level, end TOC line
3450 if( $toclevel<$wgMaxTocLevel ) {
3451 $toc .= $sk->tocLineEnd();
3455 $levelCount[$toclevel] = $level;
3457 # count number of headlines for each level
3458 @$sublevelCount[$toclevel]++
;
3460 for( $i = 1; $i <= $toclevel; $i++
) {
3461 if( !empty( $sublevelCount[$i] ) ) {
3465 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3471 # The safe header is a version of the header text safe to use for links
3472 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3473 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3475 # Remove link placeholders by the link text.
3476 # <!--LINK number-->
3478 # link text with suffix
3479 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3480 "\$this->mLinkHolders['texts'][\$1]",
3482 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3483 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3486 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3487 $tocline = preg_replace(
3488 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3492 $tocline = trim( $tocline );
3494 # For the anchor, strip out HTML-y stuff period
3495 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3496 $safeHeadline = trim( $safeHeadline );
3498 # Save headline for section edit hint before it's escaped
3499 $headlineHint = $safeHeadline;
3500 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3501 # HTML names must be case-insensitively unique (bug 10721)
3502 $arrayKey = strtolower( $safeHeadline );
3504 # XXX : Is $refers[$headlineCount] ever accessed, actually ?
3505 $refers[$headlineCount] = $safeHeadline;
3507 # count how many in assoc. array so we can track dupes in anchors
3508 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3509 $refcount[$headlineCount] = $refers[$arrayKey];
3511 # Don't number the heading if it is the only one (looks silly)
3512 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3513 # the two are different if the line contains a link
3514 $headline=$numbering . ' ' . $headline;
3517 # Create the anchor for linking from the TOC to the section
3518 $anchor = $safeHeadline;
3519 if($refcount[$headlineCount] > 1 ) {
3520 $anchor .= '_' . $refcount[$headlineCount];
3522 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3523 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3524 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3526 # give headline the correct <h#> tag
3527 if( $showEditLink && $sectionIndex !== false ) {
3529 # Put a T flag in the section identifier, to indicate to extractSections()
3530 # that sections inside <includeonly> should be counted.
3531 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3533 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3538 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3543 $this->mOutput
->setSections( $tocraw );
3545 # Never ever show TOC if no headers
3546 if( $numVisible < 1 ) {
3551 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3552 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3554 $toc = $sk->tocList( $toc );
3557 # split up and insert constructed headlines
3559 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3562 foreach( $blocks as $block ) {
3563 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3564 # This is the [edit] link that appears for the top block of text when
3565 # section editing is enabled
3567 # Disabled because it broke block formatting
3568 # For example, a bullet point in the top line
3569 # $full .= $sk->editSectionLink(0);
3572 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3573 # Top anchor now in skin
3577 if( !empty( $head[$i] ) ) {
3582 if( $this->mForceTocPosition
) {
3583 return str_replace( '<!--MWTOC-->', $toc, $full );
3590 * Transform wiki markup when saving a page by doing \r\n -> \n
3591 * conversion, substitting signatures, {{subst:}} templates, etc.
3593 * @param string $text the text to transform
3594 * @param Title &$title the Title object for the current article
3595 * @param User &$user the User object describing the current user
3596 * @param ParserOptions $options parsing options
3597 * @param bool $clearState whether to clear the parser state first
3598 * @return string the altered wiki markup
3601 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3602 $this->mOptions
= $options;
3603 $this->setTitle( $title );
3604 $this->setOutputType( self
::OT_WIKI
);
3606 if ( $clearState ) {
3607 $this->clearState();
3613 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3614 $text = $this->pstPass2( $text, $user );
3615 $text = $this->mStripState
->unstripBoth( $text );
3620 * Pre-save transform helper function
3623 function pstPass2( $text, $user ) {
3624 global $wgContLang, $wgLocaltimezone;
3626 /* Note: This is the timestamp saved as hardcoded wikitext to
3627 * the database, we use $wgContLang here in order to give
3628 * everyone the same signature and use the default one rather
3629 * than the one selected in each user's preferences.
3631 * (see also bug 12815)
3633 $ts = $this->mOptions
->getTimestamp();
3635 if ( isset( $wgLocaltimezone ) ) {
3636 $unixts = wfTimestamp( TS_UNIX
, $ts );
3637 $oldtz = getenv( 'TZ' );
3638 putenv( 'TZ='.$wgLocaltimezone );
3639 $ts = date( 'YmdHis', $unixts );
3640 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3641 putenv( 'TZ='.$oldtz );
3643 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3645 # Variable replacement
3646 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3647 $text = $this->replaceVariables( $text );
3650 $sigText = $this->getUserSig( $user );
3651 $text = strtr( $text, array(
3653 '~~~~' => "$sigText $d",
3657 # Context links: [[|name]] and [[name (context)|]]
3659 global $wgLegalTitleChars;
3660 $tc = "[$wgLegalTitleChars]";
3661 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3663 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3664 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3665 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3667 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3668 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3669 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3671 $t = $this->mTitle
->getText();
3673 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3674 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3675 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3676 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3678 # if there's no context, don't bother duplicating the title
3679 $text = preg_replace( $p2, '[[\\1]]', $text );
3682 # Trim trailing whitespace
3683 $text = rtrim( $text );
3689 * Fetch the user's signature text, if any, and normalize to
3690 * validated, ready-to-insert wikitext.
3696 function getUserSig( &$user ) {
3697 global $wgMaxSigChars;
3699 $username = $user->getName();
3700 $nickname = $user->getOption( 'nickname' );
3701 $nickname = $nickname === '' ?
$username : $nickname;
3703 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3704 $nickname = $username;
3705 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3706 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3707 # Sig. might contain markup; validate this
3708 if( $this->validateSig( $nickname ) !== false ) {
3709 # Validated; clean up (if needed) and return it
3710 return $this->cleanSig( $nickname, true );
3712 # Failed to validate; fall back to the default
3713 $nickname = $username;
3714 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3718 // Make sure nickname doesnt get a sig in a sig
3719 $nickname = $this->cleanSigInSig( $nickname );
3721 # If we're still here, make it a link to the user page
3722 $userText = wfEscapeWikiText( $username );
3723 $nickText = wfEscapeWikiText( $nickname );
3724 if ( $user->isAnon() ) {
3725 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3727 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3732 * Check that the user's signature contains no bad XML
3734 * @param string $text
3735 * @return mixed An expanded string, or false if invalid.
3737 function validateSig( $text ) {
3738 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3742 * Clean up signature text
3744 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3745 * 2) Substitute all transclusions
3747 * @param string $text
3748 * @param $parsing Whether we're cleaning (preferences save) or parsing
3749 * @return string Signature text
3751 function cleanSig( $text, $parsing = false ) {
3754 $this->clearState();
3755 $this->setTitle( $wgTitle );
3756 $this->mOptions
= new ParserOptions
;
3757 $this->setOutputType
= self
::OT_PREPROCESS
;
3760 # FIXME: regex doesn't respect extension tags or nowiki
3761 # => Move this logic to braceSubstitution()
3762 $substWord = MagicWord
::get( 'subst' );
3763 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3764 $substText = '{{' . $substWord->getSynonym( 0 );
3766 $text = preg_replace( $substRegex, $substText, $text );
3767 $text = $this->cleanSigInSig( $text );
3768 $dom = $this->preprocessToDom( $text );
3769 $frame = $this->getPreprocessor()->newFrame();
3770 $text = $frame->expand( $dom );
3773 $text = $this->mStripState
->unstripBoth( $text );
3780 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3781 * @param string $text
3782 * @return string Signature text with /~{3,5}/ removed
3784 function cleanSigInSig( $text ) {
3785 $text = preg_replace( '/~{3,5}/', '', $text );
3790 * Set up some variables which are usually set up in parse()
3791 * so that an external function can call some class members with confidence
3794 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3795 $this->setTitle( $title );
3796 $this->mOptions
= $options;
3797 $this->setOutputType( $outputType );
3798 if ( $clearState ) {
3799 $this->clearState();
3804 * Wrapper for preprocess()
3806 * @param string $text the text to preprocess
3807 * @param ParserOptions $options options
3811 function transformMsg( $text, $options ) {
3813 static $executing = false;
3815 $fname = "Parser::transformMsg";
3817 # Guard against infinite recursion
3823 wfProfileIn($fname);
3824 $text = $this->preprocess( $text, $wgTitle, $options );
3827 wfProfileOut($fname);
3832 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3833 * The callback should have the following form:
3834 * function myParserHook( $text, $params, &$parser ) { ... }
3836 * Transform and return $text. Use $parser for any required context, e.g. use
3837 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3841 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3842 * @param mixed $callback The callback function (and object) to use for the tag
3844 * @return The old value of the mTagHooks array associated with the hook
3846 function setHook( $tag, $callback ) {
3847 $tag = strtolower( $tag );
3848 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3849 $this->mTagHooks
[$tag] = $callback;
3850 if( !in_array( $tag, $this->mStripList
) ) {
3851 $this->mStripList
[] = $tag;
3857 function setTransparentTagHook( $tag, $callback ) {
3858 $tag = strtolower( $tag );
3859 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3860 $this->mTransparentTagHooks
[$tag] = $callback;
3866 * Remove all tag hooks
3868 function clearTagHooks() {
3869 $this->mTagHooks
= array();
3870 $this->mStripList
= $this->mDefaultStripList
;
3874 * Create a function, e.g. {{sum:1|2|3}}
3875 * The callback function should have the form:
3876 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3878 * The callback may either return the text result of the function, or an array with the text
3879 * in element 0, and a number of flags in the other elements. The names of the flags are
3880 * specified in the keys. Valid flags are:
3881 * found The text returned is valid, stop processing the template. This
3883 * nowiki Wiki markup in the return value should be escaped
3884 * isHTML The returned text is HTML, armour it against wikitext transformation
3888 * @param string $id The magic word ID
3889 * @param mixed $callback The callback function (and object) to use
3890 * @param integer $flags a combination of the following flags:
3891 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3893 * @return The old callback function for this name, if any
3895 function setFunctionHook( $id, $callback, $flags = 0 ) {
3896 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3897 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3899 # Add to function cache
3900 $mw = MagicWord
::get( $id );
3902 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3904 $synonyms = $mw->getSynonyms();
3905 $sensitive = intval( $mw->isCaseSensitive() );
3907 foreach ( $synonyms as $syn ) {
3909 if ( !$sensitive ) {
3910 $syn = strtolower( $syn );
3913 if ( !( $flags & SFH_NO_HASH
) ) {
3916 # Remove trailing colon
3917 if ( substr( $syn, -1, 1 ) == ':' ) {
3918 $syn = substr( $syn, 0, -1 );
3920 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3926 * Get all registered function hook identifiers
3930 function getFunctionHooks() {
3931 return array_keys( $this->mFunctionHooks
);
3935 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3936 * Placeholders created in Skin::makeLinkObj()
3937 * Returns an array of link CSS classes, indexed by PDBK.
3938 * $options is a bit field, RLH_FOR_UPDATE to select for update
3940 function replaceLinkHolders( &$text, $options = 0 ) {
3944 $fname = 'Parser::replaceLinkHolders';
3945 wfProfileIn( $fname );
3949 $linkcolour_ids = array();
3950 $sk = $this->mOptions
->getSkin();
3951 $linkCache =& LinkCache
::singleton();
3953 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3954 wfProfileIn( $fname.'-check' );
3955 $dbr = wfGetDB( DB_SLAVE
);
3956 $page = $dbr->tableName( 'page' );
3957 $threshold = $wgUser->getOption('stubthreshold');
3960 asort( $this->mLinkHolders
['namespaces'] );
3965 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3967 $title = $this->mLinkHolders
['titles'][$key];
3969 # Skip invalid entries.
3970 # Result will be ugly, but prevents crash.
3971 if ( is_null( $title ) ) {
3974 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3976 # Check if it's a static known link, e.g. interwiki
3977 if ( $title->isAlwaysKnown() ) {
3978 $colours[$pdbk] = '';
3979 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3980 $colours[$pdbk] = '';
3981 $this->mOutput
->addLink( $title, $id );
3982 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3983 $colours[$pdbk] = 'new';
3984 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
3985 $colours[$pdbk] = 'new';
3987 # Not in the link cache, add it to the query
3988 if ( !isset( $current ) ) {
3990 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect";
3991 if ( $threshold > 0 ) {
3992 $query .= ', page_len';
3994 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3995 } elseif ( $current != $ns ) {
3997 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4002 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4007 if ( $options & RLH_FOR_UPDATE
) {
4008 $query .= ' FOR UPDATE';
4011 $res = $dbr->query( $query, $fname );
4013 # Fetch data and form into an associative array
4014 # non-existent = broken
4015 while ( $s = $dbr->fetchObject($res) ) {
4016 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4017 $pdbk = $title->getPrefixedDBkey();
4018 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4019 $this->mOutput
->addLink( $title, $s->page_id
);
4020 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4021 //add id to the extension todolist
4022 $linkcolour_ids[$s->page_id
] = $pdbk;
4024 //pass an array of page_ids to an extension
4025 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4027 wfProfileOut( $fname.'-check' );
4029 # Do a second query for different language variants of links and categories
4030 if($wgContLang->hasVariants()){
4031 $linkBatch = new LinkBatch();
4032 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4033 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4034 $varCategories = array(); // category replacements oldDBkey => newDBkey
4036 $categories = $this->mOutput
->getCategoryLinks();
4038 // Add variants of links to link batch
4039 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4040 $title = $this->mLinkHolders
['titles'][$key];
4041 if ( is_null( $title ) )
4044 $pdbk = $title->getPrefixedDBkey();
4045 $titleText = $title->getText();
4047 // generate all variants of the link title text
4048 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4050 // if link was not found (in first query), add all variants to query
4051 if ( !isset($colours[$pdbk]) ){
4052 foreach($allTextVariants as $textVariant){
4053 if($textVariant != $titleText){
4054 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4055 if(is_null($variantTitle)) continue;
4056 $linkBatch->addObj( $variantTitle );
4057 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4063 // process categories, check if a category exists in some variant
4064 foreach( $categories as $category ){
4065 $variants = $wgContLang->convertLinkToAllVariants($category);
4066 foreach($variants as $variant){
4067 if($variant != $category){
4068 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4069 if(is_null($variantTitle)) continue;
4070 $linkBatch->addObj( $variantTitle );
4071 $categoryMap[$variant] = $category;
4077 if(!$linkBatch->isEmpty()){
4079 $titleClause = $linkBatch->constructSet('page', $dbr);
4081 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect";
4082 if ( $threshold > 0 ) {
4083 $variantQuery .= ', page_len';
4086 $variantQuery .= " FROM $page WHERE $titleClause";
4087 if ( $options & RLH_FOR_UPDATE
) {
4088 $variantQuery .= ' FOR UPDATE';
4091 $varRes = $dbr->query( $variantQuery, $fname );
4093 // for each found variants, figure out link holders and replace
4094 while ( $s = $dbr->fetchObject($varRes) ) {
4096 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4097 $varPdbk = $variantTitle->getPrefixedDBkey();
4098 $vardbk = $variantTitle->getDBkey();
4100 $holderKeys = array();
4101 if(isset($variantMap[$varPdbk])){
4102 $holderKeys = $variantMap[$varPdbk];
4103 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4104 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4107 // loop over link holders
4108 foreach($holderKeys as $key){
4109 $title = $this->mLinkHolders
['titles'][$key];
4110 if ( is_null( $title ) ) continue;
4112 $pdbk = $title->getPrefixedDBkey();
4114 if(!isset($colours[$pdbk])){
4115 // found link in some of the variants, replace the link holder data
4116 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4117 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4119 // set pdbk and colour
4120 $pdbks[$key] = $varPdbk;
4121 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4122 $linkcolour_ids[$s->page_id
] = $pdbk;
4124 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4127 // check if the object is a variant of a category
4128 if(isset($categoryMap[$vardbk])){
4129 $oldkey = $categoryMap[$vardbk];
4130 if($oldkey != $vardbk)
4131 $varCategories[$oldkey]=$vardbk;
4135 // rebuild the categories in original order (if there are replacements)
4136 if(count($varCategories)>0){
4138 $originalCats = $this->mOutput
->getCategories();
4139 foreach($originalCats as $cat => $sortkey){
4140 // make the replacement
4141 if( array_key_exists($cat,$varCategories) )
4142 $newCats[$varCategories[$cat]] = $sortkey;
4143 else $newCats[$cat] = $sortkey;
4145 $this->mOutput
->setCategoryLinks($newCats);
4150 # Construct search and replace arrays
4151 wfProfileIn( $fname.'-construct' );
4152 $replacePairs = array();
4153 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4154 $pdbk = $pdbks[$key];
4155 $searchkey = "<!--LINK $key-->";
4156 $title = $this->mLinkHolders
['titles'][$key];
4157 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4158 $linkCache->addBadLinkObj( $title );
4159 $colours[$pdbk] = 'new';
4160 $this->mOutput
->addLink( $title, 0 );
4161 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4162 $this->mLinkHolders
['texts'][$key],
4163 $this->mLinkHolders
['queries'][$key] );
4165 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4166 $this->mLinkHolders
['texts'][$key],
4167 $this->mLinkHolders
['queries'][$key] );
4170 $replacer = new HashtableReplacer( $replacePairs, 1 );
4171 wfProfileOut( $fname.'-construct' );
4174 wfProfileIn( $fname.'-replace' );
4175 $text = preg_replace_callback(
4176 '/(<!--LINK .*?-->)/',
4180 wfProfileOut( $fname.'-replace' );
4183 # Now process interwiki link holders
4184 # This is quite a bit simpler than internal links
4185 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4186 wfProfileIn( $fname.'-interwiki' );
4187 # Make interwiki link HTML
4188 $replacePairs = array();
4189 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4190 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4191 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4193 $replacer = new HashtableReplacer( $replacePairs, 1 );
4195 $text = preg_replace_callback(
4196 '/<!--IWLINK (.*?)-->/',
4199 wfProfileOut( $fname.'-interwiki' );
4202 wfProfileOut( $fname );
4207 * Replace <!--LINK--> link placeholders with plain text of links
4208 * (not HTML-formatted).
4209 * @param string $text
4212 function replaceLinkHoldersText( $text ) {
4213 $fname = 'Parser::replaceLinkHoldersText';
4214 wfProfileIn( $fname );
4216 $text = preg_replace_callback(
4217 '/<!--(LINK|IWLINK) (.*?)-->/',
4218 array( &$this, 'replaceLinkHoldersTextCallback' ),
4221 wfProfileOut( $fname );
4226 * @param array $matches
4230 function replaceLinkHoldersTextCallback( $matches ) {
4231 $type = $matches[1];
4233 if( $type == 'LINK' ) {
4234 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4235 return $this->mLinkHolders
['texts'][$key];
4237 } elseif( $type == 'IWLINK' ) {
4238 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4239 return $this->mInterwikiLinkHolders
['texts'][$key];
4246 * Tag hook handler for 'pre'.
4248 function renderPreTag( $text, $attribs ) {
4249 // Backwards-compatibility hack
4250 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4252 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4253 return wfOpenElement( 'pre', $attribs ) .
4254 Xml
::escapeTagsOnly( $content ) .
4259 * Renders an image gallery from a text with one line per image.
4260 * text labels may be given by using |-style alternative text. E.g.
4261 * Image:one.jpg|The number "1"
4262 * Image:tree.jpg|A tree
4263 * given as text will return the HTML of a gallery with two images,
4264 * labeled 'The number "1"' and
4267 function renderImageGallery( $text, $params ) {
4268 $ig = new ImageGallery();
4269 $ig->setContextTitle( $this->mTitle
);
4270 $ig->setShowBytes( false );
4271 $ig->setShowFilename( false );
4272 $ig->setParser( $this );
4273 $ig->setHideBadImages();
4274 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4275 $ig->useSkin( $this->mOptions
->getSkin() );
4276 $ig->mRevisionId
= $this->mRevisionId
;
4278 if( isset( $params['caption'] ) ) {
4279 $caption = $params['caption'];
4280 $caption = htmlspecialchars( $caption );
4281 $caption = $this->replaceInternalLinks( $caption );
4282 $ig->setCaptionHtml( $caption );
4284 if( isset( $params['perrow'] ) ) {
4285 $ig->setPerRow( $params['perrow'] );
4287 if( isset( $params['widths'] ) ) {
4288 $ig->setWidths( $params['widths'] );
4290 if( isset( $params['heights'] ) ) {
4291 $ig->setHeights( $params['heights'] );
4294 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4296 $lines = explode( "\n", $text );
4297 foreach ( $lines as $line ) {
4298 # match lines like these:
4299 # Image:someimage.jpg|This is some image
4301 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4303 if ( count( $matches ) == 0 ) {
4306 $tp = Title
::newFromText( $matches[1] );
4308 if( is_null( $nt ) ) {
4309 # Bogus title. Ignore these so we don't bomb out later.
4312 if ( isset( $matches[3] ) ) {
4313 $label = $matches[3];
4318 $html = $this->recursiveTagParse( trim( $label ) );
4320 $ig->add( $nt, $html );
4322 # Only add real images (bug #5586)
4323 if ( $nt->getNamespace() == NS_IMAGE
) {
4324 $this->mOutput
->addImage( $nt->getDBkey() );
4327 return $ig->toHTML();
4330 function getImageParams( $handler ) {
4332 $handlerClass = get_class( $handler );
4336 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4337 // Initialise static lists
4338 static $internalParamNames = array(
4339 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4340 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4341 'bottom', 'text-bottom' ),
4342 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4343 'upright', 'border' ),
4345 static $internalParamMap;
4346 if ( !$internalParamMap ) {
4347 $internalParamMap = array();
4348 foreach ( $internalParamNames as $type => $names ) {
4349 foreach ( $names as $name ) {
4350 $magicName = str_replace( '-', '_', "img_$name" );
4351 $internalParamMap[$magicName] = array( $type, $name );
4356 // Add handler params
4357 $paramMap = $internalParamMap;
4359 $handlerParamMap = $handler->getParamMap();
4360 foreach ( $handlerParamMap as $magic => $paramName ) {
4361 $paramMap[$magic] = array( 'handler', $paramName );
4364 $this->mImageParams
[$handlerClass] = $paramMap;
4365 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4367 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4371 * Parse image options text and use it to make an image
4373 function makeImage( $title, $options ) {
4374 # Check if the options text is of the form "options|alt text"
4376 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4377 # * left no resizing, just left align. label is used for alt= only
4378 # * right same, but right aligned
4379 # * none same, but not aligned
4380 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4381 # * center center the image
4382 # * framed Keep original image size, no magnify-button.
4383 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4384 # * upright reduce width for upright images, rounded to full __0 px
4385 # * border draw a 1px border around the image
4386 # vertical-align values (no % or length right now):
4396 $parts = array_map( 'trim', explode( '|', $options) );
4397 $sk = $this->mOptions
->getSkin();
4399 # Give extensions a chance to select the file revision for us
4400 $skip = $time = false;
4401 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4404 return $sk->makeLinkObj( $title );
4408 $file = wfFindFile( $title, $time );
4409 $handler = $file ?
$file->getHandler() : false;
4411 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4413 # Process the input parameters
4415 $params = array( 'frame' => array(), 'handler' => array(),
4416 'horizAlign' => array(), 'vertAlign' => array() );
4417 foreach( $parts as $part ) {
4418 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4420 if( isset( $paramMap[$magicName] ) ) {
4421 list( $type, $paramName ) = $paramMap[$magicName];
4423 // Special case; width and height come in one variable together
4424 if( $type == 'handler' && $paramName == 'width' ) {
4426 # (bug 13500) In both cases (width/height and width only),
4427 # permit trailing "px" for backward compatibility.
4428 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4429 $width = intval( $m[1] );
4430 $height = intval( $m[2] );
4431 if ( $handler->validateParam( 'width', $width ) ) {
4432 $params[$type]['width'] = $width;
4435 if ( $handler->validateParam( 'height', $height ) ) {
4436 $params[$type]['height'] = $height;
4439 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4440 $width = intval( $value );
4441 if ( $handler->validateParam( 'width', $width ) ) {
4442 $params[$type]['width'] = $width;
4445 } // else no validation -- bug 13436
4447 if ( $type == 'handler' ) {
4448 # Validate handler parameter
4449 $validated = $handler->validateParam( $paramName, $value );
4451 # Validate internal parameters
4452 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4456 $params[$type][$paramName] = $value;
4460 if ( !$validated ) {
4465 # Process alignment parameters
4466 if ( $params['horizAlign'] ) {
4467 $params['frame']['align'] = key( $params['horizAlign'] );
4469 if ( $params['vertAlign'] ) {
4470 $params['frame']['valign'] = key( $params['vertAlign'] );
4473 # Strip bad stuff out of the alt text
4474 $alt = $this->replaceLinkHoldersText( $caption );
4476 # make sure there are no placeholders in thumbnail attributes
4477 # that are later expanded to html- so expand them now and
4479 $alt = $this->mStripState
->unstripBoth( $alt );
4480 $alt = Sanitizer
::stripAllTags( $alt );
4482 $params['frame']['alt'] = $alt;
4483 $params['frame']['caption'] = $caption;
4485 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4487 # Linker does the rest
4488 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time );
4490 # Give the handler a chance to modify the parser object
4492 $handler->parserTransformHook( $this, $file );
4499 * Set a flag in the output object indicating that the content is dynamic and
4500 * shouldn't be cached.
4502 function disableCache() {
4503 wfDebug( "Parser output marked as uncacheable.\n" );
4504 $this->mOutput
->mCacheTime
= -1;
4508 * Callback from the Sanitizer for expanding items found in HTML attribute
4509 * values, so they can be safely tested and escaped.
4510 * @param string $text
4511 * @param PPFrame $frame
4515 function attributeStripCallback( &$text, $frame = false ) {
4516 $text = $this->replaceVariables( $text, $frame );
4517 $text = $this->mStripState
->unstripBoth( $text );
4526 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4527 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4528 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4534 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4539 * Break wikitext input into sections, and either pull or replace
4540 * some particular section's text.
4542 * External callers should use the getSection and replaceSection methods.
4544 * @param string $text Page wikitext
4545 * @param string $section A section identifier string of the form:
4546 * <flag1> - <flag2> - ... - <section number>
4548 * Currently the only recognised flag is "T", which means the target section number
4549 * was derived during a template inclusion parse, in other words this is a template
4550 * section edit link. If no flags are given, it was an ordinary section edit link.
4551 * This flag is required to avoid a section numbering mismatch when a section is
4552 * enclosed by <includeonly> (bug 6563).
4554 * The section number 0 pulls the text before the first heading; other numbers will
4555 * pull the given section along with its lower-level subsections. If the section is
4556 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4558 * @param string $mode One of "get" or "replace"
4559 * @param string $newText Replacement text for section data.
4560 * @return string for "get", the extracted section text.
4561 * for "replace", the whole page with the section replaced.
4563 private function extractSections( $text, $section, $mode, $newText='' ) {
4565 $this->clearState();
4566 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4567 $this->mOptions
= new ParserOptions
;
4568 $this->setOutputType( self
::OT_WIKI
);
4570 $frame = $this->getPreprocessor()->newFrame();
4572 // Process section extraction flags
4574 $sectionParts = explode( '-', $section );
4575 $sectionIndex = array_pop( $sectionParts );
4576 foreach ( $sectionParts as $part ) {
4577 if ( $part == 'T' ) {
4578 $flags |
= self
::PTD_FOR_INCLUSION
;
4581 // Preprocess the text
4582 $root = $this->preprocessToDom( $text, $flags );
4584 // <h> nodes indicate section breaks
4585 // They can only occur at the top level, so we can find them by iterating the root's children
4586 $node = $root->getFirstChild();
4588 // Find the target section
4589 if ( $sectionIndex == 0 ) {
4590 // Section zero doesn't nest, level=big
4591 $targetLevel = 1000;
4594 if ( $node->getName() == 'h' ) {
4595 $bits = $node->splitHeading();
4596 if ( $bits['i'] == $sectionIndex ) {
4597 $targetLevel = $bits['level'];
4601 if ( $mode == 'replace' ) {
4602 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4604 $node = $node->getNextSibling();
4610 if ( $mode == 'get' ) {
4617 // Find the end of the section, including nested sections
4619 if ( $node->getName() == 'h' ) {
4620 $bits = $node->splitHeading();
4621 $curLevel = $bits['level'];
4622 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4626 if ( $mode == 'get' ) {
4627 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4629 $node = $node->getNextSibling();
4632 // Write out the remainder (in replace mode only)
4633 if ( $mode == 'replace' ) {
4634 // Output the replacement text
4635 // Add two newlines on -- trailing whitespace in $newText is conventionally
4636 // stripped by the editor, so we need both newlines to restore the paragraph gap
4637 $outText .= $newText . "\n\n";
4639 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4640 $node = $node->getNextSibling();
4644 if ( is_string( $outText ) ) {
4645 // Re-insert stripped tags
4646 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
4653 * This function returns the text of a section, specified by a number ($section).
4654 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4655 * the first section before any such heading (section 0).
4657 * If a section contains subsections, these are also returned.
4659 * @param string $text text to look in
4660 * @param string $section section identifier
4661 * @param string $deftext default to return if section is not found
4662 * @return string text of the requested section
4664 public function getSection( $text, $section, $deftext='' ) {
4665 return $this->extractSections( $text, $section, "get", $deftext );
4668 public function replaceSection( $oldtext, $section, $text ) {
4669 return $this->extractSections( $oldtext, $section, "replace", $text );
4673 * Get the timestamp associated with the current revision, adjusted for
4674 * the default server-local timestamp
4676 function getRevisionTimestamp() {
4677 if ( is_null( $this->mRevisionTimestamp
) ) {
4678 wfProfileIn( __METHOD__
);
4680 $dbr = wfGetDB( DB_SLAVE
);
4681 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4682 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4684 // Normalize timestamp to internal MW format for timezone processing.
4685 // This has the added side-effect of replacing a null value with
4686 // the current time, which gives us more sensible behavior for
4688 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4690 // The cryptic '' timezone parameter tells to use the site-default
4691 // timezone offset instead of the user settings.
4693 // Since this value will be saved into the parser cache, served
4694 // to other users, and potentially even used inside links and such,
4695 // it needs to be consistent for all visitors.
4696 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4698 wfProfileOut( __METHOD__
);
4700 return $this->mRevisionTimestamp
;
4704 * Mutator for $mDefaultSort
4706 * @param $sort New value
4708 public function setDefaultSort( $sort ) {
4709 $this->mDefaultSort
= $sort;
4713 * Accessor for $mDefaultSort
4714 * Will use the title/prefixed title if none is set
4718 public function getDefaultSort() {
4719 if( $this->mDefaultSort
!== false ) {
4720 return $this->mDefaultSort
;
4722 return $this->mTitle
->getNamespace() == NS_CATEGORY
4723 ?
$this->mTitle
->getText()
4724 : $this->mTitle
->getPrefixedText();
4729 * Try to guess the section anchor name based on a wikitext fragment
4730 * presumably extracted from a heading, for example "Header" from
4733 public function guessSectionNameFromWikiText( $text ) {
4734 # Strip out wikitext links(they break the anchor)
4735 $text = $this->stripSectionName( $text );
4736 $headline = Sanitizer
::decodeCharReferences( $text );
4738 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4739 $headline = trim( $headline );
4740 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4741 $replacearray = array(
4746 array_keys( $replacearray ),
4747 array_values( $replacearray ),
4752 * Strips a text string of wikitext for use in a section anchor
4754 * Accepts a text string and then removes all wikitext from the
4755 * string and leaves only the resultant text (i.e. the result of
4756 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4757 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4758 * to create valid section anchors by mimicing the output of the
4759 * parser when headings are parsed.
4761 * @param $text string Text string to be stripped of wikitext
4762 * for use in a Section anchor
4763 * @return Filtered text string
4765 public function stripSectionName( $text ) {
4766 # Strip internal link markup
4767 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4768 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4770 # Strip external link markup (FIXME: Not Tolerant to blank link text
4771 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4772 # on how many empty links there are on the page - need to figure that out.
4773 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4775 # Parse wikitext quotes (italics & bold)
4776 $text = $this->doQuotes($text);
4779 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4783 function srvus( $text ) {
4784 return $this->testSrvus( $text, $this->mOutputType
);
4788 * strip/replaceVariables/unstrip for preprocessor regression testing
4790 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4791 $this->clearState();
4792 if ( ! ( $title instanceof Title
) ) {
4793 $title = Title
::newFromText( $title );
4795 $this->mTitle
= $title;
4796 $this->mOptions
= $options;
4797 $this->setOutputType( $outputType );
4798 $text = $this->replaceVariables( $text );
4799 $text = $this->mStripState
->unstripBoth( $text );
4800 $text = Sanitizer
::removeHTMLtags( $text );
4804 function testPst( $text, $title, $options ) {
4806 if ( ! ( $title instanceof Title
) ) {
4807 $title = Title
::newFromText( $title );
4809 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4812 function testPreprocess( $text, $title, $options ) {
4813 if ( ! ( $title instanceof Title
) ) {
4814 $title = Title
::newFromText( $title );
4816 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4819 function markerSkipCallback( $s, $callback ) {
4822 while ( $i < strlen( $s ) ) {
4823 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4824 if ( $markerStart === false ) {
4825 $out .= call_user_func( $callback, substr( $s, $i ) );
4828 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4829 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4830 if ( $markerEnd === false ) {
4831 $out .= substr( $s, $markerStart );
4834 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4835 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4845 * @todo document, briefly.
4846 * @addtogroup Parser
4849 var $general, $nowiki;
4851 function __construct() {
4852 $this->general
= new ReplacementArray
;
4853 $this->nowiki
= new ReplacementArray
;
4856 function unstripGeneral( $text ) {
4857 wfProfileIn( __METHOD__
);
4860 $text = $this->general
->replace( $text );
4861 } while ( $text != $oldText );
4862 wfProfileOut( __METHOD__
);
4866 function unstripNoWiki( $text ) {
4867 wfProfileIn( __METHOD__
);
4870 $text = $this->nowiki
->replace( $text );
4871 } while ( $text != $oldText );
4872 wfProfileOut( __METHOD__
);
4876 function unstripBoth( $text ) {
4877 wfProfileIn( __METHOD__
);
4880 $text = $this->general
->replace( $text );
4881 $text = $this->nowiki
->replace( $text );
4882 } while ( $text != $oldText );
4883 wfProfileOut( __METHOD__
);
4889 * @todo document, briefly.
4890 * @addtogroup Parser
4892 class OnlyIncludeReplacer
{
4895 function replace( $matches ) {
4896 if ( substr( $matches[1], -1 ) == "\n" ) {
4897 $this->output
.= substr( $matches[1], 0, -1 );
4899 $this->output
.= $matches[1];