3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $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 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
400 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
402 # Information on include size limits, for the benefit of users who try to skirt them
403 if ( $this->mOptions
->getEnableLimitReport() ) {
404 global $wgExpensiveParserFunctionLimit;
405 $max = $this->mOptions
->getMaxIncludeSize();
406 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
408 "NewPP limit report\n" .
409 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
410 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
411 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
413 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
414 $text .= "\n<!-- \n$limitReport-->\n";
416 $this->mOutput
->setText( $text );
417 $this->mRevisionId
= $oldRevisionId;
418 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
419 wfProfileOut( $fname );
420 wfProfileOut( __METHOD__
);
422 return $this->mOutput
;
426 * Recursive parser entry point that can be called from an extension tag
429 function recursiveTagParse( $text ) {
430 wfProfileIn( __METHOD__
);
431 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
432 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->internalParse( $text );
434 wfProfileOut( __METHOD__
);
439 * Expand templates and variables in the text, producing valid, static wikitext.
440 * Also removes comments.
442 function preprocess( $text, $title, $options, $revid = null ) {
443 wfProfileIn( __METHOD__
);
445 $this->setOutputType( self
::OT_PREPROCESS
);
446 $this->mOptions
= $options;
447 $this->setTitle( $title );
448 if( $revid !== null ) {
449 $this->mRevisionId
= $revid;
451 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
452 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
453 $text = $this->replaceVariables( $text );
454 $text = $this->mStripState
->unstripBoth( $text );
455 wfProfileOut( __METHOD__
);
460 * Get a random string
465 function getRandomString() {
466 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
469 function &getTitle() { return $this->mTitle
; }
470 function getOptions() { return $this->mOptions
; }
472 function getFunctionLang() {
473 global $wgLang, $wgContLang;
475 $target = $this->mOptions
->getTargetLanguage();
476 if ( $target !== null ) {
479 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
484 * Get a preprocessor object
486 function getPreprocessor() {
487 if ( !isset( $this->mPreprocessor
) ) {
488 $class = $this->mPreprocessorClass
;
489 $this->mPreprocessor
= new $class( $this );
491 return $this->mPreprocessor
;
495 * Replaces all occurrences of HTML-style comments and the given tags
496 * in the text with a random marker and returns the next text. The output
497 * parameter $matches will be an associative array filled with data in
499 * 'UNIQ-xxxxx' => array(
502 * array( 'param' => 'x' ),
503 * '<element param="x">tag content</element>' ) )
505 * @param $elements list of element names. Comments are always extracted.
506 * @param $text Source text string.
507 * @param $uniq_prefix
512 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
517 $taglist = implode( '|', $elements );
518 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
520 while ( '' != $text ) {
521 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
523 if( count( $p ) < 5 ) {
526 if( count( $p ) > 5 ) {
540 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
541 $stripped .= $marker;
543 if ( $close === '/>' ) {
544 // Empty element tag, <tag />
549 if( $element == '!--' ) {
552 $end = "/(<\\/$element\\s*>)/i";
554 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
556 if( count( $q ) < 3 ) {
557 # No end tag -- let it run out to the end of the text.
566 $matches[$marker] = array( $element,
568 Sanitizer
::decodeTagAttributes( $attributes ),
569 "<$element$attributes$close$content$tail" );
575 * Get a list of strippable XML-like elements
577 function getStripList() {
579 $elements = $this->mStripList
;
581 $elements[] = 'html';
583 if( $this->mOptions
->getUseTeX() ) {
584 $elements[] = 'math';
590 * @deprecated use replaceVariables
592 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
597 * Restores pre, math, and other extensions removed by strip()
599 * always call unstripNoWiki() after this one
601 * @deprecated use $this->mStripState->unstrip()
603 function unstrip( $text, $state ) {
604 return $state->unstripGeneral( $text );
608 * Always call this after unstrip() to preserve the order
611 * @deprecated use $this->mStripState->unstrip()
613 function unstripNoWiki( $text, $state ) {
614 return $state->unstripNoWiki( $text );
618 * @deprecated use $this->mStripState->unstripBoth()
620 function unstripForHTML( $text ) {
621 return $this->mStripState
->unstripBoth( $text );
625 * Add an item to the strip state
626 * Returns the unique tag which must be inserted into the stripped text
627 * The tag will be replaced with the original text in unstrip()
631 function insertStripItem( $text ) {
632 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
633 $this->mMarkerIndex++
;
634 $this->mStripState
->general
->setPair( $rnd, $text );
639 * Interface with html tidy, used if $wgUseTidy = true.
640 * If tidy isn't able to correct the markup, the original will be
641 * returned in all its glory with a warning comment appended.
643 * Either the external tidy program or the in-process tidy extension
644 * will be used depending on availability. Override the default
645 * $wgTidyInternal setting to disable the internal if it's not working.
647 * @param string $text Hideous HTML input
648 * @return string Corrected HTML output
652 function tidy( $text ) {
653 global $wgTidyInternal;
654 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
655 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
656 '<head><title>test</title></head><body>'.$text.'</body></html>';
657 if( $wgTidyInternal ) {
658 $correctedtext = Parser
::internalTidy( $wrappedtext );
660 $correctedtext = Parser
::externalTidy( $wrappedtext );
662 if( is_null( $correctedtext ) ) {
663 wfDebug( "Tidy error detected!\n" );
664 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
666 return $correctedtext;
670 * Spawn an external HTML tidy process and get corrected markup back from it.
675 function externalTidy( $text ) {
676 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
677 $fname = 'Parser::externalTidy';
678 wfProfileIn( $fname );
683 $descriptorspec = array(
684 0 => array('pipe', 'r'),
685 1 => array('pipe', 'w'),
686 2 => array('file', wfGetNull(), 'a')
689 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
690 if (is_resource($process)) {
691 // Theoretically, this style of communication could cause a deadlock
692 // here. If the stdout buffer fills up, then writes to stdin could
693 // block. This doesn't appear to happen with tidy, because tidy only
694 // writes to stdout after it's finished reading from stdin. Search
695 // for tidyParseStdin and tidySaveStdout in console/tidy.c
696 fwrite($pipes[0], $text);
698 while (!feof($pipes[1])) {
699 $cleansource .= fgets($pipes[1], 1024);
702 proc_close($process);
705 wfProfileOut( $fname );
707 if( $cleansource == '' && $text != '') {
708 // Some kind of error happened, so we couldn't get the corrected text.
709 // Just give up; we'll use the source text and append a warning.
717 * Use the HTML tidy PECL extension to use the tidy library in-process,
718 * saving the overhead of spawning a new process.
720 * 'pear install tidy' should be able to compile the extension module.
725 function internalTidy( $text ) {
726 global $wgTidyConf, $IP, $wgDebugTidy;
727 $fname = 'Parser::internalTidy';
728 wfProfileIn( $fname );
731 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
732 $tidy->cleanRepair();
733 if( $tidy->getStatus() == 2 ) {
734 // 2 is magic number for fatal error
735 // http://www.php.net/manual/en/function.tidy-get-status.php
738 $cleansource = tidy_get_output( $tidy );
740 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
741 $cleansource .= "<!--\nTidy reports:\n" .
742 str_replace( '-->', '-->', $tidy->errorBuffer
) .
746 wfProfileOut( $fname );
751 * parse the wiki syntax used to render tables
755 function doTableStuff ( $text ) {
756 $fname = 'Parser::doTableStuff';
757 wfProfileIn( $fname );
759 $lines = explode ( "\n" , $text );
760 $td_history = array (); // Is currently a td tag open?
761 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
762 $tr_history = array (); // Is currently a tr tag open?
763 $tr_attributes = array (); // history of tr attributes
764 $has_opened_tr = array(); // Did this table open a <tr> element?
765 $indent_level = 0; // indent level of the table
766 foreach ( $lines as $key => $line )
768 $line = trim ( $line );
770 if( $line == '' ) { // empty line, go to next line
773 $first_character = $line{0};
776 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
777 // First check if we are starting a new table
778 $indent_level = strlen( $matches[1] );
780 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
781 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
783 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
784 array_push ( $td_history , false );
785 array_push ( $last_tag_history , '' );
786 array_push ( $tr_history , false );
787 array_push ( $tr_attributes , '' );
788 array_push ( $has_opened_tr , false );
789 } else if ( count ( $td_history ) == 0 ) {
790 // Don't do any of the following
792 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
793 // We are ending a table
794 $line = '</table>' . substr ( $line , 2 );
795 $last_tag = array_pop ( $last_tag_history );
797 if ( !array_pop ( $has_opened_tr ) ) {
798 $line = "<tr><td></td></tr>{$line}";
801 if ( array_pop ( $tr_history ) ) {
802 $line = "</tr>{$line}";
805 if ( array_pop ( $td_history ) ) {
806 $line = "</{$last_tag}>{$line}";
808 array_pop ( $tr_attributes );
809 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
810 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
811 // Now we have a table row
812 $line = preg_replace( '#^\|-+#', '', $line );
814 // Whats after the tag is now only attributes
815 $attributes = $this->mStripState
->unstripBoth( $line );
816 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
817 array_pop ( $tr_attributes );
818 array_push ( $tr_attributes , $attributes );
821 $last_tag = array_pop ( $last_tag_history );
822 array_pop ( $has_opened_tr );
823 array_push ( $has_opened_tr , true );
825 if ( array_pop ( $tr_history ) ) {
829 if ( array_pop ( $td_history ) ) {
830 $line = "</{$last_tag}>{$line}";
833 $lines[$key] = $line;
834 array_push ( $tr_history , false );
835 array_push ( $td_history , false );
836 array_push ( $last_tag_history , '' );
838 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
839 // This might be cell elements, td, th or captions
840 if ( substr ( $line , 0 , 2 ) == '|+' ) {
841 $first_character = '+';
842 $line = substr ( $line , 1 );
845 $line = substr ( $line , 1 );
847 if ( $first_character == '!' ) {
848 $line = str_replace ( '!!' , '||' , $line );
851 // Split up multiple cells on the same line.
852 // FIXME : This can result in improper nesting of tags processed
853 // by earlier parser steps, but should avoid splitting up eg
854 // attribute values containing literal "||".
855 $cells = StringUtils
::explodeMarkup( '||' , $line );
859 // Loop through each table cell
860 foreach ( $cells as $cell )
863 if ( $first_character != '+' )
865 $tr_after = array_pop ( $tr_attributes );
866 if ( !array_pop ( $tr_history ) ) {
867 $previous = "<tr{$tr_after}>\n";
869 array_push ( $tr_history , true );
870 array_push ( $tr_attributes , '' );
871 array_pop ( $has_opened_tr );
872 array_push ( $has_opened_tr , true );
875 $last_tag = array_pop ( $last_tag_history );
877 if ( array_pop ( $td_history ) ) {
878 $previous = "</{$last_tag}>{$previous}";
881 if ( $first_character == '|' ) {
883 } else if ( $first_character == '!' ) {
885 } else if ( $first_character == '+' ) {
886 $last_tag = 'caption';
891 array_push ( $last_tag_history , $last_tag );
893 // A cell could contain both parameters and data
894 $cell_data = explode ( '|' , $cell , 2 );
896 // Bug 553: Note that a '|' inside an invalid link should not
897 // be mistaken as delimiting cell parameters
898 if ( strpos( $cell_data[0], '[[' ) !== false ) {
899 $cell = "{$previous}<{$last_tag}>{$cell}";
900 } else if ( count ( $cell_data ) == 1 )
901 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
903 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
904 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
905 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
908 $lines[$key] .= $cell;
909 array_push ( $td_history , true );
914 // Closing open td, tr && table
915 while ( count ( $td_history ) > 0 )
917 if ( array_pop ( $td_history ) ) {
920 if ( array_pop ( $tr_history ) ) {
923 if ( !array_pop ( $has_opened_tr ) ) {
924 $lines[] = "<tr><td></td></tr>" ;
927 $lines[] = '</table>' ;
930 $output = implode ( "\n" , $lines ) ;
932 // special case: don't return empty table
933 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
937 wfProfileOut( $fname );
943 * Helper function for parse() that transforms wiki markup into
944 * HTML. Only called for $mOutputType == self::OT_HTML.
948 function internalParse( $text ) {
950 $fname = 'Parser::internalParse';
951 wfProfileIn( $fname );
953 # Hook to suspend the parser in this state
954 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
955 wfProfileOut( $fname );
959 $text = $this->replaceVariables( $text );
960 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
961 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
963 // Tables need to come after variable replacement for things to work
964 // properly; putting them before other transformations should keep
965 // exciting things like link expansions from showing up in surprising
967 $text = $this->doTableStuff( $text );
969 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
971 $text = $this->doDoubleUnderscore( $text );
972 $text = $this->doHeadings( $text );
973 if($this->mOptions
->getUseDynamicDates()) {
974 $df = DateFormatter
::getInstance();
975 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
977 $text = $this->doAllQuotes( $text );
978 $text = $this->replaceInternalLinks( $text );
979 $text = $this->replaceExternalLinks( $text );
981 # replaceInternalLinks may sometimes leave behind
982 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
983 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
985 $text = $this->doMagicLinks( $text );
986 $text = $this->formatHeadings( $text, $isMain );
988 wfProfileOut( $fname );
993 * Replace special strings like "ISBN xxx" and "RFC xxx" with
994 * magic external links.
998 function doMagicLinks( $text ) {
999 wfProfileIn( __METHOD__
);
1000 $text = preg_replace_callback(
1002 <a.*?</a> | # Skip link text
1003 <.*?> | # Skip stuff inside HTML elements
1004 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1005 ISBN\s+(\b # ISBN, capture number as m[2]
1006 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1007 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1008 [0-9Xx] # check digit
1010 )!x', array( &$this, 'magicLinkCallback' ), $text );
1011 wfProfileOut( __METHOD__
);
1015 function magicLinkCallback( $m ) {
1016 if ( substr( $m[0], 0, 1 ) == '<' ) {
1019 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1021 $num = strtr( $isbn, array(
1026 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1027 $text = '<a href="' .
1028 $titleObj->escapeLocalUrl() .
1029 "\" class=\"internal\">ISBN $isbn</a>";
1031 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1035 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1037 $urlmsg = 'pubmedurl';
1040 throw new MWException( __METHOD__
.': unrecognised match type "' .
1041 substr($m[0], 0, 20 ) . '"' );
1044 $url = wfMsg( $urlmsg, $id);
1045 $sk = $this->mOptions
->getSkin();
1046 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1047 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1053 * Parse headers and return html
1057 function doHeadings( $text ) {
1058 $fname = 'Parser::doHeadings';
1059 wfProfileIn( $fname );
1060 for ( $i = 6; $i >= 1; --$i ) {
1061 $h = str_repeat( '=', $i );
1062 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1063 "<h$i>\\1</h$i>", $text );
1065 wfProfileOut( $fname );
1070 * Replace single quotes with HTML markup
1072 * @return string the altered text
1074 function doAllQuotes( $text ) {
1075 $fname = 'Parser::doAllQuotes';
1076 wfProfileIn( $fname );
1078 $lines = explode( "\n", $text );
1079 foreach ( $lines as $line ) {
1080 $outtext .= $this->doQuotes ( $line ) . "\n";
1082 $outtext = substr($outtext, 0,-1);
1083 wfProfileOut( $fname );
1088 * Helper function for doAllQuotes()
1090 public function doQuotes( $text ) {
1091 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1092 if ( count( $arr ) == 1 )
1096 # First, do some preliminary work. This may shift some apostrophes from
1097 # being mark-up to being text. It also counts the number of occurrences
1098 # of bold and italics mark-ups.
1102 foreach ( $arr as $r )
1104 if ( ( $i %
2 ) == 1 )
1106 # If there are ever four apostrophes, assume the first is supposed to
1107 # be text, and the remaining three constitute mark-up for bold text.
1108 if ( strlen( $arr[$i] ) == 4 )
1113 # If there are more than 5 apostrophes in a row, assume they're all
1114 # text except for the last 5.
1115 else if ( strlen( $arr[$i] ) > 5 )
1117 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1120 # Count the number of occurrences of bold and italics mark-ups.
1121 # We are not counting sequences of five apostrophes.
1122 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1123 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1124 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1129 # If there is an odd number of both bold and italics, it is likely
1130 # that one of the bold ones was meant to be an apostrophe followed
1131 # by italics. Which one we cannot know for certain, but it is more
1132 # likely to be one that has a single-letter word before it.
1133 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1136 $firstsingleletterword = -1;
1137 $firstmultiletterword = -1;
1139 foreach ( $arr as $r )
1141 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1143 $x1 = substr ($arr[$i-1], -1);
1144 $x2 = substr ($arr[$i-1], -2, 1);
1146 if ($firstspace == -1) $firstspace = $i;
1147 } else if ($x2 == ' ') {
1148 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1150 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1156 # If there is a single-letter word, use it!
1157 if ($firstsingleletterword > -1)
1159 $arr [ $firstsingleletterword ] = "''";
1160 $arr [ $firstsingleletterword-1 ] .= "'";
1162 # If not, but there's a multi-letter word, use that one.
1163 else if ($firstmultiletterword > -1)
1165 $arr [ $firstmultiletterword ] = "''";
1166 $arr [ $firstmultiletterword-1 ] .= "'";
1168 # ... otherwise use the first one that has neither.
1169 # (notice that it is possible for all three to be -1 if, for example,
1170 # there is only one pentuple-apostrophe in the line)
1171 else if ($firstspace > -1)
1173 $arr [ $firstspace ] = "''";
1174 $arr [ $firstspace-1 ] .= "'";
1178 # Now let's actually convert our apostrophic mush to HTML!
1183 foreach ($arr as $r)
1187 if ($state == 'both')
1194 if (strlen ($r) == 2)
1197 { $output .= '</i>'; $state = ''; }
1198 else if ($state == 'bi')
1199 { $output .= '</i>'; $state = 'b'; }
1200 else if ($state == 'ib')
1201 { $output .= '</b></i><b>'; $state = 'b'; }
1202 else if ($state == 'both')
1203 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1204 else # $state can be 'b' or ''
1205 { $output .= '<i>'; $state .= 'i'; }
1207 else if (strlen ($r) == 3)
1210 { $output .= '</b>'; $state = ''; }
1211 else if ($state == 'bi')
1212 { $output .= '</i></b><i>'; $state = 'i'; }
1213 else if ($state == 'ib')
1214 { $output .= '</b>'; $state = 'i'; }
1215 else if ($state == 'both')
1216 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1217 else # $state can be 'i' or ''
1218 { $output .= '<b>'; $state .= 'b'; }
1220 else if (strlen ($r) == 5)
1223 { $output .= '</b><i>'; $state = 'i'; }
1224 else if ($state == 'i')
1225 { $output .= '</i><b>'; $state = 'b'; }
1226 else if ($state == 'bi')
1227 { $output .= '</i></b>'; $state = ''; }
1228 else if ($state == 'ib')
1229 { $output .= '</b></i>'; $state = ''; }
1230 else if ($state == 'both')
1231 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1232 else # ($state == '')
1233 { $buffer = ''; $state = 'both'; }
1238 # Now close all remaining tags. Notice that the order is important.
1239 if ($state == 'b' ||
$state == 'ib')
1241 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1245 # There might be lonely ''''', so make sure we have a buffer
1246 if ($state == 'both' && $buffer)
1247 $output .= '<b><i>'.$buffer.'</i></b>';
1253 * Replace external links
1255 * Note: this is all very hackish and the order of execution matters a lot.
1256 * Make sure to run maintenance/parserTests.php if you change this code.
1260 function replaceExternalLinks( $text ) {
1262 $fname = 'Parser::replaceExternalLinks';
1263 wfProfileIn( $fname );
1265 $sk = $this->mOptions
->getSkin();
1267 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1269 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1272 while ( $i<count( $bits ) ) {
1274 $protocol = $bits[$i++
];
1275 $text = $bits[$i++
];
1276 $trail = $bits[$i++
];
1278 # The characters '<' and '>' (which were escaped by
1279 # removeHTMLtags()) should not be included in
1280 # URLs, per RFC 2396.
1282 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1283 $text = substr($url, $m2[0][1]) . ' ' . $text;
1284 $url = substr($url, 0, $m2[0][1]);
1287 # If the link text is an image URL, replace it with an <img> tag
1288 # This happened by accident in the original parser, but some people used it extensively
1289 $img = $this->maybeMakeExternalImage( $text );
1290 if ( $img !== false ) {
1296 # Set linktype for CSS - if URL==text, link is essentially free
1297 $linktype = ($text == $url) ?
'free' : 'text';
1299 # No link text, e.g. [http://domain.tld/some.link]
1300 if ( $text == '' ) {
1301 # Autonumber if allowed. See bug #5918
1302 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1303 $text = '[' . ++
$this->mAutonumber
. ']';
1304 $linktype = 'autonumber';
1306 # Otherwise just use the URL
1307 $text = htmlspecialchars( $url );
1311 # Have link text, e.g. [http://domain.tld/some.link text]s
1313 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1316 $text = $wgContLang->markNoConversion($text);
1318 $url = Sanitizer
::cleanUrl( $url );
1320 # Process the trail (i.e. everything after this link up until start of the next link),
1321 # replacing any non-bracketed links
1322 $trail = $this->replaceFreeExternalLinks( $trail );
1324 # Use the encoded URL
1325 # This means that users can paste URLs directly into the text
1326 # Funny characters like ö aren't valid in URLs anyway
1327 # This was changed in August 2004
1328 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1330 # Register link in the output object.
1331 # Replace unnecessary URL escape codes with the referenced character
1332 # This prevents spammers from hiding links from the filters
1333 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1334 $this->mOutput
->addExternalLink( $pasteurized );
1337 wfProfileOut( $fname );
1342 * Replace anything that looks like a URL with a link
1345 function replaceFreeExternalLinks( $text ) {
1347 $fname = 'Parser::replaceFreeExternalLinks';
1348 wfProfileIn( $fname );
1350 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1351 $s = array_shift( $bits );
1354 $sk = $this->mOptions
->getSkin();
1356 while ( $i < count( $bits ) ){
1357 $protocol = $bits[$i++
];
1358 $remainder = $bits[$i++
];
1361 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1362 # Found some characters after the protocol that look promising
1363 $url = $protocol . $m[1];
1366 # special case: handle urls as url args:
1367 # http://www.example.com/foo?=http://www.example.com/bar
1368 if(strlen($trail) == 0 &&
1370 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1371 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1374 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1379 # The characters '<' and '>' (which were escaped by
1380 # removeHTMLtags()) should not be included in
1381 # URLs, per RFC 2396.
1383 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1384 $trail = substr($url, $m2[0][1]) . $trail;
1385 $url = substr($url, 0, $m2[0][1]);
1388 # Move trailing punctuation to $trail
1390 # If there is no left bracket, then consider right brackets fair game too
1391 if ( strpos( $url, '(' ) === false ) {
1395 $numSepChars = strspn( strrev( $url ), $sep );
1396 if ( $numSepChars ) {
1397 $trail = substr( $url, -$numSepChars ) . $trail;
1398 $url = substr( $url, 0, -$numSepChars );
1401 $url = Sanitizer
::cleanUrl( $url );
1403 # Is this an external image?
1404 $text = $this->maybeMakeExternalImage( $url );
1405 if ( $text === false ) {
1406 # Not an image, make a link
1407 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1408 # Register it in the output object...
1409 # Replace unnecessary URL escape codes with their equivalent characters
1410 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1411 $this->mOutput
->addExternalLink( $pasteurized );
1413 $s .= $text . $trail;
1415 $s .= $protocol . $remainder;
1418 wfProfileOut( $fname );
1423 * Replace unusual URL escape codes with their equivalent characters
1427 * @todo This can merge genuinely required bits in the path or query string,
1428 * breaking legit URLs. A proper fix would treat the various parts of
1429 * the URL differently; as a workaround, just use the output for
1430 * statistical records, not for actual linking/output.
1432 static function replaceUnusualEscapes( $url ) {
1433 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1434 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1438 * Callback function used in replaceUnusualEscapes().
1439 * Replaces unusual URL escape codes with their equivalent character
1443 private static function replaceUnusualEscapesCallback( $matches ) {
1444 $char = urldecode( $matches[0] );
1445 $ord = ord( $char );
1446 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1447 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1448 // No, shouldn't be escaped
1451 // Yes, leave it escaped
1457 * make an image if it's allowed, either through the global
1458 * option or through the exception
1461 function maybeMakeExternalImage( $url ) {
1462 $sk = $this->mOptions
->getSkin();
1463 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1464 $imagesexception = !empty($imagesfrom);
1466 if ( $this->mOptions
->getAllowExternalImages()
1467 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1468 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1470 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1477 * Process [[ ]] wikilinks
1481 function replaceInternalLinks( $s ) {
1483 static $fname = 'Parser::replaceInternalLinks' ;
1485 wfProfileIn( $fname );
1487 wfProfileIn( $fname.'-setup' );
1489 # the % is needed to support urlencoded titles as well
1490 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1492 $sk = $this->mOptions
->getSkin();
1494 #split the entire text string on occurences of [[
1495 $a = explode( '[[', ' ' . $s );
1496 #get the first element (all text up to first [[), and remove the space we added
1497 $s = array_shift( $a );
1498 $s = substr( $s, 1 );
1500 # Match a link having the form [[namespace:link|alternate]]trail
1502 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1503 # Match cases where there is no "]]", which might still be images
1504 static $e1_img = FALSE;
1505 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1507 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1509 if ( $useLinkPrefixExtension ) {
1510 # Match the end of a line for a word that's not followed by whitespace,
1511 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1512 $e2 = wfMsgForContent( 'linkprefix' );
1515 if( is_null( $this->mTitle
) ) {
1516 wfProfileOut( $fname );
1517 wfProfileOut( $fname.'-setup' );
1518 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1520 $nottalk = !$this->mTitle
->isTalkPage();
1522 if ( $useLinkPrefixExtension ) {
1524 if ( preg_match( $e2, $s, $m ) ) {
1525 $first_prefix = $m[2];
1527 $first_prefix = false;
1533 if($wgContLang->hasVariants()) {
1534 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1536 $selflink = array($this->mTitle
->getPrefixedText());
1538 $useSubpages = $this->areSubpagesAllowed();
1539 wfProfileOut( $fname.'-setup' );
1541 # Loop for each link
1542 for ($k = 0; isset( $a[$k] ); $k++
) {
1544 if ( $useLinkPrefixExtension ) {
1545 wfProfileIn( $fname.'-prefixhandling' );
1546 if ( preg_match( $e2, $s, $m ) ) {
1554 $prefix = $first_prefix;
1555 $first_prefix = false;
1557 wfProfileOut( $fname.'-prefixhandling' );
1560 $might_be_img = false;
1562 wfProfileIn( "$fname-e1" );
1563 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1565 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1566 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1567 # the real problem is with the $e1 regex
1570 # Still some problems for cases where the ] is meant to be outside punctuation,
1571 # and no image is in sight. See bug 2095.
1574 substr( $m[3], 0, 1 ) === ']' &&
1575 strpos($text, '[') !== false
1578 $text .= ']'; # so that replaceExternalLinks($text) works later
1579 $m[3] = substr( $m[3], 1 );
1581 # fix up urlencoded title texts
1582 if( strpos( $m[1], '%' ) !== false ) {
1583 # Should anchors '#' also be rejected?
1584 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1587 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1588 $might_be_img = true;
1590 if ( strpos( $m[1], '%' ) !== false ) {
1591 $m[1] = urldecode($m[1]);
1594 } else { # Invalid form; output directly
1595 $s .= $prefix . '[[' . $line ;
1596 wfProfileOut( "$fname-e1" );
1599 wfProfileOut( "$fname-e1" );
1600 wfProfileIn( "$fname-misc" );
1602 # Don't allow internal links to pages containing
1603 # PROTO: where PROTO is a valid URL protocol; these
1604 # should be external links.
1605 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1606 $s .= $prefix . '[[' . $line ;
1607 wfProfileOut( "$fname-misc" );
1611 # Make subpage if necessary
1612 if( $useSubpages ) {
1613 $link = $this->maybeDoSubpageLink( $m[1], $text );
1618 $noforce = (substr($m[1], 0, 1) != ':');
1620 # Strip off leading ':'
1621 $link = substr($link, 1);
1624 wfProfileOut( "$fname-misc" );
1625 wfProfileIn( "$fname-title" );
1626 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1628 $s .= $prefix . '[[' . $line;
1629 wfProfileOut( "$fname-title" );
1633 $ns = $nt->getNamespace();
1634 $iw = $nt->getInterWiki();
1635 wfProfileOut( "$fname-title" );
1637 if ($might_be_img) { # if this is actually an invalid link
1638 wfProfileIn( "$fname-might_be_img" );
1639 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1641 while (isset ($a[$k+
1]) ) {
1642 #look at the next 'line' to see if we can close it there
1643 $spliced = array_splice( $a, $k +
1, 1 );
1644 $next_line = array_shift( $spliced );
1645 $m = explode( ']]', $next_line, 3 );
1646 if ( count( $m ) == 3 ) {
1647 # the first ]] closes the inner link, the second the image
1649 $text .= "[[{$m[0]}]]{$m[1]}";
1652 } elseif ( count( $m ) == 2 ) {
1653 #if there's exactly one ]] that's fine, we'll keep looking
1654 $text .= "[[{$m[0]}]]{$m[1]}";
1656 #if $next_line is invalid too, we need look no further
1657 $text .= '[[' . $next_line;
1662 # we couldn't find the end of this imageLink, so output it raw
1663 #but don't ignore what might be perfectly normal links in the text we've examined
1664 $text = $this->replaceInternalLinks($text);
1665 $s .= "{$prefix}[[$link|$text";
1666 # note: no $trail, because without an end, there *is* no trail
1667 wfProfileOut( "$fname-might_be_img" );
1670 } else { #it's not an image, so output it raw
1671 $s .= "{$prefix}[[$link|$text";
1672 # note: no $trail, because without an end, there *is* no trail
1673 wfProfileOut( "$fname-might_be_img" );
1676 wfProfileOut( "$fname-might_be_img" );
1679 $wasblank = ( '' == $text );
1680 if( $wasblank ) $text = $link;
1682 # Link not escaped by : , create the various objects
1686 wfProfileIn( "$fname-interwiki" );
1687 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1688 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1689 $s = rtrim($s . $prefix);
1690 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1691 wfProfileOut( "$fname-interwiki" );
1694 wfProfileOut( "$fname-interwiki" );
1696 if ( $ns == NS_IMAGE
) {
1697 wfProfileIn( "$fname-image" );
1698 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1699 # recursively parse links inside the image caption
1700 # actually, this will parse them in any other parameters, too,
1701 # but it might be hard to fix that, and it doesn't matter ATM
1702 $text = $this->replaceExternalLinks($text);
1703 $text = $this->replaceInternalLinks($text);
1705 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1706 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1707 $this->mOutput
->addImage( $nt->getDBkey() );
1709 wfProfileOut( "$fname-image" );
1712 # We still need to record the image's presence on the page
1713 $this->mOutput
->addImage( $nt->getDBkey() );
1715 wfProfileOut( "$fname-image" );
1719 if ( $ns == NS_CATEGORY
) {
1720 wfProfileIn( "$fname-category" );
1721 $s = rtrim($s . "\n"); # bug 87
1724 $sortkey = $this->getDefaultSort();
1728 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1729 $sortkey = str_replace( "\n", '', $sortkey );
1730 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1731 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1734 * Strip the whitespace Category links produce, see bug 87
1735 * @todo We might want to use trim($tmp, "\n") here.
1737 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1739 wfProfileOut( "$fname-category" );
1744 # Self-link checking
1745 if( $nt->getFragment() === '' ) {
1746 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1747 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1752 # Special and Media are pseudo-namespaces; no pages actually exist in them
1753 if( $ns == NS_MEDIA
) {
1754 # Give extensions a chance to select the file revision for us
1755 $skip = $time = false;
1756 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1758 $link = $sk->makeLinkObj( $nt );
1760 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1762 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1763 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1764 $this->mOutput
->addImage( $nt->getDBkey() );
1766 } elseif( $ns == NS_SPECIAL
) {
1767 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1768 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1770 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1773 } elseif( $ns == NS_IMAGE
) {
1774 $img = wfFindFile( $nt );
1776 // Force a blue link if the file exists; may be a remote
1777 // upload on the shared repository, and we want to see its
1778 // auto-generated page.
1779 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1780 $this->mOutput
->addLink( $nt );
1784 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1786 wfProfileOut( $fname );
1791 * Make a link placeholder. The text returned can be later resolved to a real link with
1792 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1793 * parsing of interwiki links, and secondly to allow all existence checks and
1794 * article length checks (for stub links) to be bundled into a single query.
1797 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1798 wfProfileIn( __METHOD__
);
1799 if ( ! is_object($nt) ) {
1801 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1803 # Separate the link trail from the rest of the link
1804 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1806 if ( $nt->isExternal() ) {
1807 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1808 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1809 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1811 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1812 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1813 $this->mLinkHolders
['queries'][] = $query;
1814 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1815 $this->mLinkHolders
['titles'][] = $nt;
1817 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1820 wfProfileOut( __METHOD__
);
1825 * Render a forced-blue link inline; protect against double expansion of
1826 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1827 * Since this little disaster has to split off the trail text to avoid
1828 * breaking URLs in the following text without breaking trails on the
1829 * wiki links, it's been made into a horrible function.
1832 * @param string $text
1833 * @param string $query
1834 * @param string $trail
1835 * @param string $prefix
1836 * @return string HTML-wikitext mix oh yuck
1838 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1839 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1840 $sk = $this->mOptions
->getSkin();
1841 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1842 return $this->armorLinks( $link ) . $trail;
1846 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1847 * going to go through further parsing steps before inline URL expansion.
1849 * In particular this is important when using action=render, which causes
1850 * full URLs to be included.
1852 * Oh man I hate our multi-layer parser!
1854 * @param string more-or-less HTML
1855 * @return string less-or-more HTML with NOPARSE bits
1857 function armorLinks( $text ) {
1858 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1859 "{$this->mUniqPrefix}NOPARSE$1", $text );
1863 * Return true if subpage links should be expanded on this page.
1866 function areSubpagesAllowed() {
1867 # Some namespaces don't allow subpages
1868 global $wgNamespacesWithSubpages;
1869 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1873 * Handle link to subpage if necessary
1874 * @param string $target the source of the link
1875 * @param string &$text the link text, modified as necessary
1876 * @return string the full name of the link
1879 function maybeDoSubpageLink($target, &$text) {
1882 # :Foobar -- override special treatment of prefix (images, language links)
1883 # /Foobar -- convert to CurrentPage/Foobar
1884 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1885 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1886 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1888 $fname = 'Parser::maybeDoSubpageLink';
1889 wfProfileIn( $fname );
1890 $ret = $target; # default return value is no change
1892 # Some namespaces don't allow subpages,
1893 # so only perform processing if subpages are allowed
1894 if( $this->areSubpagesAllowed() ) {
1895 $hash = strpos( $target, '#' );
1896 if( $hash !== false ) {
1897 $suffix = substr( $target, $hash );
1898 $target = substr( $target, 0, $hash );
1903 $target = trim( $target );
1904 # Look at the first character
1905 if( $target != '' && $target{0} == '/' ) {
1906 # / at end means we don't want the slash to be shown
1908 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1909 if( $trailingSlashes ) {
1910 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1912 $noslash = substr( $target, 1 );
1915 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1916 if( '' === $text ) {
1917 $text = $target . $suffix;
1918 } # this might be changed for ugliness reasons
1920 # check for .. subpage backlinks
1922 $nodotdot = $target;
1923 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1925 $nodotdot = substr( $nodotdot, 3 );
1927 if($dotdotcount > 0) {
1928 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1929 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1930 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1931 # / at the end means don't show full path
1932 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1933 $nodotdot = substr( $nodotdot, 0, -1 );
1934 if( '' === $text ) {
1935 $text = $nodotdot . $suffix;
1938 $nodotdot = trim( $nodotdot );
1939 if( $nodotdot != '' ) {
1940 $ret .= '/' . $nodotdot;
1948 wfProfileOut( $fname );
1953 * Used by doBlockLevels()
1956 /* private */ function closeParagraph() {
1958 if ( '' != $this->mLastSection
) {
1959 $result = '</' . $this->mLastSection
. ">\n";
1961 $this->mInPre
= false;
1962 $this->mLastSection
= '';
1965 # getCommon() returns the length of the longest common substring
1966 # of both arguments, starting at the beginning of both.
1968 /* private */ function getCommon( $st1, $st2 ) {
1969 $fl = strlen( $st1 );
1970 $shorter = strlen( $st2 );
1971 if ( $fl < $shorter ) { $shorter = $fl; }
1973 for ( $i = 0; $i < $shorter; ++
$i ) {
1974 if ( $st1{$i} != $st2{$i} ) { break; }
1978 # These next three functions open, continue, and close the list
1979 # element appropriate to the prefix character passed into them.
1981 /* private */ function openList( $char ) {
1982 $result = $this->closeParagraph();
1984 if ( '*' == $char ) { $result .= '<ul><li>'; }
1985 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1986 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1987 else if ( ';' == $char ) {
1988 $result .= '<dl><dt>';
1989 $this->mDTopen
= true;
1991 else { $result = '<!-- ERR 1 -->'; }
1996 /* private */ function nextItem( $char ) {
1997 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1998 else if ( ':' == $char ||
';' == $char ) {
2000 if ( $this->mDTopen
) { $close = '</dt>'; }
2001 if ( ';' == $char ) {
2002 $this->mDTopen
= true;
2003 return $close . '<dt>';
2005 $this->mDTopen
= false;
2006 return $close . '<dd>';
2009 return '<!-- ERR 2 -->';
2012 /* private */ function closeList( $char ) {
2013 if ( '*' == $char ) { $text = '</li></ul>'; }
2014 else if ( '#' == $char ) { $text = '</li></ol>'; }
2015 else if ( ':' == $char ) {
2016 if ( $this->mDTopen
) {
2017 $this->mDTopen
= false;
2018 $text = '</dt></dl>';
2020 $text = '</dd></dl>';
2023 else { return '<!-- ERR 3 -->'; }
2029 * Make lists from lines starting with ':', '*', '#', etc.
2032 * @return string the lists rendered as HTML
2034 function doBlockLevels( $text, $linestart ) {
2035 $fname = 'Parser::doBlockLevels';
2036 wfProfileIn( $fname );
2038 # Parsing through the text line by line. The main thing
2039 # happening here is handling of block-level elements p, pre,
2040 # and making lists from lines starting with * # : etc.
2042 $textLines = explode( "\n", $text );
2044 $lastPrefix = $output = '';
2045 $this->mDTopen
= $inBlockElem = false;
2047 $paragraphStack = false;
2049 if ( !$linestart ) {
2050 $output .= array_shift( $textLines );
2052 foreach ( $textLines as $oLine ) {
2053 $lastPrefixLength = strlen( $lastPrefix );
2054 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2055 $preOpenMatch = preg_match('/<pre/i', $oLine );
2056 if ( !$this->mInPre
) {
2057 # Multiple prefixes may abut each other for nested lists.
2058 $prefixLength = strspn( $oLine, '*#:;' );
2059 $pref = substr( $oLine, 0, $prefixLength );
2062 $pref2 = str_replace( ';', ':', $pref );
2063 $t = substr( $oLine, $prefixLength );
2064 $this->mInPre
= !empty($preOpenMatch);
2066 # Don't interpret any other prefixes in preformatted text
2068 $pref = $pref2 = '';
2073 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2074 # Same as the last item, so no need to deal with nesting or opening stuff
2075 $output .= $this->nextItem( substr( $pref, -1 ) );
2076 $paragraphStack = false;
2078 if ( substr( $pref, -1 ) == ';') {
2079 # The one nasty exception: definition lists work like this:
2080 # ; title : definition text
2081 # So we check for : in the remainder text to split up the
2082 # title and definition, without b0rking links.
2084 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2086 $output .= $term . $this->nextItem( ':' );
2089 } elseif( $prefixLength ||
$lastPrefixLength ) {
2090 # Either open or close a level...
2091 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2092 $paragraphStack = false;
2094 while( $commonPrefixLength < $lastPrefixLength ) {
2095 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2096 --$lastPrefixLength;
2098 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2099 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2101 while ( $prefixLength > $commonPrefixLength ) {
2102 $char = substr( $pref, $commonPrefixLength, 1 );
2103 $output .= $this->openList( $char );
2105 if ( ';' == $char ) {
2106 # FIXME: This is dupe of code above
2107 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2109 $output .= $term . $this->nextItem( ':' );
2112 ++
$commonPrefixLength;
2114 $lastPrefix = $pref2;
2116 if( 0 == $prefixLength ) {
2117 wfProfileIn( "$fname-paragraph" );
2118 # No prefix (not in list)--go to paragraph mode
2119 // XXX: use a stack for nestable elements like span, table and div
2120 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2121 $closematch = preg_match(
2122 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2123 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2124 if ( $openmatch or $closematch ) {
2125 $paragraphStack = false;
2126 #Â TODO bug 5718: paragraph closed
2127 $output .= $this->closeParagraph();
2128 if ( $preOpenMatch and !$preCloseMatch ) {
2129 $this->mInPre
= true;
2131 if ( $closematch ) {
2132 $inBlockElem = false;
2134 $inBlockElem = true;
2136 } else if ( !$inBlockElem && !$this->mInPre
) {
2137 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2139 if ($this->mLastSection
!= 'pre') {
2140 $paragraphStack = false;
2141 $output .= $this->closeParagraph().'<pre>';
2142 $this->mLastSection
= 'pre';
2144 $t = substr( $t, 1 );
2147 if ( '' == trim($t) ) {
2148 if ( $paragraphStack ) {
2149 $output .= $paragraphStack.'<br />';
2150 $paragraphStack = false;
2151 $this->mLastSection
= 'p';
2153 if ($this->mLastSection
!= 'p' ) {
2154 $output .= $this->closeParagraph();
2155 $this->mLastSection
= '';
2156 $paragraphStack = '<p>';
2158 $paragraphStack = '</p><p>';
2162 if ( $paragraphStack ) {
2163 $output .= $paragraphStack;
2164 $paragraphStack = false;
2165 $this->mLastSection
= 'p';
2166 } else if ($this->mLastSection
!= 'p') {
2167 $output .= $this->closeParagraph().'<p>';
2168 $this->mLastSection
= 'p';
2173 wfProfileOut( "$fname-paragraph" );
2175 // somewhere above we forget to get out of pre block (bug 785)
2176 if($preCloseMatch && $this->mInPre
) {
2177 $this->mInPre
= false;
2179 if ($paragraphStack === false) {
2183 while ( $prefixLength ) {
2184 $output .= $this->closeList( $pref2{$prefixLength-1} );
2187 if ( '' != $this->mLastSection
) {
2188 $output .= '</' . $this->mLastSection
. '>';
2189 $this->mLastSection
= '';
2192 wfProfileOut( $fname );
2197 * Split up a string on ':', ignoring any occurences inside tags
2198 * to prevent illegal overlapping.
2199 * @param string $str the string to split
2200 * @param string &$before set to everything before the ':'
2201 * @param string &$after set to everything after the ':'
2202 * return string the position of the ':', or false if none found
2204 function findColonNoLinks($str, &$before, &$after) {
2205 $fname = 'Parser::findColonNoLinks';
2206 wfProfileIn( $fname );
2208 $pos = strpos( $str, ':' );
2209 if( $pos === false ) {
2211 wfProfileOut( $fname );
2215 $lt = strpos( $str, '<' );
2216 if( $lt === false ||
$lt > $pos ) {
2217 // Easy; no tag nesting to worry about
2218 $before = substr( $str, 0, $pos );
2219 $after = substr( $str, $pos+
1 );
2220 wfProfileOut( $fname );
2224 // Ugly state machine to walk through avoiding tags.
2225 $state = self
::COLON_STATE_TEXT
;
2227 $len = strlen( $str );
2228 for( $i = 0; $i < $len; $i++
) {
2232 // (Using the number is a performance hack for common cases)
2233 case 0: // self::COLON_STATE_TEXT:
2236 // Could be either a <start> tag or an </end> tag
2237 $state = self
::COLON_STATE_TAGSTART
;
2242 $before = substr( $str, 0, $i );
2243 $after = substr( $str, $i +
1 );
2244 wfProfileOut( $fname );
2247 // Embedded in a tag; don't break it.
2250 // Skip ahead looking for something interesting
2251 $colon = strpos( $str, ':', $i );
2252 if( $colon === false ) {
2253 // Nothing else interesting
2254 wfProfileOut( $fname );
2257 $lt = strpos( $str, '<', $i );
2258 if( $stack === 0 ) {
2259 if( $lt === false ||
$colon < $lt ) {
2261 $before = substr( $str, 0, $colon );
2262 $after = substr( $str, $colon +
1 );
2263 wfProfileOut( $fname );
2267 if( $lt === false ) {
2268 // Nothing else interesting to find; abort!
2269 // We're nested, but there's no close tags left. Abort!
2272 // Skip ahead to next tag start
2274 $state = self
::COLON_STATE_TAGSTART
;
2277 case 1: // self::COLON_STATE_TAG:
2282 $state = self
::COLON_STATE_TEXT
;
2285 // Slash may be followed by >?
2286 $state = self
::COLON_STATE_TAGSLASH
;
2292 case 2: // self::COLON_STATE_TAGSTART:
2295 $state = self
::COLON_STATE_CLOSETAG
;
2298 $state = self
::COLON_STATE_COMMENT
;
2301 // Illegal early close? This shouldn't happen D:
2302 $state = self
::COLON_STATE_TEXT
;
2305 $state = self
::COLON_STATE_TAG
;
2308 case 3: // self::COLON_STATE_CLOSETAG:
2313 wfDebug( "Invalid input in $fname; too many close tags\n" );
2314 wfProfileOut( $fname );
2317 $state = self
::COLON_STATE_TEXT
;
2320 case self
::COLON_STATE_TAGSLASH
:
2322 // Yes, a self-closed tag <blah/>
2323 $state = self
::COLON_STATE_TEXT
;
2325 // Probably we're jumping the gun, and this is an attribute
2326 $state = self
::COLON_STATE_TAG
;
2329 case 5: // self::COLON_STATE_COMMENT:
2331 $state = self
::COLON_STATE_COMMENTDASH
;
2334 case self
::COLON_STATE_COMMENTDASH
:
2336 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2338 $state = self
::COLON_STATE_COMMENT
;
2341 case self
::COLON_STATE_COMMENTDASHDASH
:
2343 $state = self
::COLON_STATE_TEXT
;
2345 $state = self
::COLON_STATE_COMMENT
;
2349 throw new MWException( "State machine error in $fname" );
2353 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2356 wfProfileOut( $fname );
2361 * Return value of a magic variable (like PAGENAME)
2365 function getVariableValue( $index ) {
2366 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2369 * Some of these require message or data lookups and can be
2370 * expensive to check many times.
2372 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2373 if ( isset( $this->mVarCache
[$index] ) ) {
2374 return $this->mVarCache
[$index];
2378 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2379 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2382 global $wgLocaltimezone;
2383 if ( isset( $wgLocaltimezone ) ) {
2384 $oldtz = getenv( 'TZ' );
2385 putenv( 'TZ='.$wgLocaltimezone );
2388 wfSuppressWarnings(); // E_STRICT system time bitching
2389 $localTimestamp = date( 'YmdHis', $ts );
2390 $localMonth = date( 'm', $ts );
2391 $localMonthName = date( 'n', $ts );
2392 $localDay = date( 'j', $ts );
2393 $localDay2 = date( 'd', $ts );
2394 $localDayOfWeek = date( 'w', $ts );
2395 $localWeek = date( 'W', $ts );
2396 $localYear = date( 'Y', $ts );
2397 $localHour = date( 'H', $ts );
2398 if ( isset( $wgLocaltimezone ) ) {
2399 putenv( 'TZ='.$oldtz );
2401 wfRestoreWarnings();
2404 case 'currentmonth':
2405 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2406 case 'currentmonthname':
2407 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2408 case 'currentmonthnamegen':
2409 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2410 case 'currentmonthabbrev':
2411 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2413 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2415 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2417 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2418 case 'localmonthname':
2419 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2420 case 'localmonthnamegen':
2421 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2422 case 'localmonthabbrev':
2423 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2425 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2427 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2429 return wfEscapeWikiText( $this->mTitle
->getText() );
2431 return $this->mTitle
->getPartialURL();
2432 case 'fullpagename':
2433 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2434 case 'fullpagenamee':
2435 return $this->mTitle
->getPrefixedURL();
2437 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2438 case 'subpagenamee':
2439 return $this->mTitle
->getSubpageUrlForm();
2440 case 'basepagename':
2441 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2442 case 'basepagenamee':
2443 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2444 case 'talkpagename':
2445 if( $this->mTitle
->canTalk() ) {
2446 $talkPage = $this->mTitle
->getTalkPage();
2447 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2451 case 'talkpagenamee':
2452 if( $this->mTitle
->canTalk() ) {
2453 $talkPage = $this->mTitle
->getTalkPage();
2454 return $talkPage->getPrefixedUrl();
2458 case 'subjectpagename':
2459 $subjPage = $this->mTitle
->getSubjectPage();
2460 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2461 case 'subjectpagenamee':
2462 $subjPage = $this->mTitle
->getSubjectPage();
2463 return $subjPage->getPrefixedUrl();
2465 // Let the edit saving system know we should parse the page
2466 // *after* a revision ID has been assigned.
2467 $this->mOutput
->setFlag( 'vary-revision' );
2468 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2469 return $this->mRevisionId
;
2471 // Let the edit saving system know we should parse the page
2472 // *after* a revision ID has been assigned. This is for null edits.
2473 $this->mOutput
->setFlag( 'vary-revision' );
2474 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2475 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2476 case 'revisionday2':
2477 // Let the edit saving system know we should parse the page
2478 // *after* a revision ID has been assigned. This is for null edits.
2479 $this->mOutput
->setFlag( 'vary-revision' );
2480 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2481 return substr( $this->getRevisionTimestamp(), 6, 2 );
2482 case 'revisionmonth':
2483 // Let the edit saving system know we should parse the page
2484 // *after* a revision ID has been assigned. This is for null edits.
2485 $this->mOutput
->setFlag( 'vary-revision' );
2486 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2487 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2488 case 'revisionyear':
2489 // Let the edit saving system know we should parse the page
2490 // *after* a revision ID has been assigned. This is for null edits.
2491 $this->mOutput
->setFlag( 'vary-revision' );
2492 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2493 return substr( $this->getRevisionTimestamp(), 0, 4 );
2494 case 'revisiontimestamp':
2495 // Let the edit saving system know we should parse the page
2496 // *after* a revision ID has been assigned. This is for null edits.
2497 $this->mOutput
->setFlag( 'vary-revision' );
2498 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2499 return $this->getRevisionTimestamp();
2501 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2503 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2505 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2507 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2508 case 'subjectspace':
2509 return $this->mTitle
->getSubjectNsText();
2510 case 'subjectspacee':
2511 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2512 case 'currentdayname':
2513 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2515 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2517 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2519 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2521 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2522 // int to remove the padding
2523 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2525 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2526 case 'localdayname':
2527 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2531 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2535 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2536 // int to remove the padding
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2540 case 'numberofarticles':
2541 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2542 case 'numberoffiles':
2543 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2544 case 'numberofusers':
2545 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2546 case 'numberofpages':
2547 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2548 case 'numberofadmins':
2549 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2550 case 'numberofedits':
2551 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2552 case 'currenttimestamp':
2553 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2554 case 'localtimestamp':
2555 return $this->mVarCache
[$index] = $localTimestamp;
2556 case 'currentversion':
2557 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2563 return $wgServerName;
2565 return $wgScriptPath;
2566 case 'directionmark':
2567 return $wgContLang->getDirMark();
2568 case 'contentlanguage':
2569 global $wgContLanguageCode;
2570 return $wgContLanguageCode;
2573 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2581 * initialise the magic variables (like CURRENTMONTHNAME)
2585 function initialiseVariables() {
2586 $fname = 'Parser::initialiseVariables';
2587 wfProfileIn( $fname );
2588 $variableIDs = MagicWord
::getVariableIDs();
2590 $this->mVariables
= new MagicWordArray( $variableIDs );
2591 wfProfileOut( $fname );
2595 * Preprocess some wikitext and return the document tree.
2596 * This is the ghost of replace_variables().
2598 * @param string $text The text to parse
2599 * @param integer flags Bitwise combination of:
2600 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2601 * included. Default is to assume a direct page view.
2603 * The generated DOM tree must depend only on the input text and the flags.
2604 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2606 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2607 * change in the DOM tree for a given text, must be passed through the section identifier
2608 * in the section edit link and thus back to extractSections().
2610 * The output of this function is currently only cached in process memory, but a persistent
2611 * cache may be implemented at a later date which takes further advantage of these strict
2612 * dependency requirements.
2616 function preprocessToDom ( $text, $flags = 0 ) {
2617 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2622 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2624 public static function splitWhitespace( $s ) {
2625 $ltrimmed = ltrim( $s );
2626 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2627 $trimmed = rtrim( $ltrimmed );
2628 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2630 $w2 = substr( $ltrimmed, -$diff );
2634 return array( $w1, $trimmed, $w2 );
2638 * Replace magic variables, templates, and template arguments
2639 * with the appropriate text. Templates are substituted recursively,
2640 * taking care to avoid infinite loops.
2642 * Note that the substitution depends on value of $mOutputType:
2643 * self::OT_WIKI: only {{subst:}} templates
2644 * self::OT_PREPROCESS: templates but not extension tags
2645 * self::OT_HTML: all templates and extension tags
2647 * @param string $tex The text to transform
2648 * @param PPFrame $frame Object describing the arguments passed to the template
2649 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2652 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2653 # Prevent too big inclusions
2654 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2658 $fname = __METHOD__
;
2659 wfProfileIn( $fname );
2661 if ( $frame === false ) {
2662 $frame = $this->getPreprocessor()->newFrame();
2663 } elseif ( !( $frame instanceof PPFrame
) ) {
2664 throw new MWException( __METHOD__
. ' called using the old argument format' );
2667 $dom = $this->preprocessToDom( $text );
2668 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2669 $text = $frame->expand( $dom, $flags );
2671 wfProfileOut( $fname );
2675 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2676 static function createAssocArgs( $args ) {
2677 $assocArgs = array();
2679 foreach( $args as $arg ) {
2680 $eqpos = strpos( $arg, '=' );
2681 if ( $eqpos === false ) {
2682 $assocArgs[$index++
] = $arg;
2684 $name = trim( substr( $arg, 0, $eqpos ) );
2685 $value = trim( substr( $arg, $eqpos+
1 ) );
2686 if ( $value === false ) {
2689 if ( $name !== false ) {
2690 $assocArgs[$name] = $value;
2699 * Warn the user when a parser limitation is reached
2700 * Will warn at most once the user per limitation type
2702 * @param string $limitationType, should be one of:
2703 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2704 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2705 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2706 * @params int $current, $max When an explicit limit has been
2707 * exceeded, provide the values (optional)
2709 function limitationWarn( $limitationType, $current=null, $max=null) {
2710 $msgName = $limitationType . '-warning';
2711 //does no harm if $current and $max are present but are unnecessary for the message
2712 $warning = wfMsg( $msgName, $current, $max);
2713 $this->mOutput
->addWarning( $warning );
2714 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2716 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2721 * Return the text of a template, after recursively
2722 * replacing any variables or templates within the template.
2724 * @param array $piece The parts of the template
2725 * $piece['title']: the title, i.e. the part before the |
2726 * $piece['parts']: the parameter array
2727 * $piece['lineStart']: whether the brace was at the start of a line
2728 * @param PPFrame The current frame, contains template arguments
2729 * @return string the text of the template
2732 function braceSubstitution( $piece, $frame ) {
2733 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2734 $fname = __METHOD__
;
2735 wfProfileIn( $fname );
2736 wfProfileIn( __METHOD__
.'-setup' );
2739 $found = false; # $text has been filled
2740 $nowiki = false; # wiki markup in $text should be escaped
2741 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2742 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2743 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2744 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2746 # Title object, where $text came from
2749 # $part1 is the bit before the first |, and must contain only title characters.
2750 # Various prefixes will be stripped from it later.
2751 $titleWithSpaces = $frame->expand( $piece['title'] );
2752 $part1 = trim( $titleWithSpaces );
2755 # Original title text preserved for various purposes
2756 $originalTitle = $part1;
2758 # $args is a list of argument nodes, starting from index 0, not including $part1
2759 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2760 wfProfileOut( __METHOD__
.'-setup' );
2763 wfProfileIn( __METHOD__
.'-modifiers' );
2765 $mwSubst = MagicWord
::get( 'subst' );
2766 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2767 # One of two possibilities is true:
2768 # 1) Found SUBST but not in the PST phase
2769 # 2) Didn't find SUBST and in the PST phase
2770 # In either case, return without further processing
2771 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2778 if ( !$found && $args->getLength() == 0 ) {
2779 $id = $this->mVariables
->matchStartToEnd( $part1 );
2780 if ( $id !== false ) {
2781 $text = $this->getVariableValue( $id );
2782 if (MagicWord
::getCacheTTL($id)>-1)
2783 $this->mOutput
->mContainsOldMagic
= true;
2788 # MSG, MSGNW and RAW
2791 $mwMsgnw = MagicWord
::get( 'msgnw' );
2792 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2795 # Remove obsolete MSG:
2796 $mwMsg = MagicWord
::get( 'msg' );
2797 $mwMsg->matchStartAndRemove( $part1 );
2801 $mwRaw = MagicWord
::get( 'raw' );
2802 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2803 $forceRawInterwiki = true;
2806 wfProfileOut( __METHOD__
.'-modifiers' );
2810 wfProfileIn( __METHOD__
. '-pfunc' );
2812 $colonPos = strpos( $part1, ':' );
2813 if ( $colonPos !== false ) {
2814 # Case sensitive functions
2815 $function = substr( $part1, 0, $colonPos );
2816 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2817 $function = $this->mFunctionSynonyms
[1][$function];
2819 # Case insensitive functions
2820 $function = strtolower( $function );
2821 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2822 $function = $this->mFunctionSynonyms
[0][$function];
2828 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2829 $initialArgs = array( &$this );
2830 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2831 if ( $flags & SFH_OBJECT_ARGS
) {
2832 # Add a frame parameter, and pass the arguments as an array
2833 $allArgs = $initialArgs;
2834 $allArgs[] = $frame;
2835 for ( $i = 0; $i < $args->getLength(); $i++
) {
2836 $funcArgs[] = $args->item( $i );
2838 $allArgs[] = $funcArgs;
2840 # Convert arguments to plain text
2841 for ( $i = 0; $i < $args->getLength(); $i++
) {
2842 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2844 $allArgs = array_merge( $initialArgs, $funcArgs );
2847 # Workaround for PHP bug 35229 and similar
2848 if ( !is_callable( $callback ) ) {
2849 throw new MWException( "Tag hook for $name is not callable\n" );
2851 $result = call_user_func_array( $callback, $allArgs );
2854 $preprocessFlags = 0;
2856 if ( is_array( $result ) ) {
2857 if ( isset( $result[0] ) ) {
2859 unset( $result[0] );
2862 // Extract flags into the local scope
2863 // This allows callers to set flags such as nowiki, found, etc.
2869 $text = $this->preprocessToDom( $text, $preprocessFlags );
2874 wfProfileOut( __METHOD__
. '-pfunc' );
2877 # Finish mangling title and then check for loops.
2878 # Set $title to a Title object and $titleText to the PDBK
2881 # Split the title into page and subpage
2883 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2884 if ($subpage !== '') {
2885 $ns = $this->mTitle
->getNamespace();
2887 $title = Title
::newFromText( $part1, $ns );
2889 $titleText = $title->getPrefixedText();
2890 # Check for language variants if the template is not found
2891 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2892 $wgContLang->findVariantLink($part1, $title);
2894 # Do infinite loop check
2895 if ( !$frame->loopCheck( $title ) ) {
2897 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2898 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2900 # Do recursion depth check
2901 $limit = $this->mOptions
->getMaxTemplateDepth();
2902 if ( $frame->depth
>= $limit ) {
2904 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2909 # Load from database
2910 if ( !$found && $title ) {
2911 wfProfileIn( __METHOD__
. '-loadtpl' );
2912 if ( !$title->isExternal() ) {
2913 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2914 $text = SpecialPage
::capturePath( $title );
2915 if ( is_string( $text ) ) {
2918 $this->disableCache();
2920 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2921 $found = false; //access denied
2922 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2924 list( $text, $title ) = $this->getTemplateDom( $title );
2925 if ( $text !== false ) {
2931 # If the title is valid but undisplayable, make a link to it
2932 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2933 $text = "[[:$titleText]]";
2936 } elseif ( $title->isTrans() ) {
2937 // Interwiki transclusion
2938 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2939 $text = $this->interwikiTransclude( $title, 'render' );
2942 $text = $this->interwikiTransclude( $title, 'raw' );
2943 // Preprocess it like a template
2944 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2949 wfProfileOut( __METHOD__
. '-loadtpl' );
2952 # If we haven't found text to substitute by now, we're done
2953 # Recover the source wikitext and return it
2955 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2956 wfProfileOut( $fname );
2957 return array( 'object' => $text );
2960 # Expand DOM-style return values in a child frame
2961 if ( $isChildObj ) {
2962 # Clean up argument array
2963 $newFrame = $frame->newChild( $args, $title );
2966 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2967 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2968 # Expansion is eligible for the empty-frame cache
2969 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2970 $text = $this->mTplExpandCache
[$titleText];
2972 $text = $newFrame->expand( $text );
2973 $this->mTplExpandCache
[$titleText] = $text;
2976 # Uncached expansion
2977 $text = $newFrame->expand( $text );
2980 if ( $isLocalObj && $nowiki ) {
2981 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2982 $isLocalObj = false;
2985 # Replace raw HTML by a placeholder
2986 # Add a blank line preceding, to prevent it from mucking up
2987 # immediately preceding headings
2989 $text = "\n\n" . $this->insertStripItem( $text );
2991 # Escape nowiki-style return values
2992 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2993 $text = wfEscapeWikiText( $text );
2995 # Bug 529: if the template begins with a table or block-level
2996 # element, it should be treated as beginning a new line.
2997 # This behaviour is somewhat controversial.
2998 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2999 $text = "\n" . $text;
3002 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3003 # Error, oversize inclusion
3004 $text = "[[$originalTitle]]" .
3005 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3006 $this->limitationWarn( 'post-expand-template-inclusion' );
3009 if ( $isLocalObj ) {
3010 $ret = array( 'object' => $text );
3012 $ret = array( 'text' => $text );
3015 wfProfileOut( $fname );
3020 * Get the semi-parsed DOM representation of a template with a given title,
3021 * and its redirect destination title. Cached.
3023 function getTemplateDom( $title ) {
3024 $cacheTitle = $title;
3025 $titleText = $title->getPrefixedDBkey();
3027 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3028 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3029 $title = Title
::makeTitle( $ns, $dbk );
3030 $titleText = $title->getPrefixedDBkey();
3032 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3033 return array( $this->mTplDomCache
[$titleText], $title );
3036 // Cache miss, go to the database
3037 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3039 if ( $text === false ) {
3040 $this->mTplDomCache
[$titleText] = false;
3041 return array( false, $title );
3044 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3045 $this->mTplDomCache
[ $titleText ] = $dom;
3047 if (! $title->equals($cacheTitle)) {
3048 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3049 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3052 return array( $dom, $title );
3056 * Fetch the unparsed text of a template and register a reference to it.
3058 function fetchTemplateAndTitle( $title ) {
3059 $templateCb = $this->mOptions
->getTemplateCallback();
3060 $stuff = call_user_func( $templateCb, $title );
3061 $text = $stuff['text'];
3062 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3063 if ( isset( $stuff['deps'] ) ) {
3064 foreach ( $stuff['deps'] as $dep ) {
3065 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3068 return array($text,$finalTitle);
3071 function fetchTemplate( $title ) {
3072 $rv = $this->fetchTemplateAndTitle($title);
3077 * Static function to get a template
3078 * Can be overridden via ParserOptions::setTemplateCallback().
3080 static function statelessFetchTemplate( $title ) {
3081 $text = $skip = false;
3082 $finalTitle = $title;
3085 // Loop to fetch the article, with up to 1 redirect
3086 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3087 # Give extensions a chance to select the revision instead
3088 $id = false; // Assume current
3089 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3095 'page_id' => $title->getArticleID(),
3099 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3100 $rev_id = $rev ?
$rev->getId() : 0;
3101 // If there is no current revision, there is no page
3102 if( $id === false && !$rev ) {
3103 $linkCache = LinkCache
::singleton();
3104 $linkCache->addBadLinkObj( $title );
3109 'page_id' => $title->getArticleID(),
3110 'rev_id' => $rev_id );
3113 $text = $rev->getText();
3114 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3116 $message = $wgLang->lcfirst( $title->getText() );
3117 $text = wfMsgForContentNoTrans( $message );
3118 if( wfEmptyMsg( $message, $text ) ) {
3125 if ( $text === false ) {
3129 $finalTitle = $title;
3130 $title = Title
::newFromRedirect( $text );
3134 'finalTitle' => $finalTitle,
3139 * Transclude an interwiki link.
3141 function interwikiTransclude( $title, $action ) {
3142 global $wgEnableScaryTranscluding;
3144 if (!$wgEnableScaryTranscluding)
3145 return wfMsg('scarytranscludedisabled');
3147 $url = $title->getFullUrl( "action=$action" );
3149 if (strlen($url) > 255)
3150 return wfMsg('scarytranscludetoolong');
3151 return $this->fetchScaryTemplateMaybeFromCache($url);
3154 function fetchScaryTemplateMaybeFromCache($url) {
3155 global $wgTranscludeCacheExpiry;
3156 $dbr = wfGetDB(DB_SLAVE
);
3157 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3158 array('tc_url' => $url));
3160 $time = $obj->tc_time
;
3161 $text = $obj->tc_contents
;
3162 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3167 $text = Http
::get($url);
3169 return wfMsg('scarytranscludefailed', $url);
3171 $dbw = wfGetDB(DB_MASTER
);
3172 $dbw->replace('transcache', array('tc_url'), array(
3174 'tc_time' => time(),
3175 'tc_contents' => $text));
3181 * Triple brace replacement -- used for template arguments
3184 function argSubstitution( $piece, $frame ) {
3185 wfProfileIn( __METHOD__
);
3188 $parts = $piece['parts'];
3189 $nameWithSpaces = $frame->expand( $piece['title'] );
3190 $argName = trim( $nameWithSpaces );
3192 $text = $frame->getArgument( $argName );
3193 if ( $text === false && $parts->getLength() > 0
3197 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3200 # No match in frame, use the supplied default
3201 $object = $parts->item( 0 )->getChildren();
3203 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3204 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3205 $this->limitationWarn( 'post-expand-template-argument' );
3208 if ( $text === false && $object === false ) {
3210 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3212 if ( $error !== false ) {
3215 if ( $object !== false ) {
3216 $ret = array( 'object' => $object );
3218 $ret = array( 'text' => $text );
3221 wfProfileOut( __METHOD__
);
3226 * Return the text to be used for a given extension tag.
3227 * This is the ghost of strip().
3229 * @param array $params Associative array of parameters:
3230 * name PPNode for the tag name
3231 * attr PPNode for unparsed text where tag attributes are thought to be
3232 * attributes Optional associative array of parsed attributes
3233 * inner Contents of extension element
3234 * noClose Original text did not have a close tag
3235 * @param PPFrame $frame
3237 function extensionSubstitution( $params, $frame ) {
3238 global $wgRawHtml, $wgContLang;
3240 $name = $frame->expand( $params['name'] );
3241 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3242 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3244 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3246 if ( $this->ot
['html'] ) {
3247 $name = strtolower( $name );
3249 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3250 if ( isset( $params['attributes'] ) ) {
3251 $attributes = $attributes +
$params['attributes'];
3259 throw new MWException( '<html> extension tag encountered unexpectedly' );
3262 $output = Xml
::escapeTagsOnly( $content );
3265 $output = $wgContLang->armourMath(
3266 MathRenderer
::renderMath( $content, $attributes ) );
3269 $output = $this->renderImageGallery( $content, $attributes );
3272 if( isset( $this->mTagHooks
[$name] ) ) {
3273 # Workaround for PHP bug 35229 and similar
3274 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3275 throw new MWException( "Tag hook for $name is not callable\n" );
3277 $output = call_user_func_array( $this->mTagHooks
[$name],
3278 array( $content, $attributes, $this ) );
3280 $output = '<span class="error">Invalid tag extension name: ' .
3281 htmlspecialchars( $name ) . '</span>';
3285 if ( is_null( $attrText ) ) {
3288 if ( isset( $params['attributes'] ) ) {
3289 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3290 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3291 htmlspecialchars( $attrValue ) . '"';
3294 if ( $content === null ) {
3295 $output = "<$name$attrText/>";
3297 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3298 $output = "<$name$attrText>$content$close";
3302 if ( $name == 'html' ||
$name == 'nowiki' ) {
3303 $this->mStripState
->nowiki
->setPair( $marker, $output );
3305 $this->mStripState
->general
->setPair( $marker, $output );
3311 * Increment an include size counter
3313 * @param string $type The type of expansion
3314 * @param integer $size The size of the text
3315 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3317 function incrementIncludeSize( $type, $size ) {
3318 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3321 $this->mIncludeSizes
[$type] +
= $size;
3327 * Increment the expensive function count
3329 * @return boolean False if the limit has been exceeded
3331 function incrementExpensiveFunctionCount() {
3332 global $wgExpensiveParserFunctionLimit;
3333 $this->mExpensiveFunctionCount++
;
3334 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3341 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3342 * Fills $this->mDoubleUnderscores, returns the modified text
3344 function doDoubleUnderscore( $text ) {
3345 // The position of __TOC__ needs to be recorded
3346 $mw = MagicWord
::get( 'toc' );
3347 if( $mw->match( $text ) ) {
3348 $this->mShowToc
= true;
3349 $this->mForceTocPosition
= true;
3351 // Set a placeholder. At the end we'll fill it in with the TOC.
3352 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3354 // Only keep the first one.
3355 $text = $mw->replace( '', $text );
3358 // Now match and remove the rest of them
3359 $mwa = MagicWord
::getDoubleUnderscoreArray();
3360 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3362 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3363 $this->mOutput
->mNoGallery
= true;
3365 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3366 $this->mShowToc
= false;
3368 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3369 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3371 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3372 if ( $containerCategory ) {
3373 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3375 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3382 * This function accomplishes several tasks:
3383 * 1) Auto-number headings if that option is enabled
3384 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3385 * 3) Add a Table of contents on the top for users who have enabled the option
3386 * 4) Auto-anchor headings
3388 * It loops through all headlines, collects the necessary data, then splits up the
3389 * string and re-inserts the newly formatted headlines.
3391 * @param string $text
3392 * @param boolean $isMain
3395 function formatHeadings( $text, $isMain=true ) {
3396 global $wgMaxTocLevel, $wgContLang;
3398 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3399 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3402 $showEditLink = $this->mOptions
->getEditSection();
3405 # Inhibit editsection links if requested in the page
3406 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3410 # Get all headlines for numbering them and adding funky stuff like [edit]
3411 # links - this is for later, but we need the number of headlines right now
3413 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3415 # if there are fewer than 4 headlines in the article, do not show TOC
3416 # unless it's been explicitly enabled.
3417 $enoughToc = $this->mShowToc
&&
3418 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3420 # Allow user to stipulate that a page should have a "new section"
3421 # link added via __NEWSECTIONLINK__
3422 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3423 $this->mOutput
->setNewSection( true );
3426 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3427 # override above conditions and always show TOC above first header
3428 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3429 $this->mShowToc
= true;
3433 # We need this to perform operations on the HTML
3434 $sk = $this->mOptions
->getSkin();
3440 # Ugh .. the TOC should have neat indentation levels which can be
3441 # passed to the skin functions. These are determined here
3445 $sublevelCount = array();
3446 $levelCount = array();
3452 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3453 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3456 foreach( $matches[3] as $headline ) {
3457 $isTemplate = false;
3459 $sectionIndex = false;
3461 $markerMatches = array();
3462 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3463 $serial = $markerMatches[1];
3464 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3465 $isTemplate = ($titleText != $baseTitleText);
3466 $headline = preg_replace("/^$markerRegex/", "", $headline);
3470 $prevlevel = $level;
3471 $prevtoclevel = $toclevel;
3473 $level = $matches[1][$headlineCount];
3475 if( $doNumberHeadings ||
$enoughToc ) {
3477 if ( $level > $prevlevel ) {
3478 # Increase TOC level
3480 $sublevelCount[$toclevel] = 0;
3481 if( $toclevel<$wgMaxTocLevel ) {
3482 $prevtoclevel = $toclevel;
3483 $toc .= $sk->tocIndent();
3487 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3488 # Decrease TOC level, find level to jump to
3490 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3491 # Can only go down to level 1
3494 for ($i = $toclevel; $i > 0; $i--) {
3495 if ( $levelCount[$i] == $level ) {
3496 # Found last matching level
3500 elseif ( $levelCount[$i] < $level ) {
3501 # Found first matching level below current level
3507 if( $toclevel<$wgMaxTocLevel ) {
3508 if($prevtoclevel < $wgMaxTocLevel) {
3509 # Unindent only if the previous toc level was shown :p
3510 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3511 $prevtoclevel = $toclevel;
3513 $toc .= $sk->tocLineEnd();
3518 # No change in level, end TOC line
3519 if( $toclevel<$wgMaxTocLevel ) {
3520 $toc .= $sk->tocLineEnd();
3524 $levelCount[$toclevel] = $level;
3526 # count number of headlines for each level
3527 @$sublevelCount[$toclevel]++
;
3529 for( $i = 1; $i <= $toclevel; $i++
) {
3530 if( !empty( $sublevelCount[$i] ) ) {
3534 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3540 # The safe header is a version of the header text safe to use for links
3541 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3542 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3544 # Remove link placeholders by the link text.
3545 # <!--LINK number-->
3547 # link text with suffix
3548 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3549 "\$this->mLinkHolders['texts'][\$1]",
3551 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3552 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3555 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3556 $tocline = preg_replace(
3557 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3561 $tocline = trim( $tocline );
3563 # For the anchor, strip out HTML-y stuff period
3564 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3565 $safeHeadline = trim( $safeHeadline );
3567 # Save headline for section edit hint before it's escaped
3568 $headlineHint = $safeHeadline;
3569 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3570 # HTML names must be case-insensitively unique (bug 10721)
3571 $arrayKey = strtolower( $safeHeadline );
3573 # XXX : Is $refers[$headlineCount] ever accessed, actually ?
3574 $refers[$headlineCount] = $safeHeadline;
3576 # count how many in assoc. array so we can track dupes in anchors
3577 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3578 $refcount[$headlineCount] = $refers[$arrayKey];
3580 # Don't number the heading if it is the only one (looks silly)
3581 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3582 # the two are different if the line contains a link
3583 $headline=$numbering . ' ' . $headline;
3586 # Create the anchor for linking from the TOC to the section
3587 $anchor = $safeHeadline;
3588 if($refcount[$headlineCount] > 1 ) {
3589 $anchor .= '_' . $refcount[$headlineCount];
3591 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3592 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3593 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3595 # give headline the correct <h#> tag
3596 if( $showEditLink && $sectionIndex !== false ) {
3598 # Put a T flag in the section identifier, to indicate to extractSections()
3599 # that sections inside <includeonly> should be counted.
3600 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3602 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3607 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3612 $this->mOutput
->setSections( $tocraw );
3614 # Never ever show TOC if no headers
3615 if( $numVisible < 1 ) {
3620 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3621 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3623 $toc = $sk->tocList( $toc );
3626 # split up and insert constructed headlines
3628 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3631 foreach( $blocks as $block ) {
3632 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3633 # This is the [edit] link that appears for the top block of text when
3634 # section editing is enabled
3636 # Disabled because it broke block formatting
3637 # For example, a bullet point in the top line
3638 # $full .= $sk->editSectionLink(0);
3641 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3642 # Top anchor now in skin
3646 if( !empty( $head[$i] ) ) {
3651 if( $this->mForceTocPosition
) {
3652 return str_replace( '<!--MWTOC-->', $toc, $full );
3659 * Transform wiki markup when saving a page by doing \r\n -> \n
3660 * conversion, substitting signatures, {{subst:}} templates, etc.
3662 * @param string $text the text to transform
3663 * @param Title &$title the Title object for the current article
3664 * @param User &$user the User object describing the current user
3665 * @param ParserOptions $options parsing options
3666 * @param bool $clearState whether to clear the parser state first
3667 * @return string the altered wiki markup
3670 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3671 $this->mOptions
= $options;
3672 $this->setTitle( $title );
3673 $this->setOutputType( self
::OT_WIKI
);
3675 if ( $clearState ) {
3676 $this->clearState();
3682 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3683 $text = $this->pstPass2( $text, $user );
3684 $text = $this->mStripState
->unstripBoth( $text );
3689 * Pre-save transform helper function
3692 function pstPass2( $text, $user ) {
3693 global $wgContLang, $wgLocaltimezone;
3695 /* Note: This is the timestamp saved as hardcoded wikitext to
3696 * the database, we use $wgContLang here in order to give
3697 * everyone the same signature and use the default one rather
3698 * than the one selected in each user's preferences.
3700 * (see also bug 12815)
3702 $ts = $this->mOptions
->getTimestamp();
3704 if ( isset( $wgLocaltimezone ) ) {
3705 $unixts = wfTimestamp( TS_UNIX
, $ts );
3706 $oldtz = getenv( 'TZ' );
3707 putenv( 'TZ='.$wgLocaltimezone );
3708 $ts = date( 'YmdHis', $unixts );
3709 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3710 putenv( 'TZ='.$oldtz );
3712 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3714 # Variable replacement
3715 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3716 $text = $this->replaceVariables( $text );
3719 $sigText = $this->getUserSig( $user );
3720 $text = strtr( $text, array(
3722 '~~~~' => "$sigText $d",
3726 # Context links: [[|name]] and [[name (context)|]]
3728 global $wgLegalTitleChars;
3729 $tc = "[$wgLegalTitleChars]";
3730 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3732 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3733 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3734 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3736 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3737 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3738 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3740 $t = $this->mTitle
->getText();
3742 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3743 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3744 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3745 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3747 # if there's no context, don't bother duplicating the title
3748 $text = preg_replace( $p2, '[[\\1]]', $text );
3751 # Trim trailing whitespace
3752 $text = rtrim( $text );
3758 * Fetch the user's signature text, if any, and normalize to
3759 * validated, ready-to-insert wikitext.
3765 function getUserSig( &$user ) {
3766 global $wgMaxSigChars;
3768 $username = $user->getName();
3769 $nickname = $user->getOption( 'nickname' );
3770 $nickname = $nickname === '' ?
$username : $nickname;
3772 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3773 $nickname = $username;
3774 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3775 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3776 # Sig. might contain markup; validate this
3777 if( $this->validateSig( $nickname ) !== false ) {
3778 # Validated; clean up (if needed) and return it
3779 return $this->cleanSig( $nickname, true );
3781 # Failed to validate; fall back to the default
3782 $nickname = $username;
3783 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3787 // Make sure nickname doesnt get a sig in a sig
3788 $nickname = $this->cleanSigInSig( $nickname );
3790 # If we're still here, make it a link to the user page
3791 $userText = wfEscapeWikiText( $username );
3792 $nickText = wfEscapeWikiText( $nickname );
3793 if ( $user->isAnon() ) {
3794 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3796 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3801 * Check that the user's signature contains no bad XML
3803 * @param string $text
3804 * @return mixed An expanded string, or false if invalid.
3806 function validateSig( $text ) {
3807 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3811 * Clean up signature text
3813 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3814 * 2) Substitute all transclusions
3816 * @param string $text
3817 * @param $parsing Whether we're cleaning (preferences save) or parsing
3818 * @return string Signature text
3820 function cleanSig( $text, $parsing = false ) {
3823 $this->clearState();
3824 $this->setTitle( $wgTitle );
3825 $this->mOptions
= new ParserOptions
;
3826 $this->setOutputType
= self
::OT_PREPROCESS
;
3829 # FIXME: regex doesn't respect extension tags or nowiki
3830 # => Move this logic to braceSubstitution()
3831 $substWord = MagicWord
::get( 'subst' );
3832 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3833 $substText = '{{' . $substWord->getSynonym( 0 );
3835 $text = preg_replace( $substRegex, $substText, $text );
3836 $text = $this->cleanSigInSig( $text );
3837 $dom = $this->preprocessToDom( $text );
3838 $frame = $this->getPreprocessor()->newFrame();
3839 $text = $frame->expand( $dom );
3842 $text = $this->mStripState
->unstripBoth( $text );
3849 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3850 * @param string $text
3851 * @return string Signature text with /~{3,5}/ removed
3853 function cleanSigInSig( $text ) {
3854 $text = preg_replace( '/~{3,5}/', '', $text );
3859 * Set up some variables which are usually set up in parse()
3860 * so that an external function can call some class members with confidence
3863 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3864 $this->setTitle( $title );
3865 $this->mOptions
= $options;
3866 $this->setOutputType( $outputType );
3867 if ( $clearState ) {
3868 $this->clearState();
3873 * Wrapper for preprocess()
3875 * @param string $text the text to preprocess
3876 * @param ParserOptions $options options
3880 function transformMsg( $text, $options ) {
3882 static $executing = false;
3884 $fname = "Parser::transformMsg";
3886 # Guard against infinite recursion
3892 wfProfileIn($fname);
3893 $text = $this->preprocess( $text, $wgTitle, $options );
3896 wfProfileOut($fname);
3901 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3902 * The callback should have the following form:
3903 * function myParserHook( $text, $params, &$parser ) { ... }
3905 * Transform and return $text. Use $parser for any required context, e.g. use
3906 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3910 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3911 * @param mixed $callback The callback function (and object) to use for the tag
3913 * @return The old value of the mTagHooks array associated with the hook
3915 function setHook( $tag, $callback ) {
3916 $tag = strtolower( $tag );
3917 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3918 $this->mTagHooks
[$tag] = $callback;
3919 if( !in_array( $tag, $this->mStripList
) ) {
3920 $this->mStripList
[] = $tag;
3926 function setTransparentTagHook( $tag, $callback ) {
3927 $tag = strtolower( $tag );
3928 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3929 $this->mTransparentTagHooks
[$tag] = $callback;
3935 * Remove all tag hooks
3937 function clearTagHooks() {
3938 $this->mTagHooks
= array();
3939 $this->mStripList
= $this->mDefaultStripList
;
3943 * Create a function, e.g. {{sum:1|2|3}}
3944 * The callback function should have the form:
3945 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3947 * The callback may either return the text result of the function, or an array with the text
3948 * in element 0, and a number of flags in the other elements. The names of the flags are
3949 * specified in the keys. Valid flags are:
3950 * found The text returned is valid, stop processing the template. This
3952 * nowiki Wiki markup in the return value should be escaped
3953 * isHTML The returned text is HTML, armour it against wikitext transformation
3957 * @param string $id The magic word ID
3958 * @param mixed $callback The callback function (and object) to use
3959 * @param integer $flags a combination of the following flags:
3960 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3962 * @return The old callback function for this name, if any
3964 function setFunctionHook( $id, $callback, $flags = 0 ) {
3965 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
3966 $this->mFunctionHooks
[$id] = array( $callback, $flags );
3968 # Add to function cache
3969 $mw = MagicWord
::get( $id );
3971 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3973 $synonyms = $mw->getSynonyms();
3974 $sensitive = intval( $mw->isCaseSensitive() );
3976 foreach ( $synonyms as $syn ) {
3978 if ( !$sensitive ) {
3979 $syn = strtolower( $syn );
3982 if ( !( $flags & SFH_NO_HASH
) ) {
3985 # Remove trailing colon
3986 if ( substr( $syn, -1, 1 ) == ':' ) {
3987 $syn = substr( $syn, 0, -1 );
3989 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3995 * Get all registered function hook identifiers
3999 function getFunctionHooks() {
4000 return array_keys( $this->mFunctionHooks
);
4004 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4005 * Placeholders created in Skin::makeLinkObj()
4006 * Returns an array of link CSS classes, indexed by PDBK.
4007 * $options is a bit field, RLH_FOR_UPDATE to select for update
4009 function replaceLinkHolders( &$text, $options = 0 ) {
4013 $fname = 'Parser::replaceLinkHolders';
4014 wfProfileIn( $fname );
4018 $linkcolour_ids = array();
4019 $sk = $this->mOptions
->getSkin();
4020 $linkCache = LinkCache
::singleton();
4022 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4023 wfProfileIn( $fname.'-check' );
4024 $dbr = wfGetDB( DB_SLAVE
);
4025 $page = $dbr->tableName( 'page' );
4026 $threshold = $wgUser->getOption('stubthreshold');
4029 asort( $this->mLinkHolders
['namespaces'] );
4034 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4036 $title = $this->mLinkHolders
['titles'][$key];
4038 # Skip invalid entries.
4039 # Result will be ugly, but prevents crash.
4040 if ( is_null( $title ) ) {
4043 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4045 # Check if it's a static known link, e.g. interwiki
4046 if ( $title->isAlwaysKnown() ) {
4047 $colours[$pdbk] = '';
4048 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4049 $colours[$pdbk] = '';
4050 $this->mOutput
->addLink( $title, $id );
4051 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4052 $colours[$pdbk] = 'new';
4053 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4054 $colours[$pdbk] = 'new';
4056 # Not in the link cache, add it to the query
4057 if ( !isset( $current ) ) {
4059 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4060 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4061 } elseif ( $current != $ns ) {
4063 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4068 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4073 if ( $options & RLH_FOR_UPDATE
) {
4074 $query .= ' FOR UPDATE';
4077 $res = $dbr->query( $query, $fname );
4079 # Fetch data and form into an associative array
4080 # non-existent = broken
4081 while ( $s = $dbr->fetchObject($res) ) {
4082 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4083 $pdbk = $title->getPrefixedDBkey();
4084 $linkCache->addGoodLinkObj( $s->page_id
, $title, $s->page_len
, $s->page_is_redirect
);
4085 $this->mOutput
->addLink( $title, $s->page_id
);
4086 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
4087 //add id to the extension todolist
4088 $linkcolour_ids[$s->page_id
] = $pdbk;
4090 //pass an array of page_ids to an extension
4091 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4093 wfProfileOut( $fname.'-check' );
4095 # Do a second query for different language variants of links and categories
4096 if($wgContLang->hasVariants()){
4097 $linkBatch = new LinkBatch();
4098 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4099 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4100 $varCategories = array(); // category replacements oldDBkey => newDBkey
4102 $categories = $this->mOutput
->getCategoryLinks();
4104 // Add variants of links to link batch
4105 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4106 $title = $this->mLinkHolders
['titles'][$key];
4107 if ( is_null( $title ) )
4110 $pdbk = $title->getPrefixedDBkey();
4111 $titleText = $title->getText();
4113 // generate all variants of the link title text
4114 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4116 // if link was not found (in first query), add all variants to query
4117 if ( !isset($colours[$pdbk]) ){
4118 foreach($allTextVariants as $textVariant){
4119 if($textVariant != $titleText){
4120 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4121 if(is_null($variantTitle)) continue;
4122 $linkBatch->addObj( $variantTitle );
4123 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4129 // process categories, check if a category exists in some variant
4130 foreach( $categories as $category ){
4131 $variants = $wgContLang->convertLinkToAllVariants($category);
4132 foreach($variants as $variant){
4133 if($variant != $category){
4134 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4135 if(is_null($variantTitle)) continue;
4136 $linkBatch->addObj( $variantTitle );
4137 $categoryMap[$variant] = $category;
4143 if(!$linkBatch->isEmpty()){
4145 $titleClause = $linkBatch->constructSet('page', $dbr);
4147 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4149 $variantQuery .= " FROM $page WHERE $titleClause";
4150 if ( $options & RLH_FOR_UPDATE
) {
4151 $variantQuery .= ' FOR UPDATE';
4154 $varRes = $dbr->query( $variantQuery, $fname );
4156 // for each found variants, figure out link holders and replace
4157 while ( $s = $dbr->fetchObject($varRes) ) {
4159 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4160 $varPdbk = $variantTitle->getPrefixedDBkey();
4161 $vardbk = $variantTitle->getDBkey();
4163 $holderKeys = array();
4164 if(isset($variantMap[$varPdbk])){
4165 $holderKeys = $variantMap[$varPdbk];
4166 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle, $s->page_len
, $s->page_is_redirect
);
4167 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4170 // loop over link holders
4171 foreach($holderKeys as $key){
4172 $title = $this->mLinkHolders
['titles'][$key];
4173 if ( is_null( $title ) ) continue;
4175 $pdbk = $title->getPrefixedDBkey();
4177 if(!isset($colours[$pdbk])){
4178 // found link in some of the variants, replace the link holder data
4179 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4180 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4182 // set pdbk and colour
4183 $pdbks[$key] = $varPdbk;
4184 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
4185 $linkcolour_ids[$s->page_id
] = $pdbk;
4187 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4190 // check if the object is a variant of a category
4191 if(isset($categoryMap[$vardbk])){
4192 $oldkey = $categoryMap[$vardbk];
4193 if($oldkey != $vardbk)
4194 $varCategories[$oldkey]=$vardbk;
4198 // rebuild the categories in original order (if there are replacements)
4199 if(count($varCategories)>0){
4201 $originalCats = $this->mOutput
->getCategories();
4202 foreach($originalCats as $cat => $sortkey){
4203 // make the replacement
4204 if( array_key_exists($cat,$varCategories) )
4205 $newCats[$varCategories[$cat]] = $sortkey;
4206 else $newCats[$cat] = $sortkey;
4208 $this->mOutput
->setCategoryLinks($newCats);
4213 # Construct search and replace arrays
4214 wfProfileIn( $fname.'-construct' );
4215 $replacePairs = array();
4216 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4217 $pdbk = $pdbks[$key];
4218 $searchkey = "<!--LINK $key-->";
4219 $title = $this->mLinkHolders
['titles'][$key];
4220 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] == 'new' ) {
4221 $linkCache->addBadLinkObj( $title );
4222 $colours[$pdbk] = 'new';
4223 $this->mOutput
->addLink( $title, 0 );
4224 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4225 $this->mLinkHolders
['texts'][$key],
4226 $this->mLinkHolders
['queries'][$key] );
4228 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4229 $this->mLinkHolders
['texts'][$key],
4230 $this->mLinkHolders
['queries'][$key] );
4233 $replacer = new HashtableReplacer( $replacePairs, 1 );
4234 wfProfileOut( $fname.'-construct' );
4237 wfProfileIn( $fname.'-replace' );
4238 $text = preg_replace_callback(
4239 '/(<!--LINK .*?-->)/',
4243 wfProfileOut( $fname.'-replace' );
4246 # Now process interwiki link holders
4247 # This is quite a bit simpler than internal links
4248 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4249 wfProfileIn( $fname.'-interwiki' );
4250 # Make interwiki link HTML
4251 $replacePairs = array();
4252 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4253 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4254 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4256 $replacer = new HashtableReplacer( $replacePairs, 1 );
4258 $text = preg_replace_callback(
4259 '/<!--IWLINK (.*?)-->/',
4262 wfProfileOut( $fname.'-interwiki' );
4265 wfProfileOut( $fname );
4270 * Replace <!--LINK--> link placeholders with plain text of links
4271 * (not HTML-formatted).
4272 * @param string $text
4275 function replaceLinkHoldersText( $text ) {
4276 $fname = 'Parser::replaceLinkHoldersText';
4277 wfProfileIn( $fname );
4279 $text = preg_replace_callback(
4280 '/<!--(LINK|IWLINK) (.*?)-->/',
4281 array( &$this, 'replaceLinkHoldersTextCallback' ),
4284 wfProfileOut( $fname );
4289 * @param array $matches
4293 function replaceLinkHoldersTextCallback( $matches ) {
4294 $type = $matches[1];
4296 if( $type == 'LINK' ) {
4297 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4298 return $this->mLinkHolders
['texts'][$key];
4300 } elseif( $type == 'IWLINK' ) {
4301 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4302 return $this->mInterwikiLinkHolders
['texts'][$key];
4309 * Tag hook handler for 'pre'.
4311 function renderPreTag( $text, $attribs ) {
4312 // Backwards-compatibility hack
4313 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4315 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4316 return wfOpenElement( 'pre', $attribs ) .
4317 Xml
::escapeTagsOnly( $content ) .
4322 * Renders an image gallery from a text with one line per image.
4323 * text labels may be given by using |-style alternative text. E.g.
4324 * Image:one.jpg|The number "1"
4325 * Image:tree.jpg|A tree
4326 * given as text will return the HTML of a gallery with two images,
4327 * labeled 'The number "1"' and
4330 function renderImageGallery( $text, $params ) {
4331 $ig = new ImageGallery();
4332 $ig->setContextTitle( $this->mTitle
);
4333 $ig->setShowBytes( false );
4334 $ig->setShowFilename( false );
4335 $ig->setParser( $this );
4336 $ig->setHideBadImages();
4337 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4338 $ig->useSkin( $this->mOptions
->getSkin() );
4339 $ig->mRevisionId
= $this->mRevisionId
;
4341 if( isset( $params['caption'] ) ) {
4342 $caption = $params['caption'];
4343 $caption = htmlspecialchars( $caption );
4344 $caption = $this->replaceInternalLinks( $caption );
4345 $ig->setCaptionHtml( $caption );
4347 if( isset( $params['perrow'] ) ) {
4348 $ig->setPerRow( $params['perrow'] );
4350 if( isset( $params['widths'] ) ) {
4351 $ig->setWidths( $params['widths'] );
4353 if( isset( $params['heights'] ) ) {
4354 $ig->setHeights( $params['heights'] );
4357 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4359 $lines = explode( "\n", $text );
4360 foreach ( $lines as $line ) {
4361 # match lines like these:
4362 # Image:someimage.jpg|This is some image
4364 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4366 if ( count( $matches ) == 0 ) {
4369 $tp = Title
::newFromText( $matches[1] );
4371 if( is_null( $nt ) ) {
4372 # Bogus title. Ignore these so we don't bomb out later.
4375 if ( isset( $matches[3] ) ) {
4376 $label = $matches[3];
4381 $html = $this->recursiveTagParse( trim( $label ) );
4383 $ig->add( $nt, $html );
4385 # Only add real images (bug #5586)
4386 if ( $nt->getNamespace() == NS_IMAGE
) {
4387 $this->mOutput
->addImage( $nt->getDBkey() );
4390 return $ig->toHTML();
4393 function getImageParams( $handler ) {
4395 $handlerClass = get_class( $handler );
4399 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4400 // Initialise static lists
4401 static $internalParamNames = array(
4402 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4403 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4404 'bottom', 'text-bottom' ),
4405 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4406 'upright', 'border' ),
4408 static $internalParamMap;
4409 if ( !$internalParamMap ) {
4410 $internalParamMap = array();
4411 foreach ( $internalParamNames as $type => $names ) {
4412 foreach ( $names as $name ) {
4413 $magicName = str_replace( '-', '_', "img_$name" );
4414 $internalParamMap[$magicName] = array( $type, $name );
4419 // Add handler params
4420 $paramMap = $internalParamMap;
4422 $handlerParamMap = $handler->getParamMap();
4423 foreach ( $handlerParamMap as $magic => $paramName ) {
4424 $paramMap[$magic] = array( 'handler', $paramName );
4427 $this->mImageParams
[$handlerClass] = $paramMap;
4428 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4430 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4434 * Parse image options text and use it to make an image
4436 function makeImage( $title, $options ) {
4437 # Check if the options text is of the form "options|alt text"
4439 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4440 # * left no resizing, just left align. label is used for alt= only
4441 # * right same, but right aligned
4442 # * none same, but not aligned
4443 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4444 # * center center the image
4445 # * framed Keep original image size, no magnify-button.
4446 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4447 # * upright reduce width for upright images, rounded to full __0 px
4448 # * border draw a 1px border around the image
4449 # vertical-align values (no % or length right now):
4459 $parts = array_map( 'trim', explode( '|', $options) );
4460 $sk = $this->mOptions
->getSkin();
4462 # Give extensions a chance to select the file revision for us
4463 $skip = $time = $descQuery = false;
4464 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4467 return $sk->makeLinkObj( $title );
4471 $file = wfFindFile( $title, $time );
4472 $handler = $file ?
$file->getHandler() : false;
4474 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4476 # Process the input parameters
4478 $params = array( 'frame' => array(), 'handler' => array(),
4479 'horizAlign' => array(), 'vertAlign' => array() );
4480 foreach( $parts as $part ) {
4481 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4483 if( isset( $paramMap[$magicName] ) ) {
4484 list( $type, $paramName ) = $paramMap[$magicName];
4486 // Special case; width and height come in one variable together
4487 if( $type == 'handler' && $paramName == 'width' ) {
4489 # (bug 13500) In both cases (width/height and width only),
4490 # permit trailing "px" for backward compatibility.
4491 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4492 $width = intval( $m[1] );
4493 $height = intval( $m[2] );
4494 if ( $handler->validateParam( 'width', $width ) ) {
4495 $params[$type]['width'] = $width;
4498 if ( $handler->validateParam( 'height', $height ) ) {
4499 $params[$type]['height'] = $height;
4502 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4503 $width = intval( $value );
4504 if ( $handler->validateParam( 'width', $width ) ) {
4505 $params[$type]['width'] = $width;
4508 } // else no validation -- bug 13436
4510 if ( $type == 'handler' ) {
4511 # Validate handler parameter
4512 $validated = $handler->validateParam( $paramName, $value );
4514 # Validate internal parameters
4515 switch( $paramName ) {
4517 /// @fixme - possibly check validity here?
4518 /// downstream behavior seems odd with missing manual thumbs.
4522 // Most other things appear to be empty or numeric...
4523 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4528 $params[$type][$paramName] = $value;
4532 if ( !$validated ) {
4537 # Process alignment parameters
4538 if ( $params['horizAlign'] ) {
4539 $params['frame']['align'] = key( $params['horizAlign'] );
4541 if ( $params['vertAlign'] ) {
4542 $params['frame']['valign'] = key( $params['vertAlign'] );
4545 # Strip bad stuff out of the alt text
4546 $alt = $this->replaceLinkHoldersText( $caption );
4548 # make sure there are no placeholders in thumbnail attributes
4549 # that are later expanded to html- so expand them now and
4551 $alt = $this->mStripState
->unstripBoth( $alt );
4552 $alt = Sanitizer
::stripAllTags( $alt );
4554 $params['frame']['alt'] = $alt;
4555 $params['frame']['caption'] = $caption;
4557 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4559 # Linker does the rest
4560 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4562 # Give the handler a chance to modify the parser object
4564 $handler->parserTransformHook( $this, $file );
4571 * Set a flag in the output object indicating that the content is dynamic and
4572 * shouldn't be cached.
4574 function disableCache() {
4575 wfDebug( "Parser output marked as uncacheable.\n" );
4576 $this->mOutput
->mCacheTime
= -1;
4580 * Callback from the Sanitizer for expanding items found in HTML attribute
4581 * values, so they can be safely tested and escaped.
4582 * @param string $text
4583 * @param PPFrame $frame
4587 function attributeStripCallback( &$text, $frame = false ) {
4588 $text = $this->replaceVariables( $text, $frame );
4589 $text = $this->mStripState
->unstripBoth( $text );
4598 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4599 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4600 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4606 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4611 * Break wikitext input into sections, and either pull or replace
4612 * some particular section's text.
4614 * External callers should use the getSection and replaceSection methods.
4616 * @param string $text Page wikitext
4617 * @param string $section A section identifier string of the form:
4618 * <flag1> - <flag2> - ... - <section number>
4620 * Currently the only recognised flag is "T", which means the target section number
4621 * was derived during a template inclusion parse, in other words this is a template
4622 * section edit link. If no flags are given, it was an ordinary section edit link.
4623 * This flag is required to avoid a section numbering mismatch when a section is
4624 * enclosed by <includeonly> (bug 6563).
4626 * The section number 0 pulls the text before the first heading; other numbers will
4627 * pull the given section along with its lower-level subsections. If the section is
4628 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4630 * @param string $mode One of "get" or "replace"
4631 * @param string $newText Replacement text for section data.
4632 * @return string for "get", the extracted section text.
4633 * for "replace", the whole page with the section replaced.
4635 private function extractSections( $text, $section, $mode, $newText='' ) {
4637 $this->clearState();
4638 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4639 $this->mOptions
= new ParserOptions
;
4640 $this->setOutputType( self
::OT_WIKI
);
4642 $frame = $this->getPreprocessor()->newFrame();
4644 // Process section extraction flags
4646 $sectionParts = explode( '-', $section );
4647 $sectionIndex = array_pop( $sectionParts );
4648 foreach ( $sectionParts as $part ) {
4649 if ( $part == 'T' ) {
4650 $flags |
= self
::PTD_FOR_INCLUSION
;
4653 // Preprocess the text
4654 $root = $this->preprocessToDom( $text, $flags );
4656 // <h> nodes indicate section breaks
4657 // They can only occur at the top level, so we can find them by iterating the root's children
4658 $node = $root->getFirstChild();
4660 // Find the target section
4661 if ( $sectionIndex == 0 ) {
4662 // Section zero doesn't nest, level=big
4663 $targetLevel = 1000;
4666 if ( $node->getName() == 'h' ) {
4667 $bits = $node->splitHeading();
4668 if ( $bits['i'] == $sectionIndex ) {
4669 $targetLevel = $bits['level'];
4673 if ( $mode == 'replace' ) {
4674 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4676 $node = $node->getNextSibling();
4682 if ( $mode == 'get' ) {
4689 // Find the end of the section, including nested sections
4691 if ( $node->getName() == 'h' ) {
4692 $bits = $node->splitHeading();
4693 $curLevel = $bits['level'];
4694 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4698 if ( $mode == 'get' ) {
4699 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4701 $node = $node->getNextSibling();
4704 // Write out the remainder (in replace mode only)
4705 if ( $mode == 'replace' ) {
4706 // Output the replacement text
4707 // Add two newlines on -- trailing whitespace in $newText is conventionally
4708 // stripped by the editor, so we need both newlines to restore the paragraph gap
4709 $outText .= $newText . "\n\n";
4711 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4712 $node = $node->getNextSibling();
4716 if ( is_string( $outText ) ) {
4717 // Re-insert stripped tags
4718 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4725 * This function returns the text of a section, specified by a number ($section).
4726 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4727 * the first section before any such heading (section 0).
4729 * If a section contains subsections, these are also returned.
4731 * @param string $text text to look in
4732 * @param string $section section identifier
4733 * @param string $deftext default to return if section is not found
4734 * @return string text of the requested section
4736 public function getSection( $text, $section, $deftext='' ) {
4737 return $this->extractSections( $text, $section, "get", $deftext );
4740 public function replaceSection( $oldtext, $section, $text ) {
4741 return $this->extractSections( $oldtext, $section, "replace", $text );
4745 * Get the timestamp associated with the current revision, adjusted for
4746 * the default server-local timestamp
4748 function getRevisionTimestamp() {
4749 if ( is_null( $this->mRevisionTimestamp
) ) {
4750 wfProfileIn( __METHOD__
);
4752 $dbr = wfGetDB( DB_SLAVE
);
4753 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4754 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4756 // Normalize timestamp to internal MW format for timezone processing.
4757 // This has the added side-effect of replacing a null value with
4758 // the current time, which gives us more sensible behavior for
4760 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4762 // The cryptic '' timezone parameter tells to use the site-default
4763 // timezone offset instead of the user settings.
4765 // Since this value will be saved into the parser cache, served
4766 // to other users, and potentially even used inside links and such,
4767 // it needs to be consistent for all visitors.
4768 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4770 wfProfileOut( __METHOD__
);
4772 return $this->mRevisionTimestamp
;
4776 * Mutator for $mDefaultSort
4778 * @param $sort New value
4780 public function setDefaultSort( $sort ) {
4781 $this->mDefaultSort
= $sort;
4785 * Accessor for $mDefaultSort
4786 * Will use the title/prefixed title if none is set
4790 public function getDefaultSort() {
4791 if( $this->mDefaultSort
!== false ) {
4792 return $this->mDefaultSort
;
4794 return $this->mTitle
->getNamespace() == NS_CATEGORY
4795 ?
$this->mTitle
->getText()
4796 : $this->mTitle
->getPrefixedText();
4801 * Try to guess the section anchor name based on a wikitext fragment
4802 * presumably extracted from a heading, for example "Header" from
4805 public function guessSectionNameFromWikiText( $text ) {
4806 # Strip out wikitext links(they break the anchor)
4807 $text = $this->stripSectionName( $text );
4808 $headline = Sanitizer
::decodeCharReferences( $text );
4810 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4811 $headline = trim( $headline );
4812 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4813 $replacearray = array(
4818 array_keys( $replacearray ),
4819 array_values( $replacearray ),
4824 * Strips a text string of wikitext for use in a section anchor
4826 * Accepts a text string and then removes all wikitext from the
4827 * string and leaves only the resultant text (i.e. the result of
4828 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4829 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4830 * to create valid section anchors by mimicing the output of the
4831 * parser when headings are parsed.
4833 * @param $text string Text string to be stripped of wikitext
4834 * for use in a Section anchor
4835 * @return Filtered text string
4837 public function stripSectionName( $text ) {
4838 # Strip internal link markup
4839 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4840 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4842 # Strip external link markup (FIXME: Not Tolerant to blank link text
4843 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4844 # on how many empty links there are on the page - need to figure that out.
4845 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4847 # Parse wikitext quotes (italics & bold)
4848 $text = $this->doQuotes($text);
4851 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4855 function srvus( $text ) {
4856 return $this->testSrvus( $text, $this->mOutputType
);
4860 * strip/replaceVariables/unstrip for preprocessor regression testing
4862 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4863 $this->clearState();
4864 if ( ! ( $title instanceof Title
) ) {
4865 $title = Title
::newFromText( $title );
4867 $this->mTitle
= $title;
4868 $this->mOptions
= $options;
4869 $this->setOutputType( $outputType );
4870 $text = $this->replaceVariables( $text );
4871 $text = $this->mStripState
->unstripBoth( $text );
4872 $text = Sanitizer
::removeHTMLtags( $text );
4876 function testPst( $text, $title, $options ) {
4878 if ( ! ( $title instanceof Title
) ) {
4879 $title = Title
::newFromText( $title );
4881 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4884 function testPreprocess( $text, $title, $options ) {
4885 if ( ! ( $title instanceof Title
) ) {
4886 $title = Title
::newFromText( $title );
4888 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4891 function markerSkipCallback( $s, $callback ) {
4894 while ( $i < strlen( $s ) ) {
4895 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4896 if ( $markerStart === false ) {
4897 $out .= call_user_func( $callback, substr( $s, $i ) );
4900 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4901 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4902 if ( $markerEnd === false ) {
4903 $out .= substr( $s, $markerStart );
4906 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4907 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4917 * @todo document, briefly.
4921 var $general, $nowiki;
4923 function __construct() {
4924 $this->general
= new ReplacementArray
;
4925 $this->nowiki
= new ReplacementArray
;
4928 function unstripGeneral( $text ) {
4929 wfProfileIn( __METHOD__
);
4932 $text = $this->general
->replace( $text );
4933 } while ( $text != $oldText );
4934 wfProfileOut( __METHOD__
);
4938 function unstripNoWiki( $text ) {
4939 wfProfileIn( __METHOD__
);
4942 $text = $this->nowiki
->replace( $text );
4943 } while ( $text != $oldText );
4944 wfProfileOut( __METHOD__
);
4948 function unstripBoth( $text ) {
4949 wfProfileIn( __METHOD__
);
4952 $text = $this->general
->replace( $text );
4953 $text = $this->nowiki
->replace( $text );
4954 } while ( $text != $oldText );
4955 wfProfileOut( __METHOD__
);
4961 * @todo document, briefly.
4964 class OnlyIncludeReplacer
{
4967 function replace( $matches ) {
4968 if ( substr( $matches[1], -1 ) == "\n" ) {
4969 $this->output
.= substr( $matches[1], 0, -1 );
4971 $this->output
.= $matches[1];