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;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
124 function __construct( $conf = array() ) {
125 $this->mConf
= $conf;
126 $this->mTagHooks
= array();
127 $this->mTransparentTagHooks
= array();
128 $this->mFunctionHooks
= array();
129 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
131 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
133 $this->mVarCache
= array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass
= $conf['preprocessorClass'];
137 $this->mPreprocessorClass
= 'Preprocessor_DOM';
139 $this->mMarkerIndex
= 0;
140 $this->mFirstCall
= true;
144 * Do various kinds of initialisation on the first call of the parser
146 function firstCallInit() {
147 if ( !$this->mFirstCall
) {
150 $this->mFirstCall
= false;
152 wfProfileIn( __METHOD__
);
154 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
155 CoreParserFunctions
::register( $this );
156 $this->initialiseVariables();
158 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
159 wfProfileOut( __METHOD__
);
167 function clearState() {
168 wfProfileIn( __METHOD__
);
169 if ( $this->mFirstCall
) {
170 $this->firstCallInit();
172 $this->mOutput
= new ParserOutput
;
173 $this->mAutonumber
= 0;
174 $this->mLastSection
= '';
175 $this->mDTopen
= false;
176 $this->mIncludeCount
= array();
177 $this->mStripState
= new StripState
;
178 $this->mArgStack
= false;
179 $this->mInPre
= false;
180 $this->mInterwikiLinkHolders
= array(
184 $this->mLinkHolders
= array(
185 'namespaces' => array(),
187 'queries' => array(),
191 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
194 * Prefix for temporary replacement strings for the multipass parser.
195 * \x07 should never appear in input as it's disallowed in XML.
196 * Using it at the front also gives us a little extra robustness
197 * since it shouldn't match when butted up against identifier-like
200 * Must not consist of all title characters, or else it will change
201 * the behaviour of <nowiki> in a link.
203 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
204 # Changed to \x7f to allow XML double-parsing -- TS
205 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
208 # Clear these on every parse, bug 4549
209 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
211 $this->mShowToc
= true;
212 $this->mForceTocPosition
= false;
213 $this->mIncludeSizes
= array(
217 $this->mPPNodeCount
= 0;
218 $this->mDefaultSort
= false;
219 $this->mHeadings
= array();
220 $this->mDoubleUnderscores
= array();
221 $this->mExpensiveFunctionCount
= 0;
224 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
225 $this->mPreprocessor
= null;
228 wfRunHooks( 'ParserClearState', array( &$this ) );
229 wfProfileOut( __METHOD__
);
232 function setOutputType( $ot ) {
233 $this->mOutputType
= $ot;
236 'html' => $ot == self
::OT_HTML
,
237 'wiki' => $ot == self
::OT_WIKI
,
238 'pre' => $ot == self
::OT_PREPROCESS
,
243 * Set the context title
245 function setTitle( $t ) {
246 if ( !$t ||
$t instanceof FakeTitle
) {
247 $t = Title
::newFromText( 'NO TITLE' );
249 if ( strval( $t->getFragment() ) !== '' ) {
250 # Strip the fragment to avoid various odd effects
251 $this->mTitle
= clone $t;
252 $this->mTitle
->setFragment( '' );
259 * Accessor for mUniqPrefix.
263 function uniqPrefix() {
264 if( !isset( $this->mUniqPrefix
) ) {
265 // @fixme this is probably *horribly wrong*
266 // LanguageConverter seems to want $wgParser's uniqPrefix, however
267 // if this is called for a parser cache hit, the parser may not
268 // have ever been initialized in the first place.
269 // Not really sure what the heck is supposed to be going on here.
271 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
273 return $this->mUniqPrefix
;
277 * Convert wikitext to HTML
278 * Do not call this function recursively.
280 * @param string $text Text we want to parse
281 * @param Title &$title A title object
282 * @param array $options
283 * @param boolean $linestart
284 * @param boolean $clearState
285 * @param int $revid number to pass in {{REVISIONID}}
286 * @return ParserOutput a ParserOutput
288 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
290 * First pass--just handle <nowiki> sections, pass the rest off
291 * to internalParse() which does all the real work.
294 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
295 $fname = 'Parser::parse-' . wfGetCaller();
296 wfProfileIn( __METHOD__
);
297 wfProfileIn( $fname );
303 $this->mOptions
= $options;
304 $this->setTitle( $title );
305 $oldRevisionId = $this->mRevisionId
;
306 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
307 if( $revid !== null ) {
308 $this->mRevisionId
= $revid;
309 $this->mRevisionTimestamp
= null;
311 $this->setOutputType( self
::OT_HTML
);
312 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
314 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
315 $text = $this->internalParse( $text );
316 $text = $this->mStripState
->unstripGeneral( $text );
318 # Clean up special characters, only run once, next-to-last before doBlockLevels
320 # french spaces, last one Guillemet-left
321 # only if there is something before the space
322 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
323 # french spaces, Guillemet-right
324 '/(\\302\\253) /' => '\\1 ',
325 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
327 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
330 $text = $this->doBlockLevels( $text, $linestart );
332 $this->replaceLinkHolders( $text );
334 # the position of the parserConvert() call should not be changed. it
335 # assumes that the links are all replaced and the only thing left
336 # is the <nowiki> mark.
337 # Side-effects: this calls $this->mOutput->setTitleText()
338 $text = $wgContLang->parserConvert( $text, $this );
340 $text = $this->mStripState
->unstripNoWiki( $text );
342 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
344 //!JF Move to its own function
346 $uniq_prefix = $this->mUniqPrefix
;
348 $elements = array_keys( $this->mTransparentTagHooks
);
349 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
351 foreach( $matches as $marker => $data ) {
352 list( $element, $content, $params, $tag ) = $data;
353 $tagName = strtolower( $element );
354 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
355 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
356 array( $content, $params, $this ) );
360 $this->mStripState
->general
->setPair( $marker, $output );
362 $text = $this->mStripState
->unstripGeneral( $text );
364 $text = Sanitizer
::normalizeCharReferences( $text );
366 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
367 $text = Parser
::tidy($text);
369 # attempt to sanitize at least some nesting problems
370 # (bug #2702 and quite a few others)
372 # ''Something [http://www.cool.com cool''] -->
373 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
374 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
375 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
376 # fix up an anchor inside another anchor, only
377 # at least for a single single nested link (bug 3695)
378 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
379 '\\1\\2</a>\\3</a>\\1\\4</a>',
380 # fix div inside inline elements- doBlockLevels won't wrap a line which
381 # contains a div, so fix it up here; replace
382 # div with escaped text
383 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
384 '\\1\\3<div\\5>\\6</div>\\8\\9',
385 # remove empty italic or bold tag pairs, some
386 # introduced by rules above
387 '/<([bi])><\/\\1>/' => '',
390 $text = preg_replace(
391 array_keys( $tidyregs ),
392 array_values( $tidyregs ),
395 global $wgExpensiveParserFunctionLimit;
396 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
397 if ( is_callable( array( $this->mOutput
, 'addWarning' ) ) ) {
398 $warning = wfMsg( 'expensive-parserfunction-warning', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
399 $this->mOutput
->addWarning( $warning );
400 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'expensive-parserfunction-category' ) );
402 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
407 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
409 # Information on include size limits, for the benefit of users who try to skirt them
410 if ( $this->mOptions
->getEnableLimitReport() ) {
411 global $wgExpensiveParserFunctionLimit;
412 $max = $this->mOptions
->getMaxIncludeSize();
413 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
415 "NewPP limit report\n" .
416 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
417 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
418 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
420 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
421 $text .= "\n<!-- \n$limitReport-->\n";
423 $this->mOutput
->setText( $text );
424 $this->mRevisionId
= $oldRevisionId;
425 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
426 wfProfileOut( $fname );
427 wfProfileOut( __METHOD__
);
429 return $this->mOutput
;
433 * Recursive parser entry point that can be called from an extension tag
436 function recursiveTagParse( $text ) {
437 wfProfileIn( __METHOD__
);
438 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
439 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
440 $text = $this->internalParse( $text );
441 wfProfileOut( __METHOD__
);
446 * Expand templates and variables in the text, producing valid, static wikitext.
447 * Also removes comments.
449 function preprocess( $text, $title, $options, $revid = null ) {
450 wfProfileIn( __METHOD__
);
452 $this->setOutputType( self
::OT_PREPROCESS
);
453 $this->mOptions
= $options;
454 $this->setTitle( $title );
455 if( $revid !== null ) {
456 $this->mRevisionId
= $revid;
458 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
459 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
460 $text = $this->replaceVariables( $text );
461 $text = $this->mStripState
->unstripBoth( $text );
462 wfProfileOut( __METHOD__
);
467 * Get a random string
472 function getRandomString() {
473 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
476 function &getTitle() { return $this->mTitle
; }
477 function getOptions() { return $this->mOptions
; }
479 function getFunctionLang() {
480 global $wgLang, $wgContLang;
482 $target = $this->mOptions
->getTargetLanguage();
483 if ( $target !== null ) {
486 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
491 * Get a preprocessor object
493 function getPreprocessor() {
494 if ( !isset( $this->mPreprocessor
) ) {
495 $class = $this->mPreprocessorClass
;
496 $this->mPreprocessor
= new $class( $this );
498 return $this->mPreprocessor
;
502 * Replaces all occurrences of HTML-style comments and the given tags
503 * in the text with a random marker and returns the next text. The output
504 * parameter $matches will be an associative array filled with data in
506 * 'UNIQ-xxxxx' => array(
509 * array( 'param' => 'x' ),
510 * '<element param="x">tag content</element>' ) )
512 * @param $elements list of element names. Comments are always extracted.
513 * @param $text Source text string.
514 * @param $uniq_prefix
519 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
524 $taglist = implode( '|', $elements );
525 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
527 while ( '' != $text ) {
528 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
530 if( count( $p ) < 5 ) {
533 if( count( $p ) > 5 ) {
547 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
548 $stripped .= $marker;
550 if ( $close === '/>' ) {
551 // Empty element tag, <tag />
556 if( $element == '!--' ) {
559 $end = "/(<\\/$element\\s*>)/i";
561 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
563 if( count( $q ) < 3 ) {
564 # No end tag -- let it run out to the end of the text.
573 $matches[$marker] = array( $element,
575 Sanitizer
::decodeTagAttributes( $attributes ),
576 "<$element$attributes$close$content$tail" );
582 * Get a list of strippable XML-like elements
584 function getStripList() {
586 $elements = $this->mStripList
;
588 $elements[] = 'html';
590 if( $this->mOptions
->getUseTeX() ) {
591 $elements[] = 'math';
597 * @deprecated use replaceVariables
599 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
604 * Restores pre, math, and other extensions removed by strip()
606 * always call unstripNoWiki() after this one
608 * @deprecated use $this->mStripState->unstrip()
610 function unstrip( $text, $state ) {
611 return $state->unstripGeneral( $text );
615 * Always call this after unstrip() to preserve the order
618 * @deprecated use $this->mStripState->unstrip()
620 function unstripNoWiki( $text, $state ) {
621 return $state->unstripNoWiki( $text );
625 * @deprecated use $this->mStripState->unstripBoth()
627 function unstripForHTML( $text ) {
628 return $this->mStripState
->unstripBoth( $text );
632 * Add an item to the strip state
633 * Returns the unique tag which must be inserted into the stripped text
634 * The tag will be replaced with the original text in unstrip()
638 function insertStripItem( $text ) {
639 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
640 $this->mMarkerIndex++
;
641 $this->mStripState
->general
->setPair( $rnd, $text );
646 * Interface with html tidy, used if $wgUseTidy = true.
647 * If tidy isn't able to correct the markup, the original will be
648 * returned in all its glory with a warning comment appended.
650 * Either the external tidy program or the in-process tidy extension
651 * will be used depending on availability. Override the default
652 * $wgTidyInternal setting to disable the internal if it's not working.
654 * @param string $text Hideous HTML input
655 * @return string Corrected HTML output
659 function tidy( $text ) {
660 global $wgTidyInternal;
661 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
662 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
663 '<head><title>test</title></head><body>'.$text.'</body></html>';
664 if( $wgTidyInternal ) {
665 $correctedtext = Parser
::internalTidy( $wrappedtext );
667 $correctedtext = Parser
::externalTidy( $wrappedtext );
669 if( is_null( $correctedtext ) ) {
670 wfDebug( "Tidy error detected!\n" );
671 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
673 return $correctedtext;
677 * Spawn an external HTML tidy process and get corrected markup back from it.
682 function externalTidy( $text ) {
683 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
684 $fname = 'Parser::externalTidy';
685 wfProfileIn( $fname );
690 $descriptorspec = array(
691 0 => array('pipe', 'r'),
692 1 => array('pipe', 'w'),
693 2 => array('file', wfGetNull(), 'a')
696 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
697 if (is_resource($process)) {
698 // Theoretically, this style of communication could cause a deadlock
699 // here. If the stdout buffer fills up, then writes to stdin could
700 // block. This doesn't appear to happen with tidy, because tidy only
701 // writes to stdout after it's finished reading from stdin. Search
702 // for tidyParseStdin and tidySaveStdout in console/tidy.c
703 fwrite($pipes[0], $text);
705 while (!feof($pipes[1])) {
706 $cleansource .= fgets($pipes[1], 1024);
709 proc_close($process);
712 wfProfileOut( $fname );
714 if( $cleansource == '' && $text != '') {
715 // Some kind of error happened, so we couldn't get the corrected text.
716 // Just give up; we'll use the source text and append a warning.
724 * Use the HTML tidy PECL extension to use the tidy library in-process,
725 * saving the overhead of spawning a new process.
727 * 'pear install tidy' should be able to compile the extension module.
732 function internalTidy( $text ) {
733 global $wgTidyConf, $IP, $wgDebugTidy;
734 $fname = 'Parser::internalTidy';
735 wfProfileIn( $fname );
738 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
739 $tidy->cleanRepair();
740 if( $tidy->getStatus() == 2 ) {
741 // 2 is magic number for fatal error
742 // http://www.php.net/manual/en/function.tidy-get-status.php
745 $cleansource = tidy_get_output( $tidy );
747 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
748 $cleansource .= "<!--\nTidy reports:\n" .
749 str_replace( '-->', '-->', $tidy->errorBuffer
) .
753 wfProfileOut( $fname );
758 * parse the wiki syntax used to render tables
762 function doTableStuff ( $text ) {
763 $fname = 'Parser::doTableStuff';
764 wfProfileIn( $fname );
766 $lines = explode ( "\n" , $text );
767 $td_history = array (); // Is currently a td tag open?
768 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
769 $tr_history = array (); // Is currently a tr tag open?
770 $tr_attributes = array (); // history of tr attributes
771 $has_opened_tr = array(); // Did this table open a <tr> element?
772 $indent_level = 0; // indent level of the table
773 foreach ( $lines as $key => $line )
775 $line = trim ( $line );
777 if( $line == '' ) { // empty line, go to next line
780 $first_character = $line{0};
783 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
784 // First check if we are starting a new table
785 $indent_level = strlen( $matches[1] );
787 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
788 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
790 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
791 array_push ( $td_history , false );
792 array_push ( $last_tag_history , '' );
793 array_push ( $tr_history , false );
794 array_push ( $tr_attributes , '' );
795 array_push ( $has_opened_tr , false );
796 } else if ( count ( $td_history ) == 0 ) {
797 // Don't do any of the following
799 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
800 // We are ending a table
801 $line = '</table>' . substr ( $line , 2 );
802 $last_tag = array_pop ( $last_tag_history );
804 if ( !array_pop ( $has_opened_tr ) ) {
805 $line = "<tr><td></td></tr>{$line}";
808 if ( array_pop ( $tr_history ) ) {
809 $line = "</tr>{$line}";
812 if ( array_pop ( $td_history ) ) {
813 $line = "</{$last_tag}>{$line}";
815 array_pop ( $tr_attributes );
816 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
817 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
818 // Now we have a table row
819 $line = preg_replace( '#^\|-+#', '', $line );
821 // Whats after the tag is now only attributes
822 $attributes = $this->mStripState
->unstripBoth( $line );
823 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
824 array_pop ( $tr_attributes );
825 array_push ( $tr_attributes , $attributes );
828 $last_tag = array_pop ( $last_tag_history );
829 array_pop ( $has_opened_tr );
830 array_push ( $has_opened_tr , true );
832 if ( array_pop ( $tr_history ) ) {
836 if ( array_pop ( $td_history ) ) {
837 $line = "</{$last_tag}>{$line}";
840 $lines[$key] = $line;
841 array_push ( $tr_history , false );
842 array_push ( $td_history , false );
843 array_push ( $last_tag_history , '' );
845 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
846 // This might be cell elements, td, th or captions
847 if ( substr ( $line , 0 , 2 ) == '|+' ) {
848 $first_character = '+';
849 $line = substr ( $line , 1 );
852 $line = substr ( $line , 1 );
854 if ( $first_character == '!' ) {
855 $line = str_replace ( '!!' , '||' , $line );
858 // Split up multiple cells on the same line.
859 // FIXME : This can result in improper nesting of tags processed
860 // by earlier parser steps, but should avoid splitting up eg
861 // attribute values containing literal "||".
862 $cells = StringUtils
::explodeMarkup( '||' , $line );
866 // Loop through each table cell
867 foreach ( $cells as $cell )
870 if ( $first_character != '+' )
872 $tr_after = array_pop ( $tr_attributes );
873 if ( !array_pop ( $tr_history ) ) {
874 $previous = "<tr{$tr_after}>\n";
876 array_push ( $tr_history , true );
877 array_push ( $tr_attributes , '' );
878 array_pop ( $has_opened_tr );
879 array_push ( $has_opened_tr , true );
882 $last_tag = array_pop ( $last_tag_history );
884 if ( array_pop ( $td_history ) ) {
885 $previous = "</{$last_tag}>{$previous}";
888 if ( $first_character == '|' ) {
890 } else if ( $first_character == '!' ) {
892 } else if ( $first_character == '+' ) {
893 $last_tag = 'caption';
898 array_push ( $last_tag_history , $last_tag );
900 // A cell could contain both parameters and data
901 $cell_data = explode ( '|' , $cell , 2 );
903 // Bug 553: Note that a '|' inside an invalid link should not
904 // be mistaken as delimiting cell parameters
905 if ( strpos( $cell_data[0], '[[' ) !== false ) {
906 $cell = "{$previous}<{$last_tag}>{$cell}";
907 } else if ( count ( $cell_data ) == 1 )
908 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
910 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
911 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
912 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
915 $lines[$key] .= $cell;
916 array_push ( $td_history , true );
921 // Closing open td, tr && table
922 while ( count ( $td_history ) > 0 )
924 if ( array_pop ( $td_history ) ) {
927 if ( array_pop ( $tr_history ) ) {
930 if ( !array_pop ( $has_opened_tr ) ) {
931 $lines[] = "<tr><td></td></tr>" ;
934 $lines[] = '</table>' ;
937 $output = implode ( "\n" , $lines ) ;
939 // special case: don't return empty table
940 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
944 wfProfileOut( $fname );
950 * Helper function for parse() that transforms wiki markup into
951 * HTML. Only called for $mOutputType == self::OT_HTML.
955 function internalParse( $text ) {
957 $fname = 'Parser::internalParse';
958 wfProfileIn( $fname );
960 # Hook to suspend the parser in this state
961 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
962 wfProfileOut( $fname );
966 $text = $this->replaceVariables( $text );
967 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
968 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
970 // Tables need to come after variable replacement for things to work
971 // properly; putting them before other transformations should keep
972 // exciting things like link expansions from showing up in surprising
974 $text = $this->doTableStuff( $text );
976 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
978 $text = $this->doDoubleUnderscore( $text );
979 $text = $this->doHeadings( $text );
980 if($this->mOptions
->getUseDynamicDates()) {
981 $df = DateFormatter
::getInstance();
982 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
984 $text = $this->doAllQuotes( $text );
985 $text = $this->replaceInternalLinks( $text );
986 $text = $this->replaceExternalLinks( $text );
988 # replaceInternalLinks may sometimes leave behind
989 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
990 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
992 $text = $this->doMagicLinks( $text );
993 $text = $this->formatHeadings( $text, $isMain );
995 wfProfileOut( $fname );
1000 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1001 * magic external links.
1005 function doMagicLinks( $text ) {
1006 wfProfileIn( __METHOD__
);
1007 $text = preg_replace_callback(
1009 <a.*?</a> | # Skip link text
1010 <.*?> | # Skip stuff inside HTML elements
1011 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1012 ISBN\s+(\b # ISBN, capture number as m[2]
1013 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1014 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1015 [0-9Xx] # check digit
1017 )!x', array( &$this, 'magicLinkCallback' ), $text );
1018 wfProfileOut( __METHOD__
);
1022 function magicLinkCallback( $m ) {
1023 if ( substr( $m[0], 0, 1 ) == '<' ) {
1026 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1028 $num = strtr( $isbn, array(
1033 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1034 $text = '<a href="' .
1035 $titleObj->escapeLocalUrl() .
1036 "\" class=\"internal\">ISBN $isbn</a>";
1038 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1042 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1044 $urlmsg = 'pubmedurl';
1047 throw new MWException( __METHOD__
.': unrecognised match type "' .
1048 substr($m[0], 0, 20 ) . '"' );
1051 $url = wfMsg( $urlmsg, $id);
1052 $sk = $this->mOptions
->getSkin();
1053 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1054 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1060 * Parse headers and return html
1064 function doHeadings( $text ) {
1065 $fname = 'Parser::doHeadings';
1066 wfProfileIn( $fname );
1067 for ( $i = 6; $i >= 1; --$i ) {
1068 $h = str_repeat( '=', $i );
1069 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1070 "<h$i>\\1</h$i>", $text );
1072 wfProfileOut( $fname );
1077 * Replace single quotes with HTML markup
1079 * @return string the altered text
1081 function doAllQuotes( $text ) {
1082 $fname = 'Parser::doAllQuotes';
1083 wfProfileIn( $fname );
1085 $lines = explode( "\n", $text );
1086 foreach ( $lines as $line ) {
1087 $outtext .= $this->doQuotes ( $line ) . "\n";
1089 $outtext = substr($outtext, 0,-1);
1090 wfProfileOut( $fname );
1095 * Helper function for doAllQuotes()
1097 public function doQuotes( $text ) {
1098 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1099 if ( count( $arr ) == 1 )
1103 # First, do some preliminary work. This may shift some apostrophes from
1104 # being mark-up to being text. It also counts the number of occurrences
1105 # of bold and italics mark-ups.
1109 foreach ( $arr as $r )
1111 if ( ( $i %
2 ) == 1 )
1113 # If there are ever four apostrophes, assume the first is supposed to
1114 # be text, and the remaining three constitute mark-up for bold text.
1115 if ( strlen( $arr[$i] ) == 4 )
1120 # If there are more than 5 apostrophes in a row, assume they're all
1121 # text except for the last 5.
1122 else if ( strlen( $arr[$i] ) > 5 )
1124 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1127 # Count the number of occurrences of bold and italics mark-ups.
1128 # We are not counting sequences of five apostrophes.
1129 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1130 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1131 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1136 # If there is an odd number of both bold and italics, it is likely
1137 # that one of the bold ones was meant to be an apostrophe followed
1138 # by italics. Which one we cannot know for certain, but it is more
1139 # likely to be one that has a single-letter word before it.
1140 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1143 $firstsingleletterword = -1;
1144 $firstmultiletterword = -1;
1146 foreach ( $arr as $r )
1148 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1150 $x1 = substr ($arr[$i-1], -1);
1151 $x2 = substr ($arr[$i-1], -2, 1);
1153 if ($firstspace == -1) $firstspace = $i;
1154 } else if ($x2 == ' ') {
1155 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1157 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1163 # If there is a single-letter word, use it!
1164 if ($firstsingleletterword > -1)
1166 $arr [ $firstsingleletterword ] = "''";
1167 $arr [ $firstsingleletterword-1 ] .= "'";
1169 # If not, but there's a multi-letter word, use that one.
1170 else if ($firstmultiletterword > -1)
1172 $arr [ $firstmultiletterword ] = "''";
1173 $arr [ $firstmultiletterword-1 ] .= "'";
1175 # ... otherwise use the first one that has neither.
1176 # (notice that it is possible for all three to be -1 if, for example,
1177 # there is only one pentuple-apostrophe in the line)
1178 else if ($firstspace > -1)
1180 $arr [ $firstspace ] = "''";
1181 $arr [ $firstspace-1 ] .= "'";
1185 # Now let's actually convert our apostrophic mush to HTML!
1190 foreach ($arr as $r)
1194 if ($state == 'both')
1201 if (strlen ($r) == 2)
1204 { $output .= '</i>'; $state = ''; }
1205 else if ($state == 'bi')
1206 { $output .= '</i>'; $state = 'b'; }
1207 else if ($state == 'ib')
1208 { $output .= '</b></i><b>'; $state = 'b'; }
1209 else if ($state == 'both')
1210 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1211 else # $state can be 'b' or ''
1212 { $output .= '<i>'; $state .= 'i'; }
1214 else if (strlen ($r) == 3)
1217 { $output .= '</b>'; $state = ''; }
1218 else if ($state == 'bi')
1219 { $output .= '</i></b><i>'; $state = 'i'; }
1220 else if ($state == 'ib')
1221 { $output .= '</b>'; $state = 'i'; }
1222 else if ($state == 'both')
1223 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1224 else # $state can be 'i' or ''
1225 { $output .= '<b>'; $state .= 'b'; }
1227 else if (strlen ($r) == 5)
1230 { $output .= '</b><i>'; $state = 'i'; }
1231 else if ($state == 'i')
1232 { $output .= '</i><b>'; $state = 'b'; }
1233 else if ($state == 'bi')
1234 { $output .= '</i></b>'; $state = ''; }
1235 else if ($state == 'ib')
1236 { $output .= '</b></i>'; $state = ''; }
1237 else if ($state == 'both')
1238 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1239 else # ($state == '')
1240 { $buffer = ''; $state = 'both'; }
1245 # Now close all remaining tags. Notice that the order is important.
1246 if ($state == 'b' ||
$state == 'ib')
1248 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1252 # There might be lonely ''''', so make sure we have a buffer
1253 if ($state == 'both' && $buffer)
1254 $output .= '<b><i>'.$buffer.'</i></b>';
1260 * Replace external links
1262 * Note: this is all very hackish and the order of execution matters a lot.
1263 * Make sure to run maintenance/parserTests.php if you change this code.
1267 function replaceExternalLinks( $text ) {
1269 $fname = 'Parser::replaceExternalLinks';
1270 wfProfileIn( $fname );
1272 $sk = $this->mOptions
->getSkin();
1274 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1276 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1279 while ( $i<count( $bits ) ) {
1281 $protocol = $bits[$i++
];
1282 $text = $bits[$i++
];
1283 $trail = $bits[$i++
];
1285 # The characters '<' and '>' (which were escaped by
1286 # removeHTMLtags()) should not be included in
1287 # URLs, per RFC 2396.
1289 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1290 $text = substr($url, $m2[0][1]) . ' ' . $text;
1291 $url = substr($url, 0, $m2[0][1]);
1294 # If the link text is an image URL, replace it with an <img> tag
1295 # This happened by accident in the original parser, but some people used it extensively
1296 $img = $this->maybeMakeExternalImage( $text );
1297 if ( $img !== false ) {
1303 # Set linktype for CSS - if URL==text, link is essentially free
1304 $linktype = ($text == $url) ?
'free' : 'text';
1306 # No link text, e.g. [http://domain.tld/some.link]
1307 if ( $text == '' ) {
1308 # Autonumber if allowed. See bug #5918
1309 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1310 $text = '[' . ++
$this->mAutonumber
. ']';
1311 $linktype = 'autonumber';
1313 # Otherwise just use the URL
1314 $text = htmlspecialchars( $url );
1318 # Have link text, e.g. [http://domain.tld/some.link text]s
1320 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1323 $text = $wgContLang->markNoConversion($text);
1325 $url = Sanitizer
::cleanUrl( $url );
1327 # Process the trail (i.e. everything after this link up until start of the next link),
1328 # replacing any non-bracketed links
1329 $trail = $this->replaceFreeExternalLinks( $trail );
1331 # Use the encoded URL
1332 # This means that users can paste URLs directly into the text
1333 # Funny characters like ö aren't valid in URLs anyway
1334 # This was changed in August 2004
1335 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1337 # Register link in the output object.
1338 # Replace unnecessary URL escape codes with the referenced character
1339 # This prevents spammers from hiding links from the filters
1340 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1341 $this->mOutput
->addExternalLink( $pasteurized );
1344 wfProfileOut( $fname );
1349 * Replace anything that looks like a URL with a link
1352 function replaceFreeExternalLinks( $text ) {
1354 $fname = 'Parser::replaceFreeExternalLinks';
1355 wfProfileIn( $fname );
1357 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1358 $s = array_shift( $bits );
1361 $sk = $this->mOptions
->getSkin();
1363 while ( $i < count( $bits ) ){
1364 $protocol = $bits[$i++
];
1365 $remainder = $bits[$i++
];
1368 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1369 # Found some characters after the protocol that look promising
1370 $url = $protocol . $m[1];
1373 # special case: handle urls as url args:
1374 # http://www.example.com/foo?=http://www.example.com/bar
1375 if(strlen($trail) == 0 &&
1377 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1378 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1381 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1386 # The characters '<' and '>' (which were escaped by
1387 # removeHTMLtags()) should not be included in
1388 # URLs, per RFC 2396.
1390 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1391 $trail = substr($url, $m2[0][1]) . $trail;
1392 $url = substr($url, 0, $m2[0][1]);
1395 # Move trailing punctuation to $trail
1397 # If there is no left bracket, then consider right brackets fair game too
1398 if ( strpos( $url, '(' ) === false ) {
1402 $numSepChars = strspn( strrev( $url ), $sep );
1403 if ( $numSepChars ) {
1404 $trail = substr( $url, -$numSepChars ) . $trail;
1405 $url = substr( $url, 0, -$numSepChars );
1408 $url = Sanitizer
::cleanUrl( $url );
1410 # Is this an external image?
1411 $text = $this->maybeMakeExternalImage( $url );
1412 if ( $text === false ) {
1413 # Not an image, make a link
1414 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1415 # Register it in the output object...
1416 # Replace unnecessary URL escape codes with their equivalent characters
1417 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1418 $this->mOutput
->addExternalLink( $pasteurized );
1420 $s .= $text . $trail;
1422 $s .= $protocol . $remainder;
1425 wfProfileOut( $fname );
1430 * Replace unusual URL escape codes with their equivalent characters
1434 * @todo This can merge genuinely required bits in the path or query string,
1435 * breaking legit URLs. A proper fix would treat the various parts of
1436 * the URL differently; as a workaround, just use the output for
1437 * statistical records, not for actual linking/output.
1439 static function replaceUnusualEscapes( $url ) {
1440 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1441 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1445 * Callback function used in replaceUnusualEscapes().
1446 * Replaces unusual URL escape codes with their equivalent character
1450 private static function replaceUnusualEscapesCallback( $matches ) {
1451 $char = urldecode( $matches[0] );
1452 $ord = ord( $char );
1453 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1454 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1455 // No, shouldn't be escaped
1458 // Yes, leave it escaped
1464 * make an image if it's allowed, either through the global
1465 * option or through the exception
1468 function maybeMakeExternalImage( $url ) {
1469 $sk = $this->mOptions
->getSkin();
1470 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1471 $imagesexception = !empty($imagesfrom);
1473 if ( $this->mOptions
->getAllowExternalImages()
1474 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1475 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1477 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1484 * Process [[ ]] wikilinks
1488 function replaceInternalLinks( $s ) {
1490 static $fname = 'Parser::replaceInternalLinks' ;
1492 wfProfileIn( $fname );
1494 wfProfileIn( $fname.'-setup' );
1496 # the % is needed to support urlencoded titles as well
1497 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1499 $sk = $this->mOptions
->getSkin();
1501 #split the entire text string on occurences of [[
1502 $a = explode( '[[', ' ' . $s );
1503 #get the first element (all text up to first [[), and remove the space we added
1504 $s = array_shift( $a );
1505 $s = substr( $s, 1 );
1507 # Match a link having the form [[namespace:link|alternate]]trail
1509 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1510 # Match cases where there is no "]]", which might still be images
1511 static $e1_img = FALSE;
1512 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1514 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1516 if ( $useLinkPrefixExtension ) {
1517 # Match the end of a line for a word that's not followed by whitespace,
1518 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1519 $e2 = wfMsgForContent( 'linkprefix' );
1522 if( is_null( $this->mTitle
) ) {
1523 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1525 $nottalk = !$this->mTitle
->isTalkPage();
1527 if ( $useLinkPrefixExtension ) {
1529 if ( preg_match( $e2, $s, $m ) ) {
1530 $first_prefix = $m[2];
1532 $first_prefix = false;
1538 if($wgContLang->hasVariants()) {
1539 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1541 $selflink = array($this->mTitle
->getPrefixedText());
1543 $useSubpages = $this->areSubpagesAllowed();
1544 wfProfileOut( $fname.'-setup' );
1546 # Loop for each link
1547 for ($k = 0; isset( $a[$k] ); $k++
) {
1549 if ( $useLinkPrefixExtension ) {
1550 wfProfileIn( $fname.'-prefixhandling' );
1551 if ( preg_match( $e2, $s, $m ) ) {
1559 $prefix = $first_prefix;
1560 $first_prefix = false;
1562 wfProfileOut( $fname.'-prefixhandling' );
1565 $might_be_img = false;
1567 wfProfileIn( "$fname-e1" );
1568 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1570 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1571 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1572 # the real problem is with the $e1 regex
1575 # Still some problems for cases where the ] is meant to be outside punctuation,
1576 # and no image is in sight. See bug 2095.
1579 substr( $m[3], 0, 1 ) === ']' &&
1580 strpos($text, '[') !== false
1583 $text .= ']'; # so that replaceExternalLinks($text) works later
1584 $m[3] = substr( $m[3], 1 );
1586 # fix up urlencoded title texts
1587 if( strpos( $m[1], '%' ) !== false ) {
1588 # Should anchors '#' also be rejected?
1589 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1592 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1593 $might_be_img = true;
1595 if ( strpos( $m[1], '%' ) !== false ) {
1596 $m[1] = urldecode($m[1]);
1599 } else { # Invalid form; output directly
1600 $s .= $prefix . '[[' . $line ;
1601 wfProfileOut( "$fname-e1" );
1604 wfProfileOut( "$fname-e1" );
1605 wfProfileIn( "$fname-misc" );
1607 # Don't allow internal links to pages containing
1608 # PROTO: where PROTO is a valid URL protocol; these
1609 # should be external links.
1610 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1611 $s .= $prefix . '[[' . $line ;
1615 # Make subpage if necessary
1616 if( $useSubpages ) {
1617 $link = $this->maybeDoSubpageLink( $m[1], $text );
1622 $noforce = (substr($m[1], 0, 1) != ':');
1624 # Strip off leading ':'
1625 $link = substr($link, 1);
1628 wfProfileOut( "$fname-misc" );
1629 wfProfileIn( "$fname-title" );
1630 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1632 $s .= $prefix . '[[' . $line;
1633 wfProfileOut( "$fname-title" );
1637 $ns = $nt->getNamespace();
1638 $iw = $nt->getInterWiki();
1639 wfProfileOut( "$fname-title" );
1641 if ($might_be_img) { # if this is actually an invalid link
1642 wfProfileIn( "$fname-might_be_img" );
1643 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1645 while (isset ($a[$k+
1]) ) {
1646 #look at the next 'line' to see if we can close it there
1647 $spliced = array_splice( $a, $k +
1, 1 );
1648 $next_line = array_shift( $spliced );
1649 $m = explode( ']]', $next_line, 3 );
1650 if ( count( $m ) == 3 ) {
1651 # the first ]] closes the inner link, the second the image
1653 $text .= "[[{$m[0]}]]{$m[1]}";
1656 } elseif ( count( $m ) == 2 ) {
1657 #if there's exactly one ]] that's fine, we'll keep looking
1658 $text .= "[[{$m[0]}]]{$m[1]}";
1660 #if $next_line is invalid too, we need look no further
1661 $text .= '[[' . $next_line;
1666 # we couldn't find the end of this imageLink, so output it raw
1667 #but don't ignore what might be perfectly normal links in the text we've examined
1668 $text = $this->replaceInternalLinks($text);
1669 $s .= "{$prefix}[[$link|$text";
1670 # note: no $trail, because without an end, there *is* no trail
1671 wfProfileOut( "$fname-might_be_img" );
1674 } else { #it's not an image, so output it raw
1675 $s .= "{$prefix}[[$link|$text";
1676 # note: no $trail, because without an end, there *is* no trail
1677 wfProfileOut( "$fname-might_be_img" );
1680 wfProfileOut( "$fname-might_be_img" );
1683 $wasblank = ( '' == $text );
1684 if( $wasblank ) $text = $link;
1686 # Link not escaped by : , create the various objects
1690 wfProfileIn( "$fname-interwiki" );
1691 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1692 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1693 $s = rtrim($s . $prefix);
1694 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1695 wfProfileOut( "$fname-interwiki" );
1698 wfProfileOut( "$fname-interwiki" );
1700 if ( $ns == NS_IMAGE
) {
1701 wfProfileIn( "$fname-image" );
1702 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1703 # recursively parse links inside the image caption
1704 # actually, this will parse them in any other parameters, too,
1705 # but it might be hard to fix that, and it doesn't matter ATM
1706 $text = $this->replaceExternalLinks($text);
1707 $text = $this->replaceInternalLinks($text);
1709 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1710 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1711 $this->mOutput
->addImage( $nt->getDBkey() );
1713 wfProfileOut( "$fname-image" );
1716 # We still need to record the image's presence on the page
1717 $this->mOutput
->addImage( $nt->getDBkey() );
1719 wfProfileOut( "$fname-image" );
1723 if ( $ns == NS_CATEGORY
) {
1724 wfProfileIn( "$fname-category" );
1725 $s = rtrim($s . "\n"); # bug 87
1728 $sortkey = $this->getDefaultSort();
1732 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1733 $sortkey = str_replace( "\n", '', $sortkey );
1734 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1735 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1738 * Strip the whitespace Category links produce, see bug 87
1739 * @todo We might want to use trim($tmp, "\n") here.
1741 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1743 wfProfileOut( "$fname-category" );
1748 # Self-link checking
1749 if( $nt->getFragment() === '' ) {
1750 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1751 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1756 # Special and Media are pseudo-namespaces; no pages actually exist in them
1757 if( $ns == NS_MEDIA
) {
1758 # Give extensions a chance to select the file revision for us
1759 $skip = $time = false;
1760 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1762 $link = $sk->makeLinkObj( $nt );
1764 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1766 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1767 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1768 $this->mOutput
->addImage( $nt->getDBkey() );
1770 } elseif( $ns == NS_SPECIAL
) {
1771 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1772 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1774 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1777 } elseif( $ns == NS_IMAGE
) {
1778 $img = wfFindFile( $nt );
1780 // Force a blue link if the file exists; may be a remote
1781 // upload on the shared repository, and we want to see its
1782 // auto-generated page.
1783 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1784 $this->mOutput
->addLink( $nt );
1788 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1790 wfProfileOut( $fname );
1795 * Make a link placeholder. The text returned can be later resolved to a real link with
1796 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1797 * parsing of interwiki links, and secondly to allow all existence checks and
1798 * article length checks (for stub links) to be bundled into a single query.
1801 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1802 wfProfileIn( __METHOD__
);
1803 if ( ! is_object($nt) ) {
1805 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1807 # Separate the link trail from the rest of the link
1808 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1810 if ( $nt->isExternal() ) {
1811 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1812 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1813 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1815 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1816 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1817 $this->mLinkHolders
['queries'][] = $query;
1818 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1819 $this->mLinkHolders
['titles'][] = $nt;
1821 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1824 wfProfileOut( __METHOD__
);
1829 * Render a forced-blue link inline; protect against double expansion of
1830 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1831 * Since this little disaster has to split off the trail text to avoid
1832 * breaking URLs in the following text without breaking trails on the
1833 * wiki links, it's been made into a horrible function.
1836 * @param string $text
1837 * @param string $query
1838 * @param string $trail
1839 * @param string $prefix
1840 * @return string HTML-wikitext mix oh yuck
1842 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1843 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1844 $sk = $this->mOptions
->getSkin();
1845 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1846 return $this->armorLinks( $link ) . $trail;
1850 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1851 * going to go through further parsing steps before inline URL expansion.
1853 * In particular this is important when using action=render, which causes
1854 * full URLs to be included.
1856 * Oh man I hate our multi-layer parser!
1858 * @param string more-or-less HTML
1859 * @return string less-or-more HTML with NOPARSE bits
1861 function armorLinks( $text ) {
1862 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1863 "{$this->mUniqPrefix}NOPARSE$1", $text );
1867 * Return true if subpage links should be expanded on this page.
1870 function areSubpagesAllowed() {
1871 # Some namespaces don't allow subpages
1872 global $wgNamespacesWithSubpages;
1873 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1877 * Handle link to subpage if necessary
1878 * @param string $target the source of the link
1879 * @param string &$text the link text, modified as necessary
1880 * @return string the full name of the link
1883 function maybeDoSubpageLink($target, &$text) {
1886 # :Foobar -- override special treatment of prefix (images, language links)
1887 # /Foobar -- convert to CurrentPage/Foobar
1888 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1889 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1890 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1892 $fname = 'Parser::maybeDoSubpageLink';
1893 wfProfileIn( $fname );
1894 $ret = $target; # default return value is no change
1896 # Some namespaces don't allow subpages,
1897 # so only perform processing if subpages are allowed
1898 if( $this->areSubpagesAllowed() ) {
1899 $hash = strpos( $target, '#' );
1900 if( $hash !== false ) {
1901 $suffix = substr( $target, $hash );
1902 $target = substr( $target, 0, $hash );
1907 $target = trim( $target );
1908 # Look at the first character
1909 if( $target != '' && $target{0} == '/' ) {
1910 # / at end means we don't want the slash to be shown
1912 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1913 if( $trailingSlashes ) {
1914 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1916 $noslash = substr( $target, 1 );
1919 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1920 if( '' === $text ) {
1921 $text = $target . $suffix;
1922 } # this might be changed for ugliness reasons
1924 # check for .. subpage backlinks
1926 $nodotdot = $target;
1927 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1929 $nodotdot = substr( $nodotdot, 3 );
1931 if($dotdotcount > 0) {
1932 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1933 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1934 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1935 # / at the end means don't show full path
1936 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1937 $nodotdot = substr( $nodotdot, 0, -1 );
1938 if( '' === $text ) {
1939 $text = $nodotdot . $suffix;
1942 $nodotdot = trim( $nodotdot );
1943 if( $nodotdot != '' ) {
1944 $ret .= '/' . $nodotdot;
1952 wfProfileOut( $fname );
1957 * Used by doBlockLevels()
1960 /* private */ function closeParagraph() {
1962 if ( '' != $this->mLastSection
) {
1963 $result = '</' . $this->mLastSection
. ">\n";
1965 $this->mInPre
= false;
1966 $this->mLastSection
= '';
1969 # getCommon() returns the length of the longest common substring
1970 # of both arguments, starting at the beginning of both.
1972 /* private */ function getCommon( $st1, $st2 ) {
1973 $fl = strlen( $st1 );
1974 $shorter = strlen( $st2 );
1975 if ( $fl < $shorter ) { $shorter = $fl; }
1977 for ( $i = 0; $i < $shorter; ++
$i ) {
1978 if ( $st1{$i} != $st2{$i} ) { break; }
1982 # These next three functions open, continue, and close the list
1983 # element appropriate to the prefix character passed into them.
1985 /* private */ function openList( $char ) {
1986 $result = $this->closeParagraph();
1988 if ( '*' == $char ) { $result .= '<ul><li>'; }
1989 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1990 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1991 else if ( ';' == $char ) {
1992 $result .= '<dl><dt>';
1993 $this->mDTopen
= true;
1995 else { $result = '<!-- ERR 1 -->'; }
2000 /* private */ function nextItem( $char ) {
2001 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
2002 else if ( ':' == $char ||
';' == $char ) {
2004 if ( $this->mDTopen
) { $close = '</dt>'; }
2005 if ( ';' == $char ) {
2006 $this->mDTopen
= true;
2007 return $close . '<dt>';
2009 $this->mDTopen
= false;
2010 return $close . '<dd>';
2013 return '<!-- ERR 2 -->';
2016 /* private */ function closeList( $char ) {
2017 if ( '*' == $char ) { $text = '</li></ul>'; }
2018 else if ( '#' == $char ) { $text = '</li></ol>'; }
2019 else if ( ':' == $char ) {
2020 if ( $this->mDTopen
) {
2021 $this->mDTopen
= false;
2022 $text = '</dt></dl>';
2024 $text = '</dd></dl>';
2027 else { return '<!-- ERR 3 -->'; }
2033 * Make lists from lines starting with ':', '*', '#', etc.
2036 * @return string the lists rendered as HTML
2038 function doBlockLevels( $text, $linestart ) {
2039 $fname = 'Parser::doBlockLevels';
2040 wfProfileIn( $fname );
2042 # Parsing through the text line by line. The main thing
2043 # happening here is handling of block-level elements p, pre,
2044 # and making lists from lines starting with * # : etc.
2046 $textLines = explode( "\n", $text );
2048 $lastPrefix = $output = '';
2049 $this->mDTopen
= $inBlockElem = false;
2051 $paragraphStack = false;
2053 if ( !$linestart ) {
2054 $output .= array_shift( $textLines );
2056 foreach ( $textLines as $oLine ) {
2057 $lastPrefixLength = strlen( $lastPrefix );
2058 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2059 $preOpenMatch = preg_match('/<pre/i', $oLine );
2060 if ( !$this->mInPre
) {
2061 # Multiple prefixes may abut each other for nested lists.
2062 $prefixLength = strspn( $oLine, '*#:;' );
2063 $pref = substr( $oLine, 0, $prefixLength );
2066 $pref2 = str_replace( ';', ':', $pref );
2067 $t = substr( $oLine, $prefixLength );
2068 $this->mInPre
= !empty($preOpenMatch);
2070 # Don't interpret any other prefixes in preformatted text
2072 $pref = $pref2 = '';
2077 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2078 # Same as the last item, so no need to deal with nesting or opening stuff
2079 $output .= $this->nextItem( substr( $pref, -1 ) );
2080 $paragraphStack = false;
2082 if ( substr( $pref, -1 ) == ';') {
2083 # The one nasty exception: definition lists work like this:
2084 # ; title : definition text
2085 # So we check for : in the remainder text to split up the
2086 # title and definition, without b0rking links.
2088 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2090 $output .= $term . $this->nextItem( ':' );
2093 } elseif( $prefixLength ||
$lastPrefixLength ) {
2094 # Either open or close a level...
2095 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2096 $paragraphStack = false;
2098 while( $commonPrefixLength < $lastPrefixLength ) {
2099 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2100 --$lastPrefixLength;
2102 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2103 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2105 while ( $prefixLength > $commonPrefixLength ) {
2106 $char = substr( $pref, $commonPrefixLength, 1 );
2107 $output .= $this->openList( $char );
2109 if ( ';' == $char ) {
2110 # FIXME: This is dupe of code above
2111 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2113 $output .= $term . $this->nextItem( ':' );
2116 ++
$commonPrefixLength;
2118 $lastPrefix = $pref2;
2120 if( 0 == $prefixLength ) {
2121 wfProfileIn( "$fname-paragraph" );
2122 # No prefix (not in list)--go to paragraph mode
2123 // XXX: use a stack for nestable elements like span, table and div
2124 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2125 $closematch = preg_match(
2126 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2127 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2128 if ( $openmatch or $closematch ) {
2129 $paragraphStack = false;
2130 #Â TODO bug 5718: paragraph closed
2131 $output .= $this->closeParagraph();
2132 if ( $preOpenMatch and !$preCloseMatch ) {
2133 $this->mInPre
= true;
2135 if ( $closematch ) {
2136 $inBlockElem = false;
2138 $inBlockElem = true;
2140 } else if ( !$inBlockElem && !$this->mInPre
) {
2141 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2143 if ($this->mLastSection
!= 'pre') {
2144 $paragraphStack = false;
2145 $output .= $this->closeParagraph().'<pre>';
2146 $this->mLastSection
= 'pre';
2148 $t = substr( $t, 1 );
2151 if ( '' == trim($t) ) {
2152 if ( $paragraphStack ) {
2153 $output .= $paragraphStack.'<br />';
2154 $paragraphStack = false;
2155 $this->mLastSection
= 'p';
2157 if ($this->mLastSection
!= 'p' ) {
2158 $output .= $this->closeParagraph();
2159 $this->mLastSection
= '';
2160 $paragraphStack = '<p>';
2162 $paragraphStack = '</p><p>';
2166 if ( $paragraphStack ) {
2167 $output .= $paragraphStack;
2168 $paragraphStack = false;
2169 $this->mLastSection
= 'p';
2170 } else if ($this->mLastSection
!= 'p') {
2171 $output .= $this->closeParagraph().'<p>';
2172 $this->mLastSection
= 'p';
2177 wfProfileOut( "$fname-paragraph" );
2179 // somewhere above we forget to get out of pre block (bug 785)
2180 if($preCloseMatch && $this->mInPre
) {
2181 $this->mInPre
= false;
2183 if ($paragraphStack === false) {
2187 while ( $prefixLength ) {
2188 $output .= $this->closeList( $pref2{$prefixLength-1} );
2191 if ( '' != $this->mLastSection
) {
2192 $output .= '</' . $this->mLastSection
. '>';
2193 $this->mLastSection
= '';
2196 wfProfileOut( $fname );
2201 * Split up a string on ':', ignoring any occurences inside tags
2202 * to prevent illegal overlapping.
2203 * @param string $str the string to split
2204 * @param string &$before set to everything before the ':'
2205 * @param string &$after set to everything after the ':'
2206 * return string the position of the ':', or false if none found
2208 function findColonNoLinks($str, &$before, &$after) {
2209 $fname = 'Parser::findColonNoLinks';
2210 wfProfileIn( $fname );
2212 $pos = strpos( $str, ':' );
2213 if( $pos === false ) {
2215 wfProfileOut( $fname );
2219 $lt = strpos( $str, '<' );
2220 if( $lt === false ||
$lt > $pos ) {
2221 // Easy; no tag nesting to worry about
2222 $before = substr( $str, 0, $pos );
2223 $after = substr( $str, $pos+
1 );
2224 wfProfileOut( $fname );
2228 // Ugly state machine to walk through avoiding tags.
2229 $state = self
::COLON_STATE_TEXT
;
2231 $len = strlen( $str );
2232 for( $i = 0; $i < $len; $i++
) {
2236 // (Using the number is a performance hack for common cases)
2237 case 0: // self::COLON_STATE_TEXT:
2240 // Could be either a <start> tag or an </end> tag
2241 $state = self
::COLON_STATE_TAGSTART
;
2246 $before = substr( $str, 0, $i );
2247 $after = substr( $str, $i +
1 );
2248 wfProfileOut( $fname );
2251 // Embedded in a tag; don't break it.
2254 // Skip ahead looking for something interesting
2255 $colon = strpos( $str, ':', $i );
2256 if( $colon === false ) {
2257 // Nothing else interesting
2258 wfProfileOut( $fname );
2261 $lt = strpos( $str, '<', $i );
2262 if( $stack === 0 ) {
2263 if( $lt === false ||
$colon < $lt ) {
2265 $before = substr( $str, 0, $colon );
2266 $after = substr( $str, $colon +
1 );
2267 wfProfileOut( $fname );
2271 if( $lt === false ) {
2272 // Nothing else interesting to find; abort!
2273 // We're nested, but there's no close tags left. Abort!
2276 // Skip ahead to next tag start
2278 $state = self
::COLON_STATE_TAGSTART
;
2281 case 1: // self::COLON_STATE_TAG:
2286 $state = self
::COLON_STATE_TEXT
;
2289 // Slash may be followed by >?
2290 $state = self
::COLON_STATE_TAGSLASH
;
2296 case 2: // self::COLON_STATE_TAGSTART:
2299 $state = self
::COLON_STATE_CLOSETAG
;
2302 $state = self
::COLON_STATE_COMMENT
;
2305 // Illegal early close? This shouldn't happen D:
2306 $state = self
::COLON_STATE_TEXT
;
2309 $state = self
::COLON_STATE_TAG
;
2312 case 3: // self::COLON_STATE_CLOSETAG:
2317 wfDebug( "Invalid input in $fname; too many close tags\n" );
2318 wfProfileOut( $fname );
2321 $state = self
::COLON_STATE_TEXT
;
2324 case self
::COLON_STATE_TAGSLASH
:
2326 // Yes, a self-closed tag <blah/>
2327 $state = self
::COLON_STATE_TEXT
;
2329 // Probably we're jumping the gun, and this is an attribute
2330 $state = self
::COLON_STATE_TAG
;
2333 case 5: // self::COLON_STATE_COMMENT:
2335 $state = self
::COLON_STATE_COMMENTDASH
;
2338 case self
::COLON_STATE_COMMENTDASH
:
2340 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2342 $state = self
::COLON_STATE_COMMENT
;
2345 case self
::COLON_STATE_COMMENTDASHDASH
:
2347 $state = self
::COLON_STATE_TEXT
;
2349 $state = self
::COLON_STATE_COMMENT
;
2353 throw new MWException( "State machine error in $fname" );
2357 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2360 wfProfileOut( $fname );
2365 * Return value of a magic variable (like PAGENAME)
2369 function getVariableValue( $index ) {
2370 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2373 * Some of these require message or data lookups and can be
2374 * expensive to check many times.
2376 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2377 if ( isset( $this->mVarCache
[$index] ) ) {
2378 return $this->mVarCache
[$index];
2382 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2383 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2386 global $wgLocaltimezone;
2387 if ( isset( $wgLocaltimezone ) ) {
2388 $oldtz = getenv( 'TZ' );
2389 putenv( 'TZ='.$wgLocaltimezone );
2392 wfSuppressWarnings(); // E_STRICT system time bitching
2393 $localTimestamp = date( 'YmdHis', $ts );
2394 $localMonth = date( 'm', $ts );
2395 $localMonthName = date( 'n', $ts );
2396 $localDay = date( 'j', $ts );
2397 $localDay2 = date( 'd', $ts );
2398 $localDayOfWeek = date( 'w', $ts );
2399 $localWeek = date( 'W', $ts );
2400 $localYear = date( 'Y', $ts );
2401 $localHour = date( 'H', $ts );
2402 if ( isset( $wgLocaltimezone ) ) {
2403 putenv( 'TZ='.$oldtz );
2405 wfRestoreWarnings();
2408 case 'currentmonth':
2409 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2410 case 'currentmonthname':
2411 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2412 case 'currentmonthnamegen':
2413 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2414 case 'currentmonthabbrev':
2415 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2417 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2419 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2421 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2422 case 'localmonthname':
2423 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2424 case 'localmonthnamegen':
2425 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2426 case 'localmonthabbrev':
2427 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2429 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2431 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2433 return wfEscapeWikiText( $this->mTitle
->getText() );
2435 return $this->mTitle
->getPartialURL();
2436 case 'fullpagename':
2437 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2438 case 'fullpagenamee':
2439 return $this->mTitle
->getPrefixedURL();
2441 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2442 case 'subpagenamee':
2443 return $this->mTitle
->getSubpageUrlForm();
2444 case 'basepagename':
2445 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2446 case 'basepagenamee':
2447 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2448 case 'talkpagename':
2449 if( $this->mTitle
->canTalk() ) {
2450 $talkPage = $this->mTitle
->getTalkPage();
2451 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2455 case 'talkpagenamee':
2456 if( $this->mTitle
->canTalk() ) {
2457 $talkPage = $this->mTitle
->getTalkPage();
2458 return $talkPage->getPrefixedUrl();
2462 case 'subjectpagename':
2463 $subjPage = $this->mTitle
->getSubjectPage();
2464 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2465 case 'subjectpagenamee':
2466 $subjPage = $this->mTitle
->getSubjectPage();
2467 return $subjPage->getPrefixedUrl();
2469 // Let the edit saving system know we should parse the page
2470 // *after* a revision ID has been assigned.
2471 $this->mOutput
->setFlag( 'vary-revision' );
2472 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2473 return $this->mRevisionId
;
2475 // Let the edit saving system know we should parse the page
2476 // *after* a revision ID has been assigned. This is for null edits.
2477 $this->mOutput
->setFlag( 'vary-revision' );
2478 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2479 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2480 case 'revisionday2':
2481 // Let the edit saving system know we should parse the page
2482 // *after* a revision ID has been assigned. This is for null edits.
2483 $this->mOutput
->setFlag( 'vary-revision' );
2484 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2485 return substr( $this->getRevisionTimestamp(), 6, 2 );
2486 case 'revisionmonth':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput
->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2491 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2492 case 'revisionyear':
2493 // Let the edit saving system know we should parse the page
2494 // *after* a revision ID has been assigned. This is for null edits.
2495 $this->mOutput
->setFlag( 'vary-revision' );
2496 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2497 return substr( $this->getRevisionTimestamp(), 0, 4 );
2498 case 'revisiontimestamp':
2499 // Let the edit saving system know we should parse the page
2500 // *after* a revision ID has been assigned. This is for null edits.
2501 $this->mOutput
->setFlag( 'vary-revision' );
2502 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2503 return $this->getRevisionTimestamp();
2505 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2507 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2509 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2511 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2512 case 'subjectspace':
2513 return $this->mTitle
->getSubjectNsText();
2514 case 'subjectspacee':
2515 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2516 case 'currentdayname':
2517 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2519 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2521 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2523 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2525 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2526 // int to remove the padding
2527 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2530 case 'localdayname':
2531 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2535 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2539 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2540 // int to remove the padding
2541 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2544 case 'numberofarticles':
2545 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2546 case 'numberoffiles':
2547 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2548 case 'numberofusers':
2549 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2550 case 'numberofpages':
2551 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2552 case 'numberofadmins':
2553 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2554 case 'numberofedits':
2555 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2556 case 'currenttimestamp':
2557 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2558 case 'localtimestamp':
2559 return $this->mVarCache
[$index] = $localTimestamp;
2560 case 'currentversion':
2561 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2567 return $wgServerName;
2569 return $wgScriptPath;
2570 case 'directionmark':
2571 return $wgContLang->getDirMark();
2572 case 'contentlanguage':
2573 global $wgContLanguageCode;
2574 return $wgContLanguageCode;
2577 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2585 * initialise the magic variables (like CURRENTMONTHNAME)
2589 function initialiseVariables() {
2590 $fname = 'Parser::initialiseVariables';
2591 wfProfileIn( $fname );
2592 $variableIDs = MagicWord
::getVariableIDs();
2594 $this->mVariables
= new MagicWordArray( $variableIDs );
2595 wfProfileOut( $fname );
2599 * Preprocess some wikitext and return the document tree.
2600 * This is the ghost of replace_variables().
2602 * @param string $text The text to parse
2603 * @param integer flags Bitwise combination of:
2604 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2605 * included. Default is to assume a direct page view.
2607 * The generated DOM tree must depend only on the input text and the flags.
2608 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2610 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2611 * change in the DOM tree for a given text, must be passed through the section identifier
2612 * in the section edit link and thus back to extractSections().
2614 * The output of this function is currently only cached in process memory, but a persistent
2615 * cache may be implemented at a later date which takes further advantage of these strict
2616 * dependency requirements.
2620 function preprocessToDom ( $text, $flags = 0 ) {
2621 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2626 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2628 public static function splitWhitespace( $s ) {
2629 $ltrimmed = ltrim( $s );
2630 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2631 $trimmed = rtrim( $ltrimmed );
2632 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2634 $w2 = substr( $ltrimmed, -$diff );
2638 return array( $w1, $trimmed, $w2 );
2642 * Replace magic variables, templates, and template arguments
2643 * with the appropriate text. Templates are substituted recursively,
2644 * taking care to avoid infinite loops.
2646 * Note that the substitution depends on value of $mOutputType:
2647 * self::OT_WIKI: only {{subst:}} templates
2648 * self::OT_PREPROCESS: templates but not extension tags
2649 * self::OT_HTML: all templates and extension tags
2651 * @param string $tex The text to transform
2652 * @param PPFrame $frame Object describing the arguments passed to the template
2653 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2656 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2657 # Prevent too big inclusions
2658 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2662 $fname = __METHOD__
;
2663 wfProfileIn( $fname );
2665 if ( $frame === false ) {
2666 $frame = $this->getPreprocessor()->newFrame();
2667 } elseif ( !( $frame instanceof PPFrame
) ) {
2668 throw new MWException( __METHOD__
. ' called using the old argument format' );
2671 $dom = $this->preprocessToDom( $text );
2672 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2673 $text = $frame->expand( $dom, $flags );
2675 wfProfileOut( $fname );
2679 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2680 static function createAssocArgs( $args ) {
2681 $assocArgs = array();
2683 foreach( $args as $arg ) {
2684 $eqpos = strpos( $arg, '=' );
2685 if ( $eqpos === false ) {
2686 $assocArgs[$index++
] = $arg;
2688 $name = trim( substr( $arg, 0, $eqpos ) );
2689 $value = trim( substr( $arg, $eqpos+
1 ) );
2690 if ( $value === false ) {
2693 if ( $name !== false ) {
2694 $assocArgs[$name] = $value;
2703 * Return the text of a template, after recursively
2704 * replacing any variables or templates within the template.
2706 * @param array $piece The parts of the template
2707 * $piece['title']: the title, i.e. the part before the |
2708 * $piece['parts']: the parameter array
2709 * $piece['lineStart']: whether the brace was at the start of a line
2710 * @param PPFrame The current frame, contains template arguments
2711 * @return string the text of the template
2714 function braceSubstitution( $piece, $frame ) {
2715 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2716 $fname = __METHOD__
;
2717 wfProfileIn( $fname );
2718 wfProfileIn( __METHOD__
.'-setup' );
2721 $found = false; # $text has been filled
2722 $nowiki = false; # wiki markup in $text should be escaped
2723 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2724 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2725 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2726 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2728 # Title object, where $text came from
2731 # $part1 is the bit before the first |, and must contain only title characters.
2732 # Various prefixes will be stripped from it later.
2733 $titleWithSpaces = $frame->expand( $piece['title'] );
2734 $part1 = trim( $titleWithSpaces );
2737 # Original title text preserved for various purposes
2738 $originalTitle = $part1;
2740 # $args is a list of argument nodes, starting from index 0, not including $part1
2741 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2742 wfProfileOut( __METHOD__
.'-setup' );
2745 wfProfileIn( __METHOD__
.'-modifiers' );
2747 $mwSubst = MagicWord
::get( 'subst' );
2748 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2749 # One of two possibilities is true:
2750 # 1) Found SUBST but not in the PST phase
2751 # 2) Didn't find SUBST and in the PST phase
2752 # In either case, return without further processing
2753 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2760 if ( !$found && $args->getLength() == 0 ) {
2761 $id = $this->mVariables
->matchStartToEnd( $part1 );
2762 if ( $id !== false ) {
2763 $text = $this->getVariableValue( $id );
2764 if (MagicWord
::getCacheTTL($id)>-1)
2765 $this->mOutput
->mContainsOldMagic
= true;
2770 # MSG, MSGNW and RAW
2773 $mwMsgnw = MagicWord
::get( 'msgnw' );
2774 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2777 # Remove obsolete MSG:
2778 $mwMsg = MagicWord
::get( 'msg' );
2779 $mwMsg->matchStartAndRemove( $part1 );
2783 $mwRaw = MagicWord
::get( 'raw' );
2784 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2785 $forceRawInterwiki = true;
2788 wfProfileOut( __METHOD__
.'-modifiers' );
2792 wfProfileIn( __METHOD__
. '-pfunc' );
2794 $colonPos = strpos( $part1, ':' );
2795 if ( $colonPos !== false ) {
2796 # Case sensitive functions
2797 $function = substr( $part1, 0, $colonPos );
2798 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2799 $function = $this->mFunctionSynonyms
[1][$function];
2801 # Case insensitive functions
2802 $function = strtolower( $function );
2803 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2804 $function = $this->mFunctionSynonyms
[0][$function];
2810 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2811 $initialArgs = array( &$this );
2812 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2813 if ( $flags & SFH_OBJECT_ARGS
) {
2814 # Add a frame parameter, and pass the arguments as an array
2815 $allArgs = $initialArgs;
2816 $allArgs[] = $frame;
2817 for ( $i = 0; $i < $args->getLength(); $i++
) {
2818 $funcArgs[] = $args->item( $i );
2820 $allArgs[] = $funcArgs;
2822 # Convert arguments to plain text
2823 for ( $i = 0; $i < $args->getLength(); $i++
) {
2824 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2826 $allArgs = array_merge( $initialArgs, $funcArgs );
2829 # Workaround for PHP bug 35229 and similar
2830 if ( !is_callable( $callback ) ) {
2831 throw new MWException( "Tag hook for $name is not callable\n" );
2833 $result = call_user_func_array( $callback, $allArgs );
2836 if ( is_array( $result ) ) {
2837 if ( isset( $result[0] ) ) {
2839 unset( $result[0] );
2842 // Extract flags into the local scope
2843 // This allows callers to set flags such as nowiki, found, etc.
2850 wfProfileOut( __METHOD__
. '-pfunc' );
2853 # Finish mangling title and then check for loops.
2854 # Set $title to a Title object and $titleText to the PDBK
2857 # Split the title into page and subpage
2859 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2860 if ($subpage !== '') {
2861 $ns = $this->mTitle
->getNamespace();
2863 $title = Title
::newFromText( $part1, $ns );
2865 $titleText = $title->getPrefixedText();
2866 # Check for language variants if the template is not found
2867 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2868 $wgContLang->findVariantLink($part1, $title);
2870 # Do infinite loop check
2871 if ( !$frame->loopCheck( $title ) ) {
2873 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2874 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2876 # Do recursion depth check
2877 $limit = $this->mOptions
->getMaxTemplateDepth();
2878 if ( $frame->depth
>= $limit ) {
2880 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2885 # Load from database
2886 if ( !$found && $title ) {
2887 wfProfileIn( __METHOD__
. '-loadtpl' );
2888 if ( !$title->isExternal() ) {
2889 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2890 $text = SpecialPage
::capturePath( $title );
2891 if ( is_string( $text ) ) {
2894 $this->disableCache();
2896 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2897 $found = false; //access denied
2898 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2900 list( $text, $title ) = $this->getTemplateDom( $title );
2901 if ( $text !== false ) {
2907 # If the title is valid but undisplayable, make a link to it
2908 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2909 $text = "[[:$titleText]]";
2912 } elseif ( $title->isTrans() ) {
2913 // Interwiki transclusion
2914 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2915 $text = $this->interwikiTransclude( $title, 'render' );
2918 $text = $this->interwikiTransclude( $title, 'raw' );
2919 // Preprocess it like a template
2920 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2925 wfProfileOut( __METHOD__
. '-loadtpl' );
2928 # If we haven't found text to substitute by now, we're done
2929 # Recover the source wikitext and return it
2931 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2932 wfProfileOut( $fname );
2933 return array( 'object' => $text );
2936 # Expand DOM-style return values in a child frame
2937 if ( $isChildObj ) {
2938 # Clean up argument array
2939 $newFrame = $frame->newChild( $args, $title );
2942 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2943 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2944 # Expansion is eligible for the empty-frame cache
2945 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2946 $text = $this->mTplExpandCache
[$titleText];
2948 $text = $newFrame->expand( $text );
2949 $this->mTplExpandCache
[$titleText] = $text;
2952 # Uncached expansion
2953 $text = $newFrame->expand( $text );
2956 if ( $isLocalObj && $nowiki ) {
2957 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2958 $isLocalObj = false;
2961 # Replace raw HTML by a placeholder
2962 # Add a blank line preceding, to prevent it from mucking up
2963 # immediately preceding headings
2965 $text = "\n\n" . $this->insertStripItem( $text );
2967 # Escape nowiki-style return values
2968 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2969 $text = wfEscapeWikiText( $text );
2971 # Bug 529: if the template begins with a table or block-level
2972 # element, it should be treated as beginning a new line.
2973 # This behaviour is somewhat controversial.
2974 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2975 $text = "\n" . $text;
2978 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2979 # Error, oversize inclusion
2980 $text = "[[$originalTitle]]" .
2981 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2984 if ( $isLocalObj ) {
2985 $ret = array( 'object' => $text );
2987 $ret = array( 'text' => $text );
2990 wfProfileOut( $fname );
2995 * Get the semi-parsed DOM representation of a template with a given title,
2996 * and its redirect destination title. Cached.
2998 function getTemplateDom( $title ) {
2999 $cacheTitle = $title;
3000 $titleText = $title->getPrefixedDBkey();
3002 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3003 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3004 $title = Title
::makeTitle( $ns, $dbk );
3005 $titleText = $title->getPrefixedDBkey();
3007 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3008 return array( $this->mTplDomCache
[$titleText], $title );
3011 // Cache miss, go to the database
3012 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3014 if ( $text === false ) {
3015 $this->mTplDomCache
[$titleText] = false;
3016 return array( false, $title );
3019 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3020 $this->mTplDomCache
[ $titleText ] = $dom;
3022 if (! $title->equals($cacheTitle)) {
3023 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3024 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3027 return array( $dom, $title );
3031 * Fetch the unparsed text of a template and register a reference to it.
3033 function fetchTemplateAndTitle( $title ) {
3034 $templateCb = $this->mOptions
->getTemplateCallback();
3035 $stuff = call_user_func( $templateCb, $title );
3036 $text = $stuff['text'];
3037 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3038 if ( isset( $stuff['deps'] ) ) {
3039 foreach ( $stuff['deps'] as $dep ) {
3040 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3043 return array($text,$finalTitle);
3046 function fetchTemplate( $title ) {
3047 $rv = $this->fetchTemplateAndTitle($title);
3052 * Static function to get a template
3053 * Can be overridden via ParserOptions::setTemplateCallback().
3055 static function statelessFetchTemplate( $title ) {
3056 $text = $skip = false;
3057 $finalTitle = $title;
3060 // Loop to fetch the article, with up to 1 redirect
3061 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3062 # Give extensions a chance to select the revision instead
3063 $id = false; // Assume current
3064 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3070 'page_id' => $title->getArticleID(),
3074 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3075 $rev_id = $rev ?
$rev->getId() : 0;
3079 'page_id' => $title->getArticleID(),
3080 'rev_id' => $rev_id );
3083 $text = $rev->getText();
3084 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3086 $message = $wgLang->lcfirst( $title->getText() );
3087 $text = wfMsgForContentNoTrans( $message );
3088 if( wfEmptyMsg( $message, $text ) ) {
3095 if ( $text === false ) {
3099 $finalTitle = $title;
3100 $title = Title
::newFromRedirect( $text );
3104 'finalTitle' => $finalTitle,
3109 * Transclude an interwiki link.
3111 function interwikiTransclude( $title, $action ) {
3112 global $wgEnableScaryTranscluding;
3114 if (!$wgEnableScaryTranscluding)
3115 return wfMsg('scarytranscludedisabled');
3117 $url = $title->getFullUrl( "action=$action" );
3119 if (strlen($url) > 255)
3120 return wfMsg('scarytranscludetoolong');
3121 return $this->fetchScaryTemplateMaybeFromCache($url);
3124 function fetchScaryTemplateMaybeFromCache($url) {
3125 global $wgTranscludeCacheExpiry;
3126 $dbr = wfGetDB(DB_SLAVE
);
3127 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3128 array('tc_url' => $url));
3130 $time = $obj->tc_time
;
3131 $text = $obj->tc_contents
;
3132 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3137 $text = Http
::get($url);
3139 return wfMsg('scarytranscludefailed', $url);
3141 $dbw = wfGetDB(DB_MASTER
);
3142 $dbw->replace('transcache', array('tc_url'), array(
3144 'tc_time' => time(),
3145 'tc_contents' => $text));
3151 * Triple brace replacement -- used for template arguments
3154 function argSubstitution( $piece, $frame ) {
3155 wfProfileIn( __METHOD__
);
3158 $parts = $piece['parts'];
3159 $nameWithSpaces = $frame->expand( $piece['title'] );
3160 $argName = trim( $nameWithSpaces );
3162 $text = $frame->getArgument( $argName );
3163 if ( $text === false && $parts->getLength() > 0
3167 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3170 # No match in frame, use the supplied default
3171 $object = $parts->item( 0 )->getChildren();
3173 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3174 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3177 if ( $text === false && $object === false ) {
3179 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3181 if ( $error !== false ) {
3184 if ( $object !== false ) {
3185 $ret = array( 'object' => $object );
3187 $ret = array( 'text' => $text );
3190 wfProfileOut( __METHOD__
);
3195 * Return the text to be used for a given extension tag.
3196 * This is the ghost of strip().
3198 * @param array $params Associative array of parameters:
3199 * name PPNode for the tag name
3200 * attr PPNode for unparsed text where tag attributes are thought to be
3201 * attributes Optional associative array of parsed attributes
3202 * inner Contents of extension element
3203 * noClose Original text did not have a close tag
3204 * @param PPFrame $frame
3206 function extensionSubstitution( $params, $frame ) {
3207 global $wgRawHtml, $wgContLang;
3209 $name = $frame->expand( $params['name'] );
3210 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3211 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3213 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3215 if ( $this->ot
['html'] ) {
3216 $name = strtolower( $name );
3218 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3219 if ( isset( $params['attributes'] ) ) {
3220 $attributes = $attributes +
$params['attributes'];
3228 throw new MWException( '<html> extension tag encountered unexpectedly' );
3231 $output = Xml
::escapeTagsOnly( $content );
3234 $output = $wgContLang->armourMath(
3235 MathRenderer
::renderMath( $content, $attributes ) );
3238 $output = $this->renderImageGallery( $content, $attributes );
3241 if( isset( $this->mTagHooks
[$name] ) ) {
3242 # Workaround for PHP bug 35229 and similar
3243 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3244 throw new MWException( "Tag hook for $name is not callable\n" );
3246 $output = call_user_func_array( $this->mTagHooks
[$name],
3247 array( $content, $attributes, $this ) );
3249 throw new MWException( "Invalid call hook $name" );
3253 if ( is_null( $attrText ) ) {
3256 if ( isset( $params['attributes'] ) ) {
3257 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3258 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3259 htmlspecialchars( $attrValue ) . '"';
3262 if ( $content === null ) {
3263 $output = "<$name$attrText/>";
3265 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3266 $output = "<$name$attrText>$content$close";
3270 if ( $name == 'html' ||
$name == 'nowiki' ) {
3271 $this->mStripState
->nowiki
->setPair( $marker, $output );
3273 $this->mStripState
->general
->setPair( $marker, $output );
3279 * Increment an include size counter
3281 * @param string $type The type of expansion
3282 * @param integer $size The size of the text
3283 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3285 function incrementIncludeSize( $type, $size ) {
3286 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3289 $this->mIncludeSizes
[$type] +
= $size;
3295 * Increment the expensive function count
3297 * @return boolean False if the limit has been exceeded
3299 function incrementExpensiveFunctionCount() {
3300 global $wgExpensiveParserFunctionLimit;
3301 $this->mExpensiveFunctionCount++
;
3302 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3309 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3310 * Fills $this->mDoubleUnderscores, returns the modified text
3312 function doDoubleUnderscore( $text ) {
3313 // The position of __TOC__ needs to be recorded
3314 $mw = MagicWord
::get( 'toc' );
3315 if( $mw->match( $text ) ) {
3316 $this->mShowToc
= true;
3317 $this->mForceTocPosition
= true;
3319 // Set a placeholder. At the end we'll fill it in with the TOC.
3320 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3322 // Only keep the first one.
3323 $text = $mw->replace( '', $text );
3326 // Now match and remove the rest of them
3327 $mwa = MagicWord
::getDoubleUnderscoreArray();
3328 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3330 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3331 $this->mOutput
->mNoGallery
= true;
3333 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3334 $this->mShowToc
= false;
3336 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3337 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3339 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3340 if ( $containerCategory ) {
3341 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3343 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3350 * This function accomplishes several tasks:
3351 * 1) Auto-number headings if that option is enabled
3352 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3353 * 3) Add a Table of contents on the top for users who have enabled the option
3354 * 4) Auto-anchor headings
3356 * It loops through all headlines, collects the necessary data, then splits up the
3357 * string and re-inserts the newly formatted headlines.
3359 * @param string $text
3360 * @param boolean $isMain
3363 function formatHeadings( $text, $isMain=true ) {
3364 global $wgMaxTocLevel, $wgContLang;
3366 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3367 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3370 $showEditLink = $this->mOptions
->getEditSection();
3373 # Inhibit editsection links if requested in the page
3374 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3378 # Get all headlines for numbering them and adding funky stuff like [edit]
3379 # links - this is for later, but we need the number of headlines right now
3381 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3383 # if there are fewer than 4 headlines in the article, do not show TOC
3384 # unless it's been explicitly enabled.
3385 $enoughToc = $this->mShowToc
&&
3386 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3388 # Allow user to stipulate that a page should have a "new section"
3389 # link added via __NEWSECTIONLINK__
3390 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3391 $this->mOutput
->setNewSection( true );
3394 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3395 # override above conditions and always show TOC above first header
3396 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3397 $this->mShowToc
= true;
3401 # We need this to perform operations on the HTML
3402 $sk = $this->mOptions
->getSkin();
3408 # Ugh .. the TOC should have neat indentation levels which can be
3409 # passed to the skin functions. These are determined here
3413 $sublevelCount = array();
3414 $levelCount = array();
3420 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3421 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3424 foreach( $matches[3] as $headline ) {
3425 $isTemplate = false;
3427 $sectionIndex = false;
3429 $markerMatches = array();
3430 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3431 $serial = $markerMatches[1];
3432 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3433 $isTemplate = ($titleText != $baseTitleText);
3434 $headline = preg_replace("/^$markerRegex/", "", $headline);
3438 $prevlevel = $level;
3439 $prevtoclevel = $toclevel;
3441 $level = $matches[1][$headlineCount];
3443 if( $doNumberHeadings ||
$enoughToc ) {
3445 if ( $level > $prevlevel ) {
3446 # Increase TOC level
3448 $sublevelCount[$toclevel] = 0;
3449 if( $toclevel<$wgMaxTocLevel ) {
3450 $prevtoclevel = $toclevel;
3451 $toc .= $sk->tocIndent();
3455 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3456 # Decrease TOC level, find level to jump to
3458 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3459 # Can only go down to level 1
3462 for ($i = $toclevel; $i > 0; $i--) {
3463 if ( $levelCount[$i] == $level ) {
3464 # Found last matching level
3468 elseif ( $levelCount[$i] < $level ) {
3469 # Found first matching level below current level
3475 if( $toclevel<$wgMaxTocLevel ) {
3476 if($prevtoclevel < $wgMaxTocLevel) {
3477 # Unindent only if the previous toc level was shown :p
3478 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3479 $prevtoclevel = $toclevel;
3481 $toc .= $sk->tocLineEnd();
3486 # No change in level, end TOC line
3487 if( $toclevel<$wgMaxTocLevel ) {
3488 $toc .= $sk->tocLineEnd();
3492 $levelCount[$toclevel] = $level;
3494 # count number of headlines for each level
3495 @$sublevelCount[$toclevel]++
;
3497 for( $i = 1; $i <= $toclevel; $i++
) {
3498 if( !empty( $sublevelCount[$i] ) ) {
3502 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3508 # The safe header is a version of the header text safe to use for links
3509 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3510 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3512 # Remove link placeholders by the link text.
3513 # <!--LINK number-->
3515 # link text with suffix
3516 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3517 "\$this->mLinkHolders['texts'][\$1]",
3519 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3520 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3523 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3524 $tocline = preg_replace(
3525 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3529 $tocline = trim( $tocline );
3531 # For the anchor, strip out HTML-y stuff period
3532 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3533 $safeHeadline = trim( $safeHeadline );
3535 # Save headline for section edit hint before it's escaped
3536 $headlineHint = $safeHeadline;
3537 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3538 # HTML names must be case-insensitively unique (bug 10721)
3539 $arrayKey = strtolower( $safeHeadline );
3541 # XXX : Is $refers[$headlineCount] ever accessed, actually ?
3542 $refers[$headlineCount] = $safeHeadline;
3544 # count how many in assoc. array so we can track dupes in anchors
3545 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3546 $refcount[$headlineCount] = $refers[$arrayKey];
3548 # Don't number the heading if it is the only one (looks silly)
3549 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3550 # the two are different if the line contains a link
3551 $headline=$numbering . ' ' . $headline;
3554 # Create the anchor for linking from the TOC to the section
3555 $anchor = $safeHeadline;
3556 if($refcount[$headlineCount] > 1 ) {
3557 $anchor .= '_' . $refcount[$headlineCount];
3559 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3560 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3561 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3563 # give headline the correct <h#> tag
3564 if( $showEditLink && $sectionIndex !== false ) {
3566 # Put a T flag in the section identifier, to indicate to extractSections()
3567 # that sections inside <includeonly> should be counted.
3568 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3570 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3575 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3580 $this->mOutput
->setSections( $tocraw );
3582 # Never ever show TOC if no headers
3583 if( $numVisible < 1 ) {
3588 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3589 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3591 $toc = $sk->tocList( $toc );
3594 # split up and insert constructed headlines
3596 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3599 foreach( $blocks as $block ) {
3600 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3601 # This is the [edit] link that appears for the top block of text when
3602 # section editing is enabled
3604 # Disabled because it broke block formatting
3605 # For example, a bullet point in the top line
3606 # $full .= $sk->editSectionLink(0);
3609 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3610 # Top anchor now in skin
3614 if( !empty( $head[$i] ) ) {
3619 if( $this->mForceTocPosition
) {
3620 return str_replace( '<!--MWTOC-->', $toc, $full );
3627 * Transform wiki markup when saving a page by doing \r\n -> \n
3628 * conversion, substitting signatures, {{subst:}} templates, etc.
3630 * @param string $text the text to transform
3631 * @param Title &$title the Title object for the current article
3632 * @param User &$user the User object describing the current user
3633 * @param ParserOptions $options parsing options
3634 * @param bool $clearState whether to clear the parser state first
3635 * @return string the altered wiki markup
3638 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3639 $this->mOptions
= $options;
3640 $this->setTitle( $title );
3641 $this->setOutputType( self
::OT_WIKI
);
3643 if ( $clearState ) {
3644 $this->clearState();
3650 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3651 $text = $this->pstPass2( $text, $user );
3652 $text = $this->mStripState
->unstripBoth( $text );
3657 * Pre-save transform helper function
3660 function pstPass2( $text, $user ) {
3661 global $wgContLang, $wgLocaltimezone;
3663 /* Note: This is the timestamp saved as hardcoded wikitext to
3664 * the database, we use $wgContLang here in order to give
3665 * everyone the same signature and use the default one rather
3666 * than the one selected in each user's preferences.
3668 * (see also bug 12815)
3670 $ts = $this->mOptions
->getTimestamp();
3672 if ( isset( $wgLocaltimezone ) ) {
3673 $unixts = wfTimestamp( TS_UNIX
, $ts );
3674 $oldtz = getenv( 'TZ' );
3675 putenv( 'TZ='.$wgLocaltimezone );
3676 $ts = date( 'YmdHis', $unixts );
3677 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3678 putenv( 'TZ='.$oldtz );
3680 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3682 # Variable replacement
3683 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3684 $text = $this->replaceVariables( $text );
3687 $sigText = $this->getUserSig( $user );
3688 $text = strtr( $text, array(
3690 '~~~~' => "$sigText $d",
3694 # Context links: [[|name]] and [[name (context)|]]
3696 global $wgLegalTitleChars;
3697 $tc = "[$wgLegalTitleChars]";
3698 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3700 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3701 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3702 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3704 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3705 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3706 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3708 $t = $this->mTitle
->getText();
3710 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3711 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3712 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3713 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3715 # if there's no context, don't bother duplicating the title
3716 $text = preg_replace( $p2, '[[\\1]]', $text );
3719 # Trim trailing whitespace
3720 $text = rtrim( $text );
3726 * Fetch the user's signature text, if any, and normalize to
3727 * validated, ready-to-insert wikitext.
3733 function getUserSig( &$user ) {
3734 global $wgMaxSigChars;
3736 $username = $user->getName();
3737 $nickname = $user->getOption( 'nickname' );
3738 $nickname = $nickname === '' ?
$username : $nickname;
3740 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3741 $nickname = $username;
3742 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3743 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3744 # Sig. might contain markup; validate this
3745 if( $this->validateSig( $nickname ) !== false ) {
3746 # Validated; clean up (if needed) and return it
3747 return $this->cleanSig( $nickname, true );
3749 # Failed to validate; fall back to the default
3750 $nickname = $username;
3751 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3755 // Make sure nickname doesnt get a sig in a sig
3756 $nickname = $this->cleanSigInSig( $nickname );
3758 # If we're still here, make it a link to the user page
3759 $userText = wfEscapeWikiText( $username );
3760 $nickText = wfEscapeWikiText( $nickname );
3761 if ( $user->isAnon() ) {
3762 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3764 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3769 * Check that the user's signature contains no bad XML
3771 * @param string $text
3772 * @return mixed An expanded string, or false if invalid.
3774 function validateSig( $text ) {
3775 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3779 * Clean up signature text
3781 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3782 * 2) Substitute all transclusions
3784 * @param string $text
3785 * @param $parsing Whether we're cleaning (preferences save) or parsing
3786 * @return string Signature text
3788 function cleanSig( $text, $parsing = false ) {
3791 $this->clearState();
3792 $this->setTitle( $wgTitle );
3793 $this->mOptions
= new ParserOptions
;
3794 $this->setOutputType
= self
::OT_PREPROCESS
;
3797 # FIXME: regex doesn't respect extension tags or nowiki
3798 # => Move this logic to braceSubstitution()
3799 $substWord = MagicWord
::get( 'subst' );
3800 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3801 $substText = '{{' . $substWord->getSynonym( 0 );
3803 $text = preg_replace( $substRegex, $substText, $text );
3804 $text = $this->cleanSigInSig( $text );
3805 $dom = $this->preprocessToDom( $text );
3806 $frame = $this->getPreprocessor()->newFrame();
3807 $text = $frame->expand( $dom );
3810 $text = $this->mStripState
->unstripBoth( $text );
3817 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3818 * @param string $text
3819 * @return string Signature text with /~{3,5}/ removed
3821 function cleanSigInSig( $text ) {
3822 $text = preg_replace( '/~{3,5}/', '', $text );
3827 * Set up some variables which are usually set up in parse()
3828 * so that an external function can call some class members with confidence
3831 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3832 $this->setTitle( $title );
3833 $this->mOptions
= $options;
3834 $this->setOutputType( $outputType );
3835 if ( $clearState ) {
3836 $this->clearState();
3841 * Wrapper for preprocess()
3843 * @param string $text the text to preprocess
3844 * @param ParserOptions $options options
3848 function transformMsg( $text, $options ) {
3850 static $executing = false;
3852 $fname = "Parser::transformMsg";
3854 # Guard against infinite recursion
3860 wfProfileIn($fname);
3861 $text = $this->preprocess( $text, $wgTitle, $options );
3864 wfProfileOut($fname);
3869 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3870 * The callback should have the following form:
3871 * function myParserHook( $text, $params, &$parser ) { ... }
3873 * Transform and return $text. Use $parser for any required context, e.g. use
3874 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3878 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3879 * @param mixed $callback The callback function (and object) to use for the tag
3881 * @return The old value of the mTagHooks array associated with the hook
3883 function setHook( $tag, $callback ) {
3884 $tag = strtolower( $tag );
3885 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3886 $this->mTagHooks
[$tag] = $callback;
3887 if( !in_array( $tag, $this->mStripList
) ) {
3888 $this->mStripList
[] = $tag;
3894 function setTransparentTagHook( $tag, $callback ) {
3895 $tag = strtolower( $tag );
3896 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3897 $this->mTransparentTagHooks
[$tag] = $callback;
3903 * Remove all tag hooks
3905 function clearTagHooks() {
3906 $this->mTagHooks
= array();
3907 $this->mStripList
= $this->mDefaultStripList
;
3911 * Create a function, e.g. {{sum:1|2|3}}
3912 * The callback function should have the form:
3913 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3915 * The callback may either return the text result of the function, or an array with the text
3916 * in element 0, and a number of flags in the other elements. The names of the flags are
3917 * specified in the keys. Valid flags are:
3918 * found The text returned is valid, stop processing the template. This
3920 * nowiki Wiki markup in the return value should be escaped
3921 * isHTML The returned text is HTML, armour it against wikitext transformation
3925 * @param string $id The magic word ID
3926 * @param mixed $callback The callback function (and object) to use
3927 * @param integer $flags a combination of the following flags:
3928 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3930 * @return The old callback function for this name, if any
3932 function setFunctionHook( $id, $callback, $flags = 0 ) {
3933 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3934 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3936 # Add to function cache
3937 $mw = MagicWord
::get( $id );
3939 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3941 $synonyms = $mw->getSynonyms();
3942 $sensitive = intval( $mw->isCaseSensitive() );
3944 foreach ( $synonyms as $syn ) {
3946 if ( !$sensitive ) {
3947 $syn = strtolower( $syn );
3950 if ( !( $flags & SFH_NO_HASH
) ) {
3953 # Remove trailing colon
3954 if ( substr( $syn, -1, 1 ) == ':' ) {
3955 $syn = substr( $syn, 0, -1 );
3957 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3963 * Get all registered function hook identifiers
3967 function getFunctionHooks() {
3968 return array_keys( $this->mFunctionHooks
);
3972 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3973 * Placeholders created in Skin::makeLinkObj()
3974 * Returns an array of link CSS classes, indexed by PDBK.
3975 * $options is a bit field, RLH_FOR_UPDATE to select for update
3977 function replaceLinkHolders( &$text, $options = 0 ) {
3981 $fname = 'Parser::replaceLinkHolders';
3982 wfProfileIn( $fname );
3986 $linkcolour_ids = array();
3987 $sk = $this->mOptions
->getSkin();
3988 $linkCache = LinkCache
::singleton();
3990 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3991 wfProfileIn( $fname.'-check' );
3992 $dbr = wfGetDB( DB_SLAVE
);
3993 $page = $dbr->tableName( 'page' );
3994 $threshold = $wgUser->getOption('stubthreshold');
3997 asort( $this->mLinkHolders
['namespaces'] );
4002 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4004 $title = $this->mLinkHolders
['titles'][$key];
4006 # Skip invalid entries.
4007 # Result will be ugly, but prevents crash.
4008 if ( is_null( $title ) ) {
4011 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4013 # Check if it's a static known link, e.g. interwiki
4014 if ( $title->isAlwaysKnown() ) {
4015 $colours[$pdbk] = '';
4016 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4017 $colours[$pdbk] = '';
4018 $this->mOutput
->addLink( $title, $id );
4019 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4020 $colours[$pdbk] = 'new';
4021 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4022 $colours[$pdbk] = 'new';
4024 # Not in the link cache, add it to the query
4025 if ( !isset( $current ) ) {
4027 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4028 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4029 } elseif ( $current != $ns ) {
4031 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4036 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4041 if ( $options & RLH_FOR_UPDATE
) {
4042 $query .= ' FOR UPDATE';
4045 $res = $dbr->query( $query, $fname );
4047 # Fetch data and form into an associative array
4048 # non-existent = broken
4049 while ( $s = $dbr->fetchObject($res) ) {
4050 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4051 $pdbk = $title->getPrefixedDBkey();
4052 $linkCache->addGoodLinkObj( $s->page_id
, $title, $s->page_len
, $s->page_is_redirect
);
4053 $this->mOutput
->addLink( $title, $s->page_id
);
4054 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
4055 //add id to the extension todolist
4056 $linkcolour_ids[$s->page_id
] = $pdbk;
4058 //pass an array of page_ids to an extension
4059 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4061 wfProfileOut( $fname.'-check' );
4063 # Do a second query for different language variants of links and categories
4064 if($wgContLang->hasVariants()){
4065 $linkBatch = new LinkBatch();
4066 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4067 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4068 $varCategories = array(); // category replacements oldDBkey => newDBkey
4070 $categories = $this->mOutput
->getCategoryLinks();
4072 // Add variants of links to link batch
4073 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4074 $title = $this->mLinkHolders
['titles'][$key];
4075 if ( is_null( $title ) )
4078 $pdbk = $title->getPrefixedDBkey();
4079 $titleText = $title->getText();
4081 // generate all variants of the link title text
4082 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4084 // if link was not found (in first query), add all variants to query
4085 if ( !isset($colours[$pdbk]) ){
4086 foreach($allTextVariants as $textVariant){
4087 if($textVariant != $titleText){
4088 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4089 if(is_null($variantTitle)) continue;
4090 $linkBatch->addObj( $variantTitle );
4091 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4097 // process categories, check if a category exists in some variant
4098 foreach( $categories as $category ){
4099 $variants = $wgContLang->convertLinkToAllVariants($category);
4100 foreach($variants as $variant){
4101 if($variant != $category){
4102 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4103 if(is_null($variantTitle)) continue;
4104 $linkBatch->addObj( $variantTitle );
4105 $categoryMap[$variant] = $category;
4111 if(!$linkBatch->isEmpty()){
4113 $titleClause = $linkBatch->constructSet('page', $dbr);
4115 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4117 $variantQuery .= " FROM $page WHERE $titleClause";
4118 if ( $options & RLH_FOR_UPDATE
) {
4119 $variantQuery .= ' FOR UPDATE';
4122 $varRes = $dbr->query( $variantQuery, $fname );
4124 // for each found variants, figure out link holders and replace
4125 while ( $s = $dbr->fetchObject($varRes) ) {
4127 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4128 $varPdbk = $variantTitle->getPrefixedDBkey();
4129 $vardbk = $variantTitle->getDBkey();
4131 $holderKeys = array();
4132 if(isset($variantMap[$varPdbk])){
4133 $holderKeys = $variantMap[$varPdbk];
4134 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle, $s->page_len
, $s->page_is_redirect
);
4135 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4138 // loop over link holders
4139 foreach($holderKeys as $key){
4140 $title = $this->mLinkHolders
['titles'][$key];
4141 if ( is_null( $title ) ) continue;
4143 $pdbk = $title->getPrefixedDBkey();
4145 if(!isset($colours[$pdbk])){
4146 // found link in some of the variants, replace the link holder data
4147 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4148 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4150 // set pdbk and colour
4151 $pdbks[$key] = $varPdbk;
4152 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
4153 $linkcolour_ids[$s->page_id
] = $pdbk;
4155 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4158 // check if the object is a variant of a category
4159 if(isset($categoryMap[$vardbk])){
4160 $oldkey = $categoryMap[$vardbk];
4161 if($oldkey != $vardbk)
4162 $varCategories[$oldkey]=$vardbk;
4166 // rebuild the categories in original order (if there are replacements)
4167 if(count($varCategories)>0){
4169 $originalCats = $this->mOutput
->getCategories();
4170 foreach($originalCats as $cat => $sortkey){
4171 // make the replacement
4172 if( array_key_exists($cat,$varCategories) )
4173 $newCats[$varCategories[$cat]] = $sortkey;
4174 else $newCats[$cat] = $sortkey;
4176 $this->mOutput
->setCategoryLinks($newCats);
4181 # Construct search and replace arrays
4182 wfProfileIn( $fname.'-construct' );
4183 $replacePairs = array();
4184 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4185 $pdbk = $pdbks[$key];
4186 $searchkey = "<!--LINK $key-->";
4187 $title = $this->mLinkHolders
['titles'][$key];
4188 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4189 $linkCache->addBadLinkObj( $title );
4190 $colours[$pdbk] = 'new';
4191 $this->mOutput
->addLink( $title, 0 );
4192 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4193 $this->mLinkHolders
['texts'][$key],
4194 $this->mLinkHolders
['queries'][$key] );
4196 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4197 $this->mLinkHolders
['texts'][$key],
4198 $this->mLinkHolders
['queries'][$key] );
4201 $replacer = new HashtableReplacer( $replacePairs, 1 );
4202 wfProfileOut( $fname.'-construct' );
4205 wfProfileIn( $fname.'-replace' );
4206 $text = preg_replace_callback(
4207 '/(<!--LINK .*?-->)/',
4211 wfProfileOut( $fname.'-replace' );
4214 # Now process interwiki link holders
4215 # This is quite a bit simpler than internal links
4216 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4217 wfProfileIn( $fname.'-interwiki' );
4218 # Make interwiki link HTML
4219 $replacePairs = array();
4220 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4221 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4222 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4224 $replacer = new HashtableReplacer( $replacePairs, 1 );
4226 $text = preg_replace_callback(
4227 '/<!--IWLINK (.*?)-->/',
4230 wfProfileOut( $fname.'-interwiki' );
4233 wfProfileOut( $fname );
4238 * Replace <!--LINK--> link placeholders with plain text of links
4239 * (not HTML-formatted).
4240 * @param string $text
4243 function replaceLinkHoldersText( $text ) {
4244 $fname = 'Parser::replaceLinkHoldersText';
4245 wfProfileIn( $fname );
4247 $text = preg_replace_callback(
4248 '/<!--(LINK|IWLINK) (.*?)-->/',
4249 array( &$this, 'replaceLinkHoldersTextCallback' ),
4252 wfProfileOut( $fname );
4257 * @param array $matches
4261 function replaceLinkHoldersTextCallback( $matches ) {
4262 $type = $matches[1];
4264 if( $type == 'LINK' ) {
4265 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4266 return $this->mLinkHolders
['texts'][$key];
4268 } elseif( $type == 'IWLINK' ) {
4269 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4270 return $this->mInterwikiLinkHolders
['texts'][$key];
4277 * Tag hook handler for 'pre'.
4279 function renderPreTag( $text, $attribs ) {
4280 // Backwards-compatibility hack
4281 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4283 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4284 return wfOpenElement( 'pre', $attribs ) .
4285 Xml
::escapeTagsOnly( $content ) .
4290 * Renders an image gallery from a text with one line per image.
4291 * text labels may be given by using |-style alternative text. E.g.
4292 * Image:one.jpg|The number "1"
4293 * Image:tree.jpg|A tree
4294 * given as text will return the HTML of a gallery with two images,
4295 * labeled 'The number "1"' and
4298 function renderImageGallery( $text, $params ) {
4299 $ig = new ImageGallery();
4300 $ig->setContextTitle( $this->mTitle
);
4301 $ig->setShowBytes( false );
4302 $ig->setShowFilename( false );
4303 $ig->setParser( $this );
4304 $ig->setHideBadImages();
4305 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4306 $ig->useSkin( $this->mOptions
->getSkin() );
4307 $ig->mRevisionId
= $this->mRevisionId
;
4309 if( isset( $params['caption'] ) ) {
4310 $caption = $params['caption'];
4311 $caption = htmlspecialchars( $caption );
4312 $caption = $this->replaceInternalLinks( $caption );
4313 $ig->setCaptionHtml( $caption );
4315 if( isset( $params['perrow'] ) ) {
4316 $ig->setPerRow( $params['perrow'] );
4318 if( isset( $params['widths'] ) ) {
4319 $ig->setWidths( $params['widths'] );
4321 if( isset( $params['heights'] ) ) {
4322 $ig->setHeights( $params['heights'] );
4325 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4327 $lines = explode( "\n", $text );
4328 foreach ( $lines as $line ) {
4329 # match lines like these:
4330 # Image:someimage.jpg|This is some image
4332 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4334 if ( count( $matches ) == 0 ) {
4337 $tp = Title
::newFromText( $matches[1] );
4339 if( is_null( $nt ) ) {
4340 # Bogus title. Ignore these so we don't bomb out later.
4343 if ( isset( $matches[3] ) ) {
4344 $label = $matches[3];
4349 $html = $this->recursiveTagParse( trim( $label ) );
4351 $ig->add( $nt, $html );
4353 # Only add real images (bug #5586)
4354 if ( $nt->getNamespace() == NS_IMAGE
) {
4355 $this->mOutput
->addImage( $nt->getDBkey() );
4358 return $ig->toHTML();
4361 function getImageParams( $handler ) {
4363 $handlerClass = get_class( $handler );
4367 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4368 // Initialise static lists
4369 static $internalParamNames = array(
4370 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4371 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4372 'bottom', 'text-bottom' ),
4373 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4374 'upright', 'border' ),
4376 static $internalParamMap;
4377 if ( !$internalParamMap ) {
4378 $internalParamMap = array();
4379 foreach ( $internalParamNames as $type => $names ) {
4380 foreach ( $names as $name ) {
4381 $magicName = str_replace( '-', '_', "img_$name" );
4382 $internalParamMap[$magicName] = array( $type, $name );
4387 // Add handler params
4388 $paramMap = $internalParamMap;
4390 $handlerParamMap = $handler->getParamMap();
4391 foreach ( $handlerParamMap as $magic => $paramName ) {
4392 $paramMap[$magic] = array( 'handler', $paramName );
4395 $this->mImageParams
[$handlerClass] = $paramMap;
4396 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4398 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4402 * Parse image options text and use it to make an image
4404 function makeImage( $title, $options ) {
4405 # Check if the options text is of the form "options|alt text"
4407 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4408 # * left no resizing, just left align. label is used for alt= only
4409 # * right same, but right aligned
4410 # * none same, but not aligned
4411 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4412 # * center center the image
4413 # * framed Keep original image size, no magnify-button.
4414 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4415 # * upright reduce width for upright images, rounded to full __0 px
4416 # * border draw a 1px border around the image
4417 # vertical-align values (no % or length right now):
4427 $parts = array_map( 'trim', explode( '|', $options) );
4428 $sk = $this->mOptions
->getSkin();
4430 # Give extensions a chance to select the file revision for us
4431 $skip = $time = false;
4432 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4435 return $sk->makeLinkObj( $title );
4439 $file = wfFindFile( $title, $time );
4440 $handler = $file ?
$file->getHandler() : false;
4442 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4444 # Process the input parameters
4446 $params = array( 'frame' => array(), 'handler' => array(),
4447 'horizAlign' => array(), 'vertAlign' => array() );
4448 foreach( $parts as $part ) {
4449 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4451 if( isset( $paramMap[$magicName] ) ) {
4452 list( $type, $paramName ) = $paramMap[$magicName];
4454 // Special case; width and height come in one variable together
4455 if( $type == 'handler' && $paramName == 'width' ) {
4457 # (bug 13500) In both cases (width/height and width only),
4458 # permit trailing "px" for backward compatibility.
4459 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4460 $width = intval( $m[1] );
4461 $height = intval( $m[2] );
4462 if ( $handler->validateParam( 'width', $width ) ) {
4463 $params[$type]['width'] = $width;
4466 if ( $handler->validateParam( 'height', $height ) ) {
4467 $params[$type]['height'] = $height;
4470 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4471 $width = intval( $value );
4472 if ( $handler->validateParam( 'width', $width ) ) {
4473 $params[$type]['width'] = $width;
4476 } // else no validation -- bug 13436
4478 if ( $type == 'handler' ) {
4479 # Validate handler parameter
4480 $validated = $handler->validateParam( $paramName, $value );
4482 # Validate internal parameters
4483 switch( $paramName ) {
4485 /// @fixme - possibly check validity here?
4486 /// downstream behavior seems odd with missing manual thumbs.
4490 // Most other things appear to be empty or numeric...
4491 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4496 $params[$type][$paramName] = $value;
4500 if ( !$validated ) {
4505 # Process alignment parameters
4506 if ( $params['horizAlign'] ) {
4507 $params['frame']['align'] = key( $params['horizAlign'] );
4509 if ( $params['vertAlign'] ) {
4510 $params['frame']['valign'] = key( $params['vertAlign'] );
4513 # Strip bad stuff out of the alt text
4514 $alt = $this->replaceLinkHoldersText( $caption );
4516 # make sure there are no placeholders in thumbnail attributes
4517 # that are later expanded to html- so expand them now and
4519 $alt = $this->mStripState
->unstripBoth( $alt );
4520 $alt = Sanitizer
::stripAllTags( $alt );
4522 $params['frame']['alt'] = $alt;
4523 $params['frame']['caption'] = $caption;
4525 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4527 # Linker does the rest
4528 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time );
4530 # Give the handler a chance to modify the parser object
4532 $handler->parserTransformHook( $this, $file );
4539 * Set a flag in the output object indicating that the content is dynamic and
4540 * shouldn't be cached.
4542 function disableCache() {
4543 wfDebug( "Parser output marked as uncacheable.\n" );
4544 $this->mOutput
->mCacheTime
= -1;
4548 * Callback from the Sanitizer for expanding items found in HTML attribute
4549 * values, so they can be safely tested and escaped.
4550 * @param string $text
4551 * @param PPFrame $frame
4555 function attributeStripCallback( &$text, $frame = false ) {
4556 $text = $this->replaceVariables( $text, $frame );
4557 $text = $this->mStripState
->unstripBoth( $text );
4566 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4567 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4568 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4574 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4579 * Break wikitext input into sections, and either pull or replace
4580 * some particular section's text.
4582 * External callers should use the getSection and replaceSection methods.
4584 * @param string $text Page wikitext
4585 * @param string $section A section identifier string of the form:
4586 * <flag1> - <flag2> - ... - <section number>
4588 * Currently the only recognised flag is "T", which means the target section number
4589 * was derived during a template inclusion parse, in other words this is a template
4590 * section edit link. If no flags are given, it was an ordinary section edit link.
4591 * This flag is required to avoid a section numbering mismatch when a section is
4592 * enclosed by <includeonly> (bug 6563).
4594 * The section number 0 pulls the text before the first heading; other numbers will
4595 * pull the given section along with its lower-level subsections. If the section is
4596 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4598 * @param string $mode One of "get" or "replace"
4599 * @param string $newText Replacement text for section data.
4600 * @return string for "get", the extracted section text.
4601 * for "replace", the whole page with the section replaced.
4603 private function extractSections( $text, $section, $mode, $newText='' ) {
4605 $this->clearState();
4606 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4607 $this->mOptions
= new ParserOptions
;
4608 $this->setOutputType( self
::OT_WIKI
);
4610 $frame = $this->getPreprocessor()->newFrame();
4612 // Process section extraction flags
4614 $sectionParts = explode( '-', $section );
4615 $sectionIndex = array_pop( $sectionParts );
4616 foreach ( $sectionParts as $part ) {
4617 if ( $part == 'T' ) {
4618 $flags |
= self
::PTD_FOR_INCLUSION
;
4621 // Preprocess the text
4622 $root = $this->preprocessToDom( $text, $flags );
4624 // <h> nodes indicate section breaks
4625 // They can only occur at the top level, so we can find them by iterating the root's children
4626 $node = $root->getFirstChild();
4628 // Find the target section
4629 if ( $sectionIndex == 0 ) {
4630 // Section zero doesn't nest, level=big
4631 $targetLevel = 1000;
4634 if ( $node->getName() == 'h' ) {
4635 $bits = $node->splitHeading();
4636 if ( $bits['i'] == $sectionIndex ) {
4637 $targetLevel = $bits['level'];
4641 if ( $mode == 'replace' ) {
4642 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4644 $node = $node->getNextSibling();
4650 if ( $mode == 'get' ) {
4657 // Find the end of the section, including nested sections
4659 if ( $node->getName() == 'h' ) {
4660 $bits = $node->splitHeading();
4661 $curLevel = $bits['level'];
4662 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4666 if ( $mode == 'get' ) {
4667 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4669 $node = $node->getNextSibling();
4672 // Write out the remainder (in replace mode only)
4673 if ( $mode == 'replace' ) {
4674 // Output the replacement text
4675 // Add two newlines on -- trailing whitespace in $newText is conventionally
4676 // stripped by the editor, so we need both newlines to restore the paragraph gap
4677 $outText .= $newText . "\n\n";
4679 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4680 $node = $node->getNextSibling();
4684 if ( is_string( $outText ) ) {
4685 // Re-insert stripped tags
4686 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4693 * This function returns the text of a section, specified by a number ($section).
4694 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4695 * the first section before any such heading (section 0).
4697 * If a section contains subsections, these are also returned.
4699 * @param string $text text to look in
4700 * @param string $section section identifier
4701 * @param string $deftext default to return if section is not found
4702 * @return string text of the requested section
4704 public function getSection( $text, $section, $deftext='' ) {
4705 return $this->extractSections( $text, $section, "get", $deftext );
4708 public function replaceSection( $oldtext, $section, $text ) {
4709 return $this->extractSections( $oldtext, $section, "replace", $text );
4713 * Get the timestamp associated with the current revision, adjusted for
4714 * the default server-local timestamp
4716 function getRevisionTimestamp() {
4717 if ( is_null( $this->mRevisionTimestamp
) ) {
4718 wfProfileIn( __METHOD__
);
4720 $dbr = wfGetDB( DB_SLAVE
);
4721 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4722 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4724 // Normalize timestamp to internal MW format for timezone processing.
4725 // This has the added side-effect of replacing a null value with
4726 // the current time, which gives us more sensible behavior for
4728 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4730 // The cryptic '' timezone parameter tells to use the site-default
4731 // timezone offset instead of the user settings.
4733 // Since this value will be saved into the parser cache, served
4734 // to other users, and potentially even used inside links and such,
4735 // it needs to be consistent for all visitors.
4736 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4738 wfProfileOut( __METHOD__
);
4740 return $this->mRevisionTimestamp
;
4744 * Mutator for $mDefaultSort
4746 * @param $sort New value
4748 public function setDefaultSort( $sort ) {
4749 $this->mDefaultSort
= $sort;
4753 * Accessor for $mDefaultSort
4754 * Will use the title/prefixed title if none is set
4758 public function getDefaultSort() {
4759 if( $this->mDefaultSort
!== false ) {
4760 return $this->mDefaultSort
;
4762 return $this->mTitle
->getNamespace() == NS_CATEGORY
4763 ?
$this->mTitle
->getText()
4764 : $this->mTitle
->getPrefixedText();
4769 * Try to guess the section anchor name based on a wikitext fragment
4770 * presumably extracted from a heading, for example "Header" from
4773 public function guessSectionNameFromWikiText( $text ) {
4774 # Strip out wikitext links(they break the anchor)
4775 $text = $this->stripSectionName( $text );
4776 $headline = Sanitizer
::decodeCharReferences( $text );
4778 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4779 $headline = trim( $headline );
4780 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4781 $replacearray = array(
4786 array_keys( $replacearray ),
4787 array_values( $replacearray ),
4792 * Strips a text string of wikitext for use in a section anchor
4794 * Accepts a text string and then removes all wikitext from the
4795 * string and leaves only the resultant text (i.e. the result of
4796 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4797 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4798 * to create valid section anchors by mimicing the output of the
4799 * parser when headings are parsed.
4801 * @param $text string Text string to be stripped of wikitext
4802 * for use in a Section anchor
4803 * @return Filtered text string
4805 public function stripSectionName( $text ) {
4806 # Strip internal link markup
4807 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4808 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4810 # Strip external link markup (FIXME: Not Tolerant to blank link text
4811 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4812 # on how many empty links there are on the page - need to figure that out.
4813 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4815 # Parse wikitext quotes (italics & bold)
4816 $text = $this->doQuotes($text);
4819 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4823 function srvus( $text ) {
4824 return $this->testSrvus( $text, $this->mOutputType
);
4828 * strip/replaceVariables/unstrip for preprocessor regression testing
4830 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4831 $this->clearState();
4832 if ( ! ( $title instanceof Title
) ) {
4833 $title = Title
::newFromText( $title );
4835 $this->mTitle
= $title;
4836 $this->mOptions
= $options;
4837 $this->setOutputType( $outputType );
4838 $text = $this->replaceVariables( $text );
4839 $text = $this->mStripState
->unstripBoth( $text );
4840 $text = Sanitizer
::removeHTMLtags( $text );
4844 function testPst( $text, $title, $options ) {
4846 if ( ! ( $title instanceof Title
) ) {
4847 $title = Title
::newFromText( $title );
4849 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4852 function testPreprocess( $text, $title, $options ) {
4853 if ( ! ( $title instanceof Title
) ) {
4854 $title = Title
::newFromText( $title );
4856 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4859 function markerSkipCallback( $s, $callback ) {
4862 while ( $i < strlen( $s ) ) {
4863 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4864 if ( $markerStart === false ) {
4865 $out .= call_user_func( $callback, substr( $s, $i ) );
4868 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4869 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4870 if ( $markerEnd === false ) {
4871 $out .= substr( $s, $markerStart );
4874 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4875 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4885 * @todo document, briefly.
4886 * @addtogroup Parser
4889 var $general, $nowiki;
4891 function __construct() {
4892 $this->general
= new ReplacementArray
;
4893 $this->nowiki
= new ReplacementArray
;
4896 function unstripGeneral( $text ) {
4897 wfProfileIn( __METHOD__
);
4900 $text = $this->general
->replace( $text );
4901 } while ( $text != $oldText );
4902 wfProfileOut( __METHOD__
);
4906 function unstripNoWiki( $text ) {
4907 wfProfileIn( __METHOD__
);
4910 $text = $this->nowiki
->replace( $text );
4911 } while ( $text != $oldText );
4912 wfProfileOut( __METHOD__
);
4916 function unstripBoth( $text ) {
4917 wfProfileIn( __METHOD__
);
4920 $text = $this->general
->replace( $text );
4921 $text = $this->nowiki
->replace( $text );
4922 } while ( $text != $oldText );
4923 wfProfileOut( __METHOD__
);
4929 * @todo document, briefly.
4930 * @addtogroup Parser
4932 class OnlyIncludeReplacer
{
4935 function replace( $matches ) {
4936 if ( substr( $matches[1], -1 ) == "\n" ) {
4937 $this->output
.= substr( $matches[1], 0, -1 );
4939 $this->output
.= $matches[1];