3 * File for Parser and related classes
9 * Update this version number when the ParserOutput format
10 * changes in an incompatible way, so the parser cache
11 * can automatically discard old data.
13 define( 'MW_PARSER_VERSION', '1.6.1' );
15 define( 'RLH_FOR_UPDATE', 1 );
17 # Allowed values for $mOutputType
18 define( 'OT_HTML', 1 );
19 define( 'OT_WIKI', 2 );
20 define( 'OT_MSG' , 3 );
21 define( 'OT_PREPROCESS', 4 );
23 # Flags for setFunctionHook
24 define( 'SFH_NO_HASH', 1 );
26 # string parameter for extractTags which will cause it
27 # to strip HTML comments in addition to regular
28 # <XML>-style tags. This should not be anything we
29 # may want to use in wikisyntax
30 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
32 # Constants needed for external link processing
33 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
34 # Everything except bracket, space, or control characters
35 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
36 # Including space, but excluding newlines
37 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
38 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
39 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
40 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
41 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
42 define( 'EXT_IMAGE_REGEX',
43 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
44 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
45 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
48 // State constants for the definition list colon extraction
49 define( 'MW_COLON_STATE_TEXT', 0 );
50 define( 'MW_COLON_STATE_TAG', 1 );
51 define( 'MW_COLON_STATE_TAGSTART', 2 );
52 define( 'MW_COLON_STATE_CLOSETAG', 3 );
53 define( 'MW_COLON_STATE_TAGSLASH', 4 );
54 define( 'MW_COLON_STATE_COMMENT', 5 );
55 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
56 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
59 * PHP Parser - Processes wiki markup (which uses a more user-friendly
60 * syntax, such as "[[link]]" for making links), and provides a one-way
61 * transformation of that wiki markup it into XHTML output / markup
62 * (which in turn the browser understands, and can display).
65 * There are four main entry points into the Parser class:
67 * produces HTML output
69 * produces altered wiki markup.
71 * performs brace substitution on MediaWiki messages
73 * removes HTML comments and expands templates
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
86 * * only within ParserOptions
93 const VERSION
= MW_PARSER_VERSION
;
98 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
100 # Cleared with clearState():
101 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
102 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
103 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mIncludeSizes, $mDefaultSort;
105 var $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
111 # These are variables reset at least once per parse regardless of $clearState
112 var $mOptions, // ParserOptions object
113 $mTitle, // Title context, used for self-link rendering and similar things
114 $mOutputType, // Output type, one of the OT_xxx constants
115 $ot, // Shortcut alias, see setOutputType()
116 $mRevisionId, // ID to display in {{REVISIONID}} tags
117 $mRevisionTimestamp, // The timestamp of the specified revision ID
118 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
128 $this->mTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
131 $this->mFirstCall
= true;
135 * Do various kinds of initialisation on the first call of the parser
137 function firstCallInit() {
138 if ( !$this->mFirstCall
) {
142 wfProfileIn( __METHOD__
);
143 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
145 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
147 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
170 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
171 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
172 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
174 if ( $wgAllowDisplayTitle ) {
175 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
177 if ( $wgAllowSlowParserFunctions ) {
178 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
181 $this->initialiseVariables();
182 $this->mFirstCall
= false;
183 wfProfileOut( __METHOD__
);
191 function clearState() {
192 wfProfileIn( __METHOD__
);
193 if ( $this->mFirstCall
) {
194 $this->firstCallInit();
196 $this->mOutput
= new ParserOutput
;
197 $this->mAutonumber
= 0;
198 $this->mLastSection
= '';
199 $this->mDTopen
= false;
200 $this->mIncludeCount
= array();
201 $this->mStripState
= new StripState
;
202 $this->mArgStack
= array();
203 $this->mInPre
= false;
204 $this->mInterwikiLinkHolders
= array(
208 $this->mLinkHolders
= array(
209 'namespaces' => array(),
211 'queries' => array(),
215 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
218 * Prefix for temporary replacement strings for the multipass parser.
219 * \x07 should never appear in input as it's disallowed in XML.
220 * Using it at the front also gives us a little extra robustness
221 * since it shouldn't match when butted up against identifier-like
224 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
226 # Clear these on every parse, bug 4549
227 $this->mTemplates
= array();
228 $this->mTemplatePath
= array();
230 $this->mShowToc
= true;
231 $this->mForceTocPosition
= false;
232 $this->mIncludeSizes
= array(
237 $this->mDefaultSort
= false;
239 wfRunHooks( 'ParserClearState', array( &$this ) );
240 wfProfileOut( __METHOD__
);
243 function setOutputType( $ot ) {
244 $this->mOutputType
= $ot;
247 'html' => $ot == OT_HTML
,
248 'wiki' => $ot == OT_WIKI
,
249 'msg' => $ot == OT_MSG
,
250 'pre' => $ot == OT_PREPROCESS
,
255 * Accessor for mUniqPrefix.
259 function uniqPrefix() {
260 return $this->mUniqPrefix
;
264 * Convert wikitext to HTML
265 * Do not call this function recursively.
267 * @param string $text Text we want to parse
268 * @param Title &$title A title object
269 * @param array $options
270 * @param boolean $linestart
271 * @param boolean $clearState
272 * @param int $revid number to pass in {{REVISIONID}}
273 * @return ParserOutput a ParserOutput
275 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
277 * First pass--just handle <nowiki> sections, pass the rest off
278 * to internalParse() which does all the real work.
281 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
282 $fname = 'Parser::parse-' . wfGetCaller();
283 wfProfileIn( __METHOD__
);
284 wfProfileIn( $fname );
290 $this->mOptions
= $options;
291 $this->mTitle
=& $title;
292 $oldRevisionId = $this->mRevisionId
;
293 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
294 if( $revid !== null ) {
295 $this->mRevisionId
= $revid;
296 $this->mRevisionTimestamp
= null;
298 $this->setOutputType( OT_HTML
);
299 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
300 $text = $this->strip( $text, $this->mStripState
);
301 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
302 $text = $this->internalParse( $text );
303 $text = $this->mStripState
->unstripGeneral( $text );
305 # Clean up special characters, only run once, next-to-last before doBlockLevels
307 # french spaces, last one Guillemet-left
308 # only if there is something before the space
309 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
310 # french spaces, Guillemet-right
311 '/(\\302\\253) /' => '\\1 ',
313 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
316 $text = $this->doBlockLevels( $text, $linestart );
318 $this->replaceLinkHolders( $text );
320 # the position of the parserConvert() call should not be changed. it
321 # assumes that the links are all replaced and the only thing left
322 # is the <nowiki> mark.
323 # Side-effects: this calls $this->mOutput->setTitleText()
324 $text = $wgContLang->parserConvert( $text, $this );
326 $text = $this->mStripState
->unstripNoWiki( $text );
328 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
330 $text = Sanitizer
::normalizeCharReferences( $text );
332 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
333 $text = Tidy
::RunOn($text);
335 # attempt to sanitize at least some nesting problems
336 # (bug #2702 and quite a few others)
338 # ''Something [http://www.cool.com cool''] -->
339 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
340 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
341 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
342 # fix up an anchor inside another anchor, only
343 # at least for a single single nested link (bug 3695)
344 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
345 '\\1\\2</a>\\3</a>\\1\\4</a>',
346 # fix div inside inline elements- doBlockLevels won't wrap a line which
347 # contains a div, so fix it up here; replace
348 # div with escaped text
349 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
350 '\\1\\3<div\\5>\\6</div>\\8\\9',
351 # remove empty italic or bold tag pairs, some
352 # introduced by rules above
353 '/<([bi])><\/\\1>/' => '',
356 $text = preg_replace(
357 array_keys( $tidyregs ),
358 array_values( $tidyregs ),
362 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
364 # Information on include size limits, for the benefit of users who try to skirt them
365 if ( max( $this->mIncludeSizes
) > 1000 ) {
366 $max = $this->mOptions
->getMaxIncludeSize();
368 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
369 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
370 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
371 "Maximum: $max bytes\n" .
374 $this->mOutput
->setText( $text );
375 $this->mRevisionId
= $oldRevisionId;
376 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
377 wfProfileOut( $fname );
378 wfProfileOut( __METHOD__
);
380 return $this->mOutput
;
384 * Recursive parser entry point that can be called from an extension tag
387 function recursiveTagParse( $text ) {
388 wfProfileIn( __METHOD__
);
389 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
390 $text = $this->strip( $text, $this->mStripState
);
391 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
392 $text = $this->internalParse( $text );
393 wfProfileOut( __METHOD__
);
398 * Expand templates and variables in the text, producing valid, static wikitext.
399 * Also removes comments.
401 function preprocess( $text, $title, $options ) {
402 wfProfileIn( __METHOD__
);
404 $this->setOutputType( OT_PREPROCESS
);
405 $this->mOptions
= $options;
406 $this->mTitle
= $title;
407 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
408 $text = $this->strip( $text, $this->mStripState
);
409 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
410 if ( $this->mOptions
->getRemoveComments() ) {
411 $text = Sanitizer
::removeHTMLcomments( $text );
413 $text = $this->replaceVariables( $text );
414 $text = $this->mStripState
->unstripBoth( $text );
415 wfProfileOut( __METHOD__
);
420 * Get a random string
425 function getRandomString() {
426 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
429 function &getTitle() { return $this->mTitle
; }
430 function getOptions() { return $this->mOptions
; }
432 function getFunctionLang() {
433 global $wgLang, $wgContLang;
434 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
438 * Replaces all occurrences of HTML-style comments and the given tags
439 * in the text with a random marker and returns teh next text. The output
440 * parameter $matches will be an associative array filled with data in
442 * 'UNIQ-xxxxx' => array(
445 * array( 'param' => 'x' ),
446 * '<element param="x">tag content</element>' ) )
448 * @param $elements list of element names. Comments are always extracted.
449 * @param $text Source text string.
450 * @param $uniq_prefix
455 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
460 $taglist = implode( '|', $elements );
461 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
463 while ( '' != $text ) {
464 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
466 if( count( $p ) < 5 ) {
469 if( count( $p ) > 5 ) {
483 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
484 $stripped .= $marker;
486 if ( $close === '/>' ) {
487 // Empty element tag, <tag />
492 if( $element == '!--' ) {
495 $end = "/(<\\/$element\\s*>)/i";
497 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
499 if( count( $q ) < 3 ) {
500 # No end tag -- let it run out to the end of the text.
509 $matches[$marker] = array( $element,
511 Sanitizer
::decodeTagAttributes( $attributes ),
512 "<$element$attributes$close$content$tail" );
518 * Strips and renders nowiki, pre, math, hiero
519 * If $render is set, performs necessary rendering operations on plugins
520 * Returns the text, and fills an array with data needed in unstrip()
522 * @param StripState $state
524 * @param bool $stripcomments when set, HTML comments <!-- like this -->
525 * will be stripped in addition to other tags. This is important
526 * for section editing, where these comments cause confusion when
527 * counting the sections in the wikisource
529 * @param array dontstrip contains tags which should not be stripped;
530 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
534 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
536 wfProfileIn( __METHOD__
);
537 $render = ($this->mOutputType
== OT_HTML
);
539 $uniq_prefix = $this->mUniqPrefix
;
540 $commentState = new ReplacementArray
;
541 $nowikiItems = array();
542 $generalItems = array();
544 $elements = array_merge(
545 array( 'nowiki', 'gallery' ),
546 array_keys( $this->mTagHooks
) );
549 $elements[] = 'html';
551 if( $this->mOptions
->getUseTeX() ) {
552 $elements[] = 'math';
555 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
556 foreach ( $elements AS $k => $v ) {
557 if ( !in_array ( $v , $dontstrip ) ) continue;
558 unset ( $elements[$k] );
562 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
564 foreach( $matches as $marker => $data ) {
565 list( $element, $content, $params, $tag ) = $data;
567 $tagName = strtolower( $element );
568 wfProfileIn( __METHOD__
."-render-$tagName" );
572 if( substr( $tag, -3 ) == '-->' ) {
575 // Unclosed comment in input.
576 // Close it so later stripping can remove it
585 // Shouldn't happen otherwise. :)
587 $output = Xml
::escapeTagsOnly( $content );
590 $output = $wgContLang->armourMath( MathRenderer
::renderMath( $content ) );
593 $output = $this->renderImageGallery( $content, $params );
596 if( isset( $this->mTagHooks
[$tagName] ) ) {
597 $output = call_user_func_array( $this->mTagHooks
[$tagName],
598 array( $content, $params, $this ) );
600 throw new MWException( "Invalid call hook $element" );
603 wfProfileOut( __METHOD__
."-render-$tagName" );
605 // Just stripping tags; keep the source
609 // Unstrip the output, to support recursive strip() calls
610 $output = $state->unstripBoth( $output );
612 if( !$stripcomments && $element == '!--' ) {
613 $commentState->setPair( $marker, $output );
614 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
615 $nowikiItems[$marker] = $output;
617 $generalItems[$marker] = $output;
620 # Add the new items to the state
621 # We do this after the loop instead of during it to avoid slowing
622 # down the recursive unstrip
623 $state->nowiki
->mergeArray( $nowikiItems );
624 $state->general
->mergeArray( $generalItems );
626 # Unstrip comments unless explicitly told otherwise.
627 # (The comments are always stripped prior to this point, so as to
628 # not invoke any extension tags / parser hooks contained within
630 if ( !$stripcomments ) {
631 // Put them all back and forget them
632 $text = $commentState->replace( $text );
635 wfProfileOut( __METHOD__
);
640 * Restores pre, math, and other extensions removed by strip()
642 * always call unstripNoWiki() after this one
644 * @deprecated use $this->mStripState->unstrip()
646 function unstrip( $text, $state ) {
647 return $state->unstripGeneral( $text );
651 * Always call this after unstrip() to preserve the order
654 * @deprecated use $this->mStripState->unstrip()
656 function unstripNoWiki( $text, $state ) {
657 return $state->unstripNoWiki( $text );
661 * @deprecated use $this->mStripState->unstripBoth()
663 function unstripForHTML( $text ) {
664 return $this->mStripState
->unstripBoth( $text );
668 * Add an item to the strip state
669 * Returns the unique tag which must be inserted into the stripped text
670 * The tag will be replaced with the original text in unstrip()
674 function insertStripItem( $text, &$state ) {
675 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
676 $state->general
->setPair( $rnd, $text );
681 * parse the wiki syntax used to render tables
685 function doTableStuff ( $text ) {
686 $fname = 'Parser::doTableStuff';
687 wfProfileIn( $fname );
689 $lines = explode ( "\n" , $text );
690 $td_history = array (); // Is currently a td tag open?
691 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
692 $tr_history = array (); // Is currently a tr tag open?
693 $tr_attributes = array (); // history of tr attributes
694 $has_opened_tr = array(); // Did this table open a <tr> element?
695 $indent_level = 0; // indent level of the table
696 foreach ( $lines as $key => $line )
698 $line = trim ( $line );
700 if( $line == '' ) { // empty line, go to next line
703 $first_character = $line{0};
706 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
707 // First check if we are starting a new table
708 $indent_level = strlen( $matches[1] );
710 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
711 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
713 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
714 array_push ( $td_history , false );
715 array_push ( $last_tag_history , '' );
716 array_push ( $tr_history , false );
717 array_push ( $tr_attributes , '' );
718 array_push ( $has_opened_tr , false );
719 } else if ( count ( $td_history ) == 0 ) {
720 // Don't do any of the following
722 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
723 // We are ending a table
724 $line = '</table>' . substr ( $line , 2 );
725 $last_tag = array_pop ( $last_tag_history );
727 if ( !array_pop ( $has_opened_tr ) ) {
728 $line = "<tr><td></td></tr>{$line}";
731 if ( array_pop ( $tr_history ) ) {
732 $line = "</tr>{$line}";
735 if ( array_pop ( $td_history ) ) {
736 $line = "</{$last_tag}>{$line}";
738 array_pop ( $tr_attributes );
739 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
740 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
741 // Now we have a table row
742 $line = preg_replace( '#^\|-+#', '', $line );
744 // Whats after the tag is now only attributes
745 $attributes = $this->mStripState
->unstripBoth( $line );
746 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
747 array_pop ( $tr_attributes );
748 array_push ( $tr_attributes , $attributes );
751 $last_tag = array_pop ( $last_tag_history );
752 array_pop ( $has_opened_tr );
753 array_push ( $has_opened_tr , true );
755 if ( array_pop ( $tr_history ) ) {
759 if ( array_pop ( $td_history ) ) {
760 $line = "</{$last_tag}>{$line}";
763 $lines[$key] = $line;
764 array_push ( $tr_history , false );
765 array_push ( $td_history , false );
766 array_push ( $last_tag_history , '' );
768 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
769 // This might be cell elements, td, th or captions
770 if ( substr ( $line , 0 , 2 ) == '|+' ) {
771 $first_character = '+';
772 $line = substr ( $line , 1 );
775 $line = substr ( $line , 1 );
777 if ( $first_character == '!' ) {
778 $line = str_replace ( '!!' , '||' , $line );
781 // Split up multiple cells on the same line.
782 // FIXME : This can result in improper nesting of tags processed
783 // by earlier parser steps, but should avoid splitting up eg
784 // attribute values containing literal "||".
785 $cells = StringUtils
::explodeMarkup( '||' , $line );
789 // Loop through each table cell
790 foreach ( $cells as $cell )
793 if ( $first_character != '+' )
795 $tr_after = array_pop ( $tr_attributes );
796 if ( !array_pop ( $tr_history ) ) {
797 $previous = "<tr{$tr_after}>\n";
799 array_push ( $tr_history , true );
800 array_push ( $tr_attributes , '' );
801 array_pop ( $has_opened_tr );
802 array_push ( $has_opened_tr , true );
805 $last_tag = array_pop ( $last_tag_history );
807 if ( array_pop ( $td_history ) ) {
808 $previous = "</{$last_tag}>{$previous}";
811 if ( $first_character == '|' ) {
813 } else if ( $first_character == '!' ) {
815 } else if ( $first_character == '+' ) {
816 $last_tag = 'caption';
821 array_push ( $last_tag_history , $last_tag );
823 // A cell could contain both parameters and data
824 $cell_data = explode ( '|' , $cell , 2 );
826 // Bug 553: Note that a '|' inside an invalid link should not
827 // be mistaken as delimiting cell parameters
828 if ( strpos( $cell_data[0], '[[' ) !== false ) {
829 $cell = "{$previous}<{$last_tag}>{$cell}";
830 } else if ( count ( $cell_data ) == 1 )
831 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
833 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
834 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
835 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
838 $lines[$key] .= $cell;
839 array_push ( $td_history , true );
844 // Closing open td, tr && table
845 while ( count ( $td_history ) > 0 )
847 if ( array_pop ( $td_history ) ) {
850 if ( array_pop ( $tr_history ) ) {
853 if ( !array_pop ( $has_opened_tr ) ) {
854 $lines[] = "<tr><td></td></tr>" ;
857 $lines[] = '</table>' ;
860 $output = implode ( "\n" , $lines ) ;
862 // special case: don't return empty table
863 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
867 wfProfileOut( $fname );
873 * Helper function for parse() that transforms wiki markup into
874 * HTML. Only called for $mOutputType == OT_HTML.
878 function internalParse( $text ) {
881 $fname = 'Parser::internalParse';
882 wfProfileIn( $fname );
884 # Hook to suspend the parser in this state
885 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
886 wfProfileOut( $fname );
890 # Remove <noinclude> tags and <includeonly> sections
891 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
892 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
893 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
895 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
897 $text = $this->replaceVariables( $text, $args );
898 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text ) );
900 // Tables need to come after variable replacement for things to work
901 // properly; putting them before other transformations should keep
902 // exciting things like link expansions from showing up in surprising
904 $text = $this->doTableStuff( $text );
906 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
908 $text = $this->stripToc( $text );
909 $this->stripNoGallery( $text );
910 $text = $this->doHeadings( $text );
911 if($this->mOptions
->getUseDynamicDates()) {
912 $df =& DateFormatter
::getInstance();
913 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
915 $text = $this->doAllQuotes( $text );
916 $text = $this->replaceInternalLinks( $text );
917 $text = $this->replaceExternalLinks( $text );
919 # replaceInternalLinks may sometimes leave behind
920 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
921 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
923 $text = $this->doMagicLinks( $text );
924 $text = $this->formatHeadings( $text, $isMain );
926 wfProfileOut( $fname );
931 * Replace special strings like "ISBN xxx" and "RFC xxx" with
932 * magic external links.
936 function &doMagicLinks( &$text ) {
937 wfProfileIn( __METHOD__
);
938 $text = preg_replace_callback(
940 <a.*?</a> | # Skip link text
941 <.*?> | # Skip stuff inside HTML elements
942 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
943 ISBN\s+(\b # ISBN, capture number as m[2]
944 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
945 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
946 [0-9Xx] # check digit
948 )!x', array( &$this, 'magicLinkCallback' ), $text );
949 wfProfileOut( __METHOD__
);
953 function magicLinkCallback( $m ) {
954 if ( substr( $m[0], 0, 1 ) == '<' ) {
957 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
959 $num = strtr( $isbn, array(
964 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
965 $text = '<a href="' .
966 $titleObj->escapeLocalUrl( "isbn=$num" ) .
967 "\" class=\"internal\">ISBN $isbn</a>";
969 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
973 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
975 $urlmsg = 'pubmedurl';
978 throw new MWException( __METHOD__
.': unrecognised match type "' .
979 substr($m[0], 0, 20 ) . '"' );
982 $url = wfMsg( $urlmsg, $id);
983 $sk = $this->mOptions
->getSkin();
984 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
985 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
991 * Parse headers and return html
995 function doHeadings( $text ) {
996 $fname = 'Parser::doHeadings';
997 wfProfileIn( $fname );
998 for ( $i = 6; $i >= 1; --$i ) {
999 $h = str_repeat( '=', $i );
1000 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1001 "<h{$i}>\\1</h{$i}>\\2", $text );
1003 wfProfileOut( $fname );
1008 * Replace single quotes with HTML markup
1010 * @return string the altered text
1012 function doAllQuotes( $text ) {
1013 $fname = 'Parser::doAllQuotes';
1014 wfProfileIn( $fname );
1016 $lines = explode( "\n", $text );
1017 foreach ( $lines as $line ) {
1018 $outtext .= $this->doQuotes ( $line ) . "\n";
1020 $outtext = substr($outtext, 0,-1);
1021 wfProfileOut( $fname );
1026 * Helper function for doAllQuotes()
1029 function doQuotes( $text ) {
1030 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1031 if ( count( $arr ) == 1 )
1035 # First, do some preliminary work. This may shift some apostrophes from
1036 # being mark-up to being text. It also counts the number of occurrences
1037 # of bold and italics mark-ups.
1041 foreach ( $arr as $r )
1043 if ( ( $i %
2 ) == 1 )
1045 # If there are ever four apostrophes, assume the first is supposed to
1046 # be text, and the remaining three constitute mark-up for bold text.
1047 if ( strlen( $arr[$i] ) == 4 )
1052 # If there are more than 5 apostrophes in a row, assume they're all
1053 # text except for the last 5.
1054 else if ( strlen( $arr[$i] ) > 5 )
1056 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1059 # Count the number of occurrences of bold and italics mark-ups.
1060 # We are not counting sequences of five apostrophes.
1061 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1062 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1063 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1068 # If there is an odd number of both bold and italics, it is likely
1069 # that one of the bold ones was meant to be an apostrophe followed
1070 # by italics. Which one we cannot know for certain, but it is more
1071 # likely to be one that has a single-letter word before it.
1072 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1075 $firstsingleletterword = -1;
1076 $firstmultiletterword = -1;
1078 foreach ( $arr as $r )
1080 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1082 $x1 = substr ($arr[$i-1], -1);
1083 $x2 = substr ($arr[$i-1], -2, 1);
1085 if ($firstspace == -1) $firstspace = $i;
1086 } else if ($x2 == ' ') {
1087 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1089 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1095 # If there is a single-letter word, use it!
1096 if ($firstsingleletterword > -1)
1098 $arr [ $firstsingleletterword ] = "''";
1099 $arr [ $firstsingleletterword-1 ] .= "'";
1101 # If not, but there's a multi-letter word, use that one.
1102 else if ($firstmultiletterword > -1)
1104 $arr [ $firstmultiletterword ] = "''";
1105 $arr [ $firstmultiletterword-1 ] .= "'";
1107 # ... otherwise use the first one that has neither.
1108 # (notice that it is possible for all three to be -1 if, for example,
1109 # there is only one pentuple-apostrophe in the line)
1110 else if ($firstspace > -1)
1112 $arr [ $firstspace ] = "''";
1113 $arr [ $firstspace-1 ] .= "'";
1117 # Now let's actually convert our apostrophic mush to HTML!
1122 foreach ($arr as $r)
1126 if ($state == 'both')
1133 if (strlen ($r) == 2)
1136 { $output .= '</i>'; $state = ''; }
1137 else if ($state == 'bi')
1138 { $output .= '</i>'; $state = 'b'; }
1139 else if ($state == 'ib')
1140 { $output .= '</b></i><b>'; $state = 'b'; }
1141 else if ($state == 'both')
1142 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1143 else # $state can be 'b' or ''
1144 { $output .= '<i>'; $state .= 'i'; }
1146 else if (strlen ($r) == 3)
1149 { $output .= '</b>'; $state = ''; }
1150 else if ($state == 'bi')
1151 { $output .= '</i></b><i>'; $state = 'i'; }
1152 else if ($state == 'ib')
1153 { $output .= '</b>'; $state = 'i'; }
1154 else if ($state == 'both')
1155 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1156 else # $state can be 'i' or ''
1157 { $output .= '<b>'; $state .= 'b'; }
1159 else if (strlen ($r) == 5)
1162 { $output .= '</b><i>'; $state = 'i'; }
1163 else if ($state == 'i')
1164 { $output .= '</i><b>'; $state = 'b'; }
1165 else if ($state == 'bi')
1166 { $output .= '</i></b>'; $state = ''; }
1167 else if ($state == 'ib')
1168 { $output .= '</b></i>'; $state = ''; }
1169 else if ($state == 'both')
1170 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1171 else # ($state == '')
1172 { $buffer = ''; $state = 'both'; }
1177 # Now close all remaining tags. Notice that the order is important.
1178 if ($state == 'b' ||
$state == 'ib')
1180 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1184 # There might be lonely ''''', so make sure we have a buffer
1185 if ($state == 'both' && $buffer)
1186 $output .= '<b><i>'.$buffer.'</i></b>';
1192 * Replace external links
1194 * Note: this is all very hackish and the order of execution matters a lot.
1195 * Make sure to run maintenance/parserTests.php if you change this code.
1199 function replaceExternalLinks( $text ) {
1201 $fname = 'Parser::replaceExternalLinks';
1202 wfProfileIn( $fname );
1204 $sk = $this->mOptions
->getSkin();
1206 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1208 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1211 while ( $i<count( $bits ) ) {
1213 $protocol = $bits[$i++
];
1214 $text = $bits[$i++
];
1215 $trail = $bits[$i++
];
1217 # The characters '<' and '>' (which were escaped by
1218 # removeHTMLtags()) should not be included in
1219 # URLs, per RFC 2396.
1221 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1222 $text = substr($url, $m2[0][1]) . ' ' . $text;
1223 $url = substr($url, 0, $m2[0][1]);
1226 # If the link text is an image URL, replace it with an <img> tag
1227 # This happened by accident in the original parser, but some people used it extensively
1228 $img = $this->maybeMakeExternalImage( $text );
1229 if ( $img !== false ) {
1235 # Set linktype for CSS - if URL==text, link is essentially free
1236 $linktype = ($text == $url) ?
'free' : 'text';
1238 # No link text, e.g. [http://domain.tld/some.link]
1239 if ( $text == '' ) {
1240 # Autonumber if allowed. See bug #5918
1241 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1242 $text = '[' . ++
$this->mAutonumber
. ']';
1243 $linktype = 'autonumber';
1245 # Otherwise just use the URL
1246 $text = htmlspecialchars( $url );
1250 # Have link text, e.g. [http://domain.tld/some.link text]s
1252 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1255 $text = $wgContLang->markNoConversion($text);
1257 $url = Sanitizer
::cleanUrl( $url );
1259 # Process the trail (i.e. everything after this link up until start of the next link),
1260 # replacing any non-bracketed links
1261 $trail = $this->replaceFreeExternalLinks( $trail );
1263 # Use the encoded URL
1264 # This means that users can paste URLs directly into the text
1265 # Funny characters like ö aren't valid in URLs anyway
1266 # This was changed in August 2004
1267 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1269 # Register link in the output object.
1270 # Replace unnecessary URL escape codes with the referenced character
1271 # This prevents spammers from hiding links from the filters
1272 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1273 $this->mOutput
->addExternalLink( $pasteurized );
1276 wfProfileOut( $fname );
1281 * Replace anything that looks like a URL with a link
1284 function replaceFreeExternalLinks( $text ) {
1286 $fname = 'Parser::replaceFreeExternalLinks';
1287 wfProfileIn( $fname );
1289 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1290 $s = array_shift( $bits );
1293 $sk = $this->mOptions
->getSkin();
1295 while ( $i < count( $bits ) ){
1296 $protocol = $bits[$i++
];
1297 $remainder = $bits[$i++
];
1300 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1301 # Found some characters after the protocol that look promising
1302 $url = $protocol . $m[1];
1305 # special case: handle urls as url args:
1306 # http://www.example.com/foo?=http://www.example.com/bar
1307 if(strlen($trail) == 0 &&
1309 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1310 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1313 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1318 # The characters '<' and '>' (which were escaped by
1319 # removeHTMLtags()) should not be included in
1320 # URLs, per RFC 2396.
1322 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1323 $trail = substr($url, $m2[0][1]) . $trail;
1324 $url = substr($url, 0, $m2[0][1]);
1327 # Move trailing punctuation to $trail
1329 # If there is no left bracket, then consider right brackets fair game too
1330 if ( strpos( $url, '(' ) === false ) {
1334 $numSepChars = strspn( strrev( $url ), $sep );
1335 if ( $numSepChars ) {
1336 $trail = substr( $url, -$numSepChars ) . $trail;
1337 $url = substr( $url, 0, -$numSepChars );
1340 $url = Sanitizer
::cleanUrl( $url );
1342 # Is this an external image?
1343 $text = $this->maybeMakeExternalImage( $url );
1344 if ( $text === false ) {
1345 # Not an image, make a link
1346 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1347 # Register it in the output object...
1348 # Replace unnecessary URL escape codes with their equivalent characters
1349 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1350 $this->mOutput
->addExternalLink( $pasteurized );
1352 $s .= $text . $trail;
1354 $s .= $protocol . $remainder;
1357 wfProfileOut( $fname );
1362 * Replace unusual URL escape codes with their equivalent characters
1366 * @todo This can merge genuinely required bits in the path or query string,
1367 * breaking legit URLs. A proper fix would treat the various parts of
1368 * the URL differently; as a workaround, just use the output for
1369 * statistical records, not for actual linking/output.
1371 static function replaceUnusualEscapes( $url ) {
1372 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1373 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1377 * Callback function used in replaceUnusualEscapes().
1378 * Replaces unusual URL escape codes with their equivalent character
1382 private static function replaceUnusualEscapesCallback( $matches ) {
1383 $char = urldecode( $matches[0] );
1384 $ord = ord( $char );
1385 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1386 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1387 // No, shouldn't be escaped
1390 // Yes, leave it escaped
1396 * make an image if it's allowed, either through the global
1397 * option or through the exception
1400 function maybeMakeExternalImage( $url ) {
1401 $sk = $this->mOptions
->getSkin();
1402 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1403 $imagesexception = !empty($imagesfrom);
1405 if ( $this->mOptions
->getAllowExternalImages()
1406 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1407 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1409 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1416 * Process [[ ]] wikilinks
1420 function replaceInternalLinks( $s ) {
1422 static $fname = 'Parser::replaceInternalLinks' ;
1424 wfProfileIn( $fname );
1426 wfProfileIn( $fname.'-setup' );
1428 # the % is needed to support urlencoded titles as well
1429 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1431 $sk = $this->mOptions
->getSkin();
1433 #split the entire text string on occurences of [[
1434 $a = explode( '[[', ' ' . $s );
1435 #get the first element (all text up to first [[), and remove the space we added
1436 $s = array_shift( $a );
1437 $s = substr( $s, 1 );
1439 # Match a link having the form [[namespace:link|alternate]]trail
1441 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1442 # Match cases where there is no "]]", which might still be images
1443 static $e1_img = FALSE;
1444 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1445 # Match the end of a line for a word that's not followed by whitespace,
1446 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1447 $e2 = wfMsgForContent( 'linkprefix' );
1449 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1450 if( is_null( $this->mTitle
) ) {
1451 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1453 $nottalk = !$this->mTitle
->isTalkPage();
1455 if ( $useLinkPrefixExtension ) {
1457 if ( preg_match( $e2, $s, $m ) ) {
1458 $first_prefix = $m[2];
1460 $first_prefix = false;
1466 if($wgContLang->hasVariants()) {
1467 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1469 $selflink = array($this->mTitle
->getPrefixedText());
1471 $useSubpages = $this->areSubpagesAllowed();
1472 wfProfileOut( $fname.'-setup' );
1474 # Loop for each link
1475 for ($k = 0; isset( $a[$k] ); $k++
) {
1477 if ( $useLinkPrefixExtension ) {
1478 wfProfileIn( $fname.'-prefixhandling' );
1479 if ( preg_match( $e2, $s, $m ) ) {
1487 $prefix = $first_prefix;
1488 $first_prefix = false;
1490 wfProfileOut( $fname.'-prefixhandling' );
1493 $might_be_img = false;
1495 wfProfileIn( "$fname-e1" );
1496 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1498 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1499 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1500 # the real problem is with the $e1 regex
1503 # Still some problems for cases where the ] is meant to be outside punctuation,
1504 # and no image is in sight. See bug 2095.
1507 substr( $m[3], 0, 1 ) === ']' &&
1508 strpos($text, '[') !== false
1511 $text .= ']'; # so that replaceExternalLinks($text) works later
1512 $m[3] = substr( $m[3], 1 );
1514 # fix up urlencoded title texts
1515 if( strpos( $m[1], '%' ) !== false ) {
1516 # Should anchors '#' also be rejected?
1517 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1520 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1521 $might_be_img = true;
1523 if ( strpos( $m[1], '%' ) !== false ) {
1524 $m[1] = urldecode($m[1]);
1527 } else { # Invalid form; output directly
1528 $s .= $prefix . '[[' . $line ;
1529 wfProfileOut( "$fname-e1" );
1532 wfProfileOut( "$fname-e1" );
1533 wfProfileIn( "$fname-misc" );
1535 # Don't allow internal links to pages containing
1536 # PROTO: where PROTO is a valid URL protocol; these
1537 # should be external links.
1538 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1539 $s .= $prefix . '[[' . $line ;
1543 # Make subpage if necessary
1544 if( $useSubpages ) {
1545 $link = $this->maybeDoSubpageLink( $m[1], $text );
1550 $noforce = (substr($m[1], 0, 1) != ':');
1552 # Strip off leading ':'
1553 $link = substr($link, 1);
1556 wfProfileOut( "$fname-misc" );
1557 wfProfileIn( "$fname-title" );
1558 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1560 $s .= $prefix . '[[' . $line;
1561 wfProfileOut( "$fname-title" );
1565 $ns = $nt->getNamespace();
1566 $iw = $nt->getInterWiki();
1567 wfProfileOut( "$fname-title" );
1569 if ($might_be_img) { # if this is actually an invalid link
1570 wfProfileIn( "$fname-might_be_img" );
1571 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1573 while (isset ($a[$k+
1]) ) {
1574 #look at the next 'line' to see if we can close it there
1575 $spliced = array_splice( $a, $k +
1, 1 );
1576 $next_line = array_shift( $spliced );
1577 $m = explode( ']]', $next_line, 3 );
1578 if ( count( $m ) == 3 ) {
1579 # the first ]] closes the inner link, the second the image
1581 $text .= "[[{$m[0]}]]{$m[1]}";
1584 } elseif ( count( $m ) == 2 ) {
1585 #if there's exactly one ]] that's fine, we'll keep looking
1586 $text .= "[[{$m[0]}]]{$m[1]}";
1588 #if $next_line is invalid too, we need look no further
1589 $text .= '[[' . $next_line;
1594 # we couldn't find the end of this imageLink, so output it raw
1595 #but don't ignore what might be perfectly normal links in the text we've examined
1596 $text = $this->replaceInternalLinks($text);
1597 $s .= "{$prefix}[[$link|$text";
1598 # note: no $trail, because without an end, there *is* no trail
1599 wfProfileOut( "$fname-might_be_img" );
1602 } else { #it's not an image, so output it raw
1603 $s .= "{$prefix}[[$link|$text";
1604 # note: no $trail, because without an end, there *is* no trail
1605 wfProfileOut( "$fname-might_be_img" );
1608 wfProfileOut( "$fname-might_be_img" );
1611 $wasblank = ( '' == $text );
1612 if( $wasblank ) $text = $link;
1614 # Link not escaped by : , create the various objects
1618 wfProfileIn( "$fname-interwiki" );
1619 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1620 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1621 $s = rtrim($s . $prefix);
1622 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1623 wfProfileOut( "$fname-interwiki" );
1626 wfProfileOut( "$fname-interwiki" );
1628 if ( $ns == NS_IMAGE
) {
1629 wfProfileIn( "$fname-image" );
1630 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1631 # recursively parse links inside the image caption
1632 # actually, this will parse them in any other parameters, too,
1633 # but it might be hard to fix that, and it doesn't matter ATM
1634 $text = $this->replaceExternalLinks($text);
1635 $text = $this->replaceInternalLinks($text);
1637 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1638 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1639 $this->mOutput
->addImage( $nt->getDBkey() );
1641 wfProfileOut( "$fname-image" );
1644 # We still need to record the image's presence on the page
1645 $this->mOutput
->addImage( $nt->getDBkey() );
1647 wfProfileOut( "$fname-image" );
1651 if ( $ns == NS_CATEGORY
) {
1652 wfProfileIn( "$fname-category" );
1653 $s = rtrim($s . "\n"); # bug 87
1656 $sortkey = $this->getDefaultSort();
1660 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1661 $sortkey = str_replace( "\n", '', $sortkey );
1662 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1663 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1666 * Strip the whitespace Category links produce, see bug 87
1667 * @todo We might want to use trim($tmp, "\n") here.
1669 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1671 wfProfileOut( "$fname-category" );
1676 # Self-link checking
1677 if( $nt->getFragment() === '' ) {
1678 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1679 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1684 # Special and Media are pseudo-namespaces; no pages actually exist in them
1685 if( $ns == NS_MEDIA
) {
1686 $link = $sk->makeMediaLinkObj( $nt, $text );
1687 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1688 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1689 $this->mOutput
->addImage( $nt->getDBkey() );
1691 } elseif( $ns == NS_SPECIAL
) {
1692 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1694 } elseif( $ns == NS_IMAGE
) {
1695 $img = new Image( $nt );
1696 if( $img->exists() ) {
1697 // Force a blue link if the file exists; may be a remote
1698 // upload on the shared repository, and we want to see its
1699 // auto-generated page.
1700 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1701 $this->mOutput
->addLink( $nt );
1705 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1707 wfProfileOut( $fname );
1712 * Make a link placeholder. The text returned can be later resolved to a real link with
1713 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1714 * parsing of interwiki links, and secondly to allow all existence checks and
1715 * article length checks (for stub links) to be bundled into a single query.
1718 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1719 wfProfileIn( __METHOD__
);
1720 if ( ! is_object($nt) ) {
1722 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1724 # Separate the link trail from the rest of the link
1725 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1727 if ( $nt->isExternal() ) {
1728 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1729 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1730 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1732 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1733 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1734 $this->mLinkHolders
['queries'][] = $query;
1735 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1736 $this->mLinkHolders
['titles'][] = $nt;
1738 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1741 wfProfileOut( __METHOD__
);
1746 * Render a forced-blue link inline; protect against double expansion of
1747 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1748 * Since this little disaster has to split off the trail text to avoid
1749 * breaking URLs in the following text without breaking trails on the
1750 * wiki links, it's been made into a horrible function.
1753 * @param string $text
1754 * @param string $query
1755 * @param string $trail
1756 * @param string $prefix
1757 * @return string HTML-wikitext mix oh yuck
1759 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1760 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1761 $sk = $this->mOptions
->getSkin();
1762 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1763 return $this->armorLinks( $link ) . $trail;
1767 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1768 * going to go through further parsing steps before inline URL expansion.
1770 * In particular this is important when using action=render, which causes
1771 * full URLs to be included.
1773 * Oh man I hate our multi-layer parser!
1775 * @param string more-or-less HTML
1776 * @return string less-or-more HTML with NOPARSE bits
1778 function armorLinks( $text ) {
1779 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1780 "{$this->mUniqPrefix}NOPARSE$1", $text );
1784 * Return true if subpage links should be expanded on this page.
1787 function areSubpagesAllowed() {
1788 # Some namespaces don't allow subpages
1789 global $wgNamespacesWithSubpages;
1790 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1794 * Handle link to subpage if necessary
1795 * @param string $target the source of the link
1796 * @param string &$text the link text, modified as necessary
1797 * @return string the full name of the link
1800 function maybeDoSubpageLink($target, &$text) {
1803 # :Foobar -- override special treatment of prefix (images, language links)
1804 # /Foobar -- convert to CurrentPage/Foobar
1805 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1806 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1807 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1809 $fname = 'Parser::maybeDoSubpageLink';
1810 wfProfileIn( $fname );
1811 $ret = $target; # default return value is no change
1814 $target = trim( $target );
1816 # Some namespaces don't allow subpages,
1817 # so only perform processing if subpages are allowed
1818 if( $this->areSubpagesAllowed() ) {
1819 # Look at the first character
1820 if( $target != '' && $target{0} == '/' ) {
1821 # / at end means we don't want the slash to be shown
1822 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1823 if( $trailingSlashes ) {
1824 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1826 $noslash = substr( $target, 1 );
1829 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1830 if( '' === $text ) {
1832 } # this might be changed for ugliness reasons
1834 # check for .. subpage backlinks
1836 $nodotdot = $target;
1837 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1839 $nodotdot = substr( $nodotdot, 3 );
1841 if($dotdotcount > 0) {
1842 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1843 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1844 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1845 # / at the end means don't show full path
1846 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1847 $nodotdot = substr( $nodotdot, 0, -1 );
1848 if( '' === $text ) {
1852 $nodotdot = trim( $nodotdot );
1853 if( $nodotdot != '' ) {
1854 $ret .= '/' . $nodotdot;
1861 wfProfileOut( $fname );
1866 * Used by doBlockLevels()
1869 /* private */ function closeParagraph() {
1871 if ( '' != $this->mLastSection
) {
1872 $result = '</' . $this->mLastSection
. ">\n";
1874 $this->mInPre
= false;
1875 $this->mLastSection
= '';
1878 # getCommon() returns the length of the longest common substring
1879 # of both arguments, starting at the beginning of both.
1881 /* private */ function getCommon( $st1, $st2 ) {
1882 $fl = strlen( $st1 );
1883 $shorter = strlen( $st2 );
1884 if ( $fl < $shorter ) { $shorter = $fl; }
1886 for ( $i = 0; $i < $shorter; ++
$i ) {
1887 if ( $st1{$i} != $st2{$i} ) { break; }
1891 # These next three functions open, continue, and close the list
1892 # element appropriate to the prefix character passed into them.
1894 /* private */ function openList( $char ) {
1895 $result = $this->closeParagraph();
1897 if ( '*' == $char ) { $result .= '<ul><li>'; }
1898 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1899 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1900 else if ( ';' == $char ) {
1901 $result .= '<dl><dt>';
1902 $this->mDTopen
= true;
1904 else { $result = '<!-- ERR 1 -->'; }
1909 /* private */ function nextItem( $char ) {
1910 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1911 else if ( ':' == $char ||
';' == $char ) {
1913 if ( $this->mDTopen
) { $close = '</dt>'; }
1914 if ( ';' == $char ) {
1915 $this->mDTopen
= true;
1916 return $close . '<dt>';
1918 $this->mDTopen
= false;
1919 return $close . '<dd>';
1922 return '<!-- ERR 2 -->';
1925 /* private */ function closeList( $char ) {
1926 if ( '*' == $char ) { $text = '</li></ul>'; }
1927 else if ( '#' == $char ) { $text = '</li></ol>'; }
1928 else if ( ':' == $char ) {
1929 if ( $this->mDTopen
) {
1930 $this->mDTopen
= false;
1931 $text = '</dt></dl>';
1933 $text = '</dd></dl>';
1936 else { return '<!-- ERR 3 -->'; }
1942 * Make lists from lines starting with ':', '*', '#', etc.
1945 * @return string the lists rendered as HTML
1947 function doBlockLevels( $text, $linestart ) {
1948 $fname = 'Parser::doBlockLevels';
1949 wfProfileIn( $fname );
1951 # Parsing through the text line by line. The main thing
1952 # happening here is handling of block-level elements p, pre,
1953 # and making lists from lines starting with * # : etc.
1955 $textLines = explode( "\n", $text );
1957 $lastPrefix = $output = '';
1958 $this->mDTopen
= $inBlockElem = false;
1960 $paragraphStack = false;
1962 if ( !$linestart ) {
1963 $output .= array_shift( $textLines );
1965 foreach ( $textLines as $oLine ) {
1966 $lastPrefixLength = strlen( $lastPrefix );
1967 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1968 $preOpenMatch = preg_match('/<pre/i', $oLine );
1969 if ( !$this->mInPre
) {
1970 # Multiple prefixes may abut each other for nested lists.
1971 $prefixLength = strspn( $oLine, '*#:;' );
1972 $pref = substr( $oLine, 0, $prefixLength );
1975 $pref2 = str_replace( ';', ':', $pref );
1976 $t = substr( $oLine, $prefixLength );
1977 $this->mInPre
= !empty($preOpenMatch);
1979 # Don't interpret any other prefixes in preformatted text
1981 $pref = $pref2 = '';
1986 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1987 # Same as the last item, so no need to deal with nesting or opening stuff
1988 $output .= $this->nextItem( substr( $pref, -1 ) );
1989 $paragraphStack = false;
1991 if ( substr( $pref, -1 ) == ';') {
1992 # The one nasty exception: definition lists work like this:
1993 # ; title : definition text
1994 # So we check for : in the remainder text to split up the
1995 # title and definition, without b0rking links.
1997 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1999 $output .= $term . $this->nextItem( ':' );
2002 } elseif( $prefixLength ||
$lastPrefixLength ) {
2003 # Either open or close a level...
2004 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2005 $paragraphStack = false;
2007 while( $commonPrefixLength < $lastPrefixLength ) {
2008 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2009 --$lastPrefixLength;
2011 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2012 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2014 while ( $prefixLength > $commonPrefixLength ) {
2015 $char = substr( $pref, $commonPrefixLength, 1 );
2016 $output .= $this->openList( $char );
2018 if ( ';' == $char ) {
2019 # FIXME: This is dupe of code above
2020 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2022 $output .= $term . $this->nextItem( ':' );
2025 ++
$commonPrefixLength;
2027 $lastPrefix = $pref2;
2029 if( 0 == $prefixLength ) {
2030 wfProfileIn( "$fname-paragraph" );
2031 # No prefix (not in list)--go to paragraph mode
2032 // XXX: use a stack for nestable elements like span, table and div
2033 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2034 $closematch = preg_match(
2035 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2036 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2037 if ( $openmatch or $closematch ) {
2038 $paragraphStack = false;
2039 #Â TODO bug 5718: paragraph closed
2040 $output .= $this->closeParagraph();
2041 if ( $preOpenMatch and !$preCloseMatch ) {
2042 $this->mInPre
= true;
2044 if ( $closematch ) {
2045 $inBlockElem = false;
2047 $inBlockElem = true;
2049 } else if ( !$inBlockElem && !$this->mInPre
) {
2050 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2052 if ($this->mLastSection
!= 'pre') {
2053 $paragraphStack = false;
2054 $output .= $this->closeParagraph().'<pre>';
2055 $this->mLastSection
= 'pre';
2057 $t = substr( $t, 1 );
2060 if ( '' == trim($t) ) {
2061 if ( $paragraphStack ) {
2062 $output .= $paragraphStack.'<br />';
2063 $paragraphStack = false;
2064 $this->mLastSection
= 'p';
2066 if ($this->mLastSection
!= 'p' ) {
2067 $output .= $this->closeParagraph();
2068 $this->mLastSection
= '';
2069 $paragraphStack = '<p>';
2071 $paragraphStack = '</p><p>';
2075 if ( $paragraphStack ) {
2076 $output .= $paragraphStack;
2077 $paragraphStack = false;
2078 $this->mLastSection
= 'p';
2079 } else if ($this->mLastSection
!= 'p') {
2080 $output .= $this->closeParagraph().'<p>';
2081 $this->mLastSection
= 'p';
2086 wfProfileOut( "$fname-paragraph" );
2088 // somewhere above we forget to get out of pre block (bug 785)
2089 if($preCloseMatch && $this->mInPre
) {
2090 $this->mInPre
= false;
2092 if ($paragraphStack === false) {
2096 while ( $prefixLength ) {
2097 $output .= $this->closeList( $pref2{$prefixLength-1} );
2100 if ( '' != $this->mLastSection
) {
2101 $output .= '</' . $this->mLastSection
. '>';
2102 $this->mLastSection
= '';
2105 wfProfileOut( $fname );
2110 * Split up a string on ':', ignoring any occurences inside tags
2111 * to prevent illegal overlapping.
2112 * @param string $str the string to split
2113 * @param string &$before set to everything before the ':'
2114 * @param string &$after set to everything after the ':'
2115 * return string the position of the ':', or false if none found
2117 function findColonNoLinks($str, &$before, &$after) {
2118 $fname = 'Parser::findColonNoLinks';
2119 wfProfileIn( $fname );
2121 $pos = strpos( $str, ':' );
2122 if( $pos === false ) {
2124 wfProfileOut( $fname );
2128 $lt = strpos( $str, '<' );
2129 if( $lt === false ||
$lt > $pos ) {
2130 // Easy; no tag nesting to worry about
2131 $before = substr( $str, 0, $pos );
2132 $after = substr( $str, $pos+
1 );
2133 wfProfileOut( $fname );
2137 // Ugly state machine to walk through avoiding tags.
2138 $state = MW_COLON_STATE_TEXT
;
2140 $len = strlen( $str );
2141 for( $i = 0; $i < $len; $i++
) {
2145 // (Using the number is a performance hack for common cases)
2146 case 0: // MW_COLON_STATE_TEXT:
2149 // Could be either a <start> tag or an </end> tag
2150 $state = MW_COLON_STATE_TAGSTART
;
2155 $before = substr( $str, 0, $i );
2156 $after = substr( $str, $i +
1 );
2157 wfProfileOut( $fname );
2160 // Embedded in a tag; don't break it.
2163 // Skip ahead looking for something interesting
2164 $colon = strpos( $str, ':', $i );
2165 if( $colon === false ) {
2166 // Nothing else interesting
2167 wfProfileOut( $fname );
2170 $lt = strpos( $str, '<', $i );
2171 if( $stack === 0 ) {
2172 if( $lt === false ||
$colon < $lt ) {
2174 $before = substr( $str, 0, $colon );
2175 $after = substr( $str, $colon +
1 );
2176 wfProfileOut( $fname );
2180 if( $lt === false ) {
2181 // Nothing else interesting to find; abort!
2182 // We're nested, but there's no close tags left. Abort!
2185 // Skip ahead to next tag start
2187 $state = MW_COLON_STATE_TAGSTART
;
2190 case 1: // MW_COLON_STATE_TAG:
2195 $state = MW_COLON_STATE_TEXT
;
2198 // Slash may be followed by >?
2199 $state = MW_COLON_STATE_TAGSLASH
;
2205 case 2: // MW_COLON_STATE_TAGSTART:
2208 $state = MW_COLON_STATE_CLOSETAG
;
2211 $state = MW_COLON_STATE_COMMENT
;
2214 // Illegal early close? This shouldn't happen D:
2215 $state = MW_COLON_STATE_TEXT
;
2218 $state = MW_COLON_STATE_TAG
;
2221 case 3: // MW_COLON_STATE_CLOSETAG:
2226 wfDebug( "Invalid input in $fname; too many close tags\n" );
2227 wfProfileOut( $fname );
2230 $state = MW_COLON_STATE_TEXT
;
2233 case MW_COLON_STATE_TAGSLASH
:
2235 // Yes, a self-closed tag <blah/>
2236 $state = MW_COLON_STATE_TEXT
;
2238 // Probably we're jumping the gun, and this is an attribute
2239 $state = MW_COLON_STATE_TAG
;
2242 case 5: // MW_COLON_STATE_COMMENT:
2244 $state = MW_COLON_STATE_COMMENTDASH
;
2247 case MW_COLON_STATE_COMMENTDASH
:
2249 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2251 $state = MW_COLON_STATE_COMMENT
;
2254 case MW_COLON_STATE_COMMENTDASHDASH
:
2256 $state = MW_COLON_STATE_TEXT
;
2258 $state = MW_COLON_STATE_COMMENT
;
2262 throw new MWException( "State machine error in $fname" );
2266 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2269 wfProfileOut( $fname );
2274 * Return value of a magic variable (like PAGENAME)
2278 function getVariableValue( $index ) {
2279 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2282 * Some of these require message or data lookups and can be
2283 * expensive to check many times.
2285 static $varCache = array();
2286 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2287 if ( isset( $varCache[$index] ) ) {
2288 return $varCache[$index];
2293 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2296 global $wgLocaltimezone;
2297 if ( isset( $wgLocaltimezone ) ) {
2298 $oldtz = getenv( 'TZ' );
2299 putenv( 'TZ='.$wgLocaltimezone );
2301 $localTimestamp = date( 'YmdHis', $ts );
2302 $localMonth = date( 'm', $ts );
2303 $localMonthName = date( 'n', $ts );
2304 $localDay = date( 'j', $ts );
2305 $localDay2 = date( 'd', $ts );
2306 $localDayOfWeek = date( 'w', $ts );
2307 $localWeek = date( 'W', $ts );
2308 $localYear = date( 'Y', $ts );
2309 $localHour = date( 'H', $ts );
2310 if ( isset( $wgLocaltimezone ) ) {
2311 putenv( 'TZ='.$oldtz );
2315 case 'currentmonth':
2316 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2317 case 'currentmonthname':
2318 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2319 case 'currentmonthnamegen':
2320 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2321 case 'currentmonthabbrev':
2322 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2324 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2326 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2328 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2329 case 'localmonthname':
2330 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2331 case 'localmonthnamegen':
2332 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2333 case 'localmonthabbrev':
2334 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2336 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2338 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2340 return $this->mTitle
->getText();
2342 return $this->mTitle
->getPartialURL();
2343 case 'fullpagename':
2344 return $this->mTitle
->getPrefixedText();
2345 case 'fullpagenamee':
2346 return $this->mTitle
->getPrefixedURL();
2348 return $this->mTitle
->getSubpageText();
2349 case 'subpagenamee':
2350 return $this->mTitle
->getSubpageUrlForm();
2351 case 'basepagename':
2352 return $this->mTitle
->getBaseText();
2353 case 'basepagenamee':
2354 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2355 case 'talkpagename':
2356 if( $this->mTitle
->canTalk() ) {
2357 $talkPage = $this->mTitle
->getTalkPage();
2358 return $talkPage->getPrefixedText();
2362 case 'talkpagenamee':
2363 if( $this->mTitle
->canTalk() ) {
2364 $talkPage = $this->mTitle
->getTalkPage();
2365 return $talkPage->getPrefixedUrl();
2369 case 'subjectpagename':
2370 $subjPage = $this->mTitle
->getSubjectPage();
2371 return $subjPage->getPrefixedText();
2372 case 'subjectpagenamee':
2373 $subjPage = $this->mTitle
->getSubjectPage();
2374 return $subjPage->getPrefixedUrl();
2376 return $this->mRevisionId
;
2378 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2379 case 'revisionday2':
2380 return substr( $this->getRevisionTimestamp(), 6, 2 );
2381 case 'revisionmonth':
2382 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2383 case 'revisionyear':
2384 return substr( $this->getRevisionTimestamp(), 0, 4 );
2385 case 'revisiontimestamp':
2386 return $this->getRevisionTimestamp();
2388 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2390 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2392 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2394 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2395 case 'subjectspace':
2396 return $this->mTitle
->getSubjectNsText();
2397 case 'subjectspacee':
2398 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2399 case 'currentdayname':
2400 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2402 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2404 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2406 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2408 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2409 // int to remove the padding
2410 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2412 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2413 case 'localdayname':
2414 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2416 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2418 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2420 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2422 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2423 // int to remove the padding
2424 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2426 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2427 case 'numberofarticles':
2428 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2429 case 'numberoffiles':
2430 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2431 case 'numberofusers':
2432 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2433 case 'numberofpages':
2434 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2435 case 'numberofadmins':
2436 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2437 case 'numberofedits':
2438 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2439 case 'currenttimestamp':
2440 return $varCache[$index] = wfTimestampNow();
2441 case 'localtimestamp':
2442 return $varCache[$index] = $localTimestamp;
2443 case 'currentversion':
2444 return $varCache[$index] = SpecialVersion
::getVersion();
2450 return $wgServerName;
2452 return $wgScriptPath;
2453 case 'directionmark':
2454 return $wgContLang->getDirMark();
2455 case 'contentlanguage':
2456 global $wgContLanguageCode;
2457 return $wgContLanguageCode;
2460 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2468 * initialise the magic variables (like CURRENTMONTHNAME)
2472 function initialiseVariables() {
2473 $fname = 'Parser::initialiseVariables';
2474 wfProfileIn( $fname );
2475 $variableIDs = MagicWord
::getVariableIDs();
2477 $this->mVariables
= array();
2478 foreach ( $variableIDs as $id ) {
2479 $mw =& MagicWord
::get( $id );
2480 $mw->addToArray( $this->mVariables
, $id );
2482 wfProfileOut( $fname );
2486 * parse any parentheses in format ((title|part|part))
2487 * and call callbacks to get a replacement text for any found piece
2489 * @param string $text The text to parse
2490 * @param array $callbacks rules in form:
2491 * '{' => array( # opening parentheses
2492 * 'end' => '}', # closing parentheses
2493 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2494 * 3 => callback # replacement callback to call if {{{..}}} is found
2497 * 'min' => 2, # Minimum parenthesis count in cb
2498 * 'max' => 3, # Maximum parenthesis count in cb
2501 function replace_callback ($text, $callbacks) {
2502 wfProfileIn( __METHOD__
);
2503 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2504 $lastOpeningBrace = -1; # last not closed parentheses
2506 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2509 while ( $i < strlen( $text ) ) {
2510 # Find next opening brace, closing brace or pipe
2511 if ( $lastOpeningBrace == -1 ) {
2512 $currentClosing = '';
2513 $search = $validOpeningBraces;
2515 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2516 $search = $validOpeningBraces . '|' . $currentClosing;
2519 $i +
= strcspn( $text, $search, $i );
2520 if ( $i < strlen( $text ) ) {
2521 if ( $text[$i] == '|' ) {
2523 } elseif ( $text[$i] == $currentClosing ) {
2525 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2527 $rule = $callbacks[$text[$i]];
2529 # Some versions of PHP have a strcspn which stops on null characters
2530 # Ignore and continue
2539 if ( $found == 'open' ) {
2540 # found opening brace, let's add it to parentheses stack
2541 $piece = array('brace' => $text[$i],
2542 'braceEnd' => $rule['end'],
2546 # count opening brace characters
2547 $piece['count'] = strspn( $text, $piece['brace'], $i );
2548 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2549 $i +
= $piece['count'];
2551 # we need to add to stack only if opening brace count is enough for one of the rules
2552 if ( $piece['count'] >= $rule['min'] ) {
2553 $lastOpeningBrace ++
;
2554 $openingBraceStack[$lastOpeningBrace] = $piece;
2556 } elseif ( $found == 'close' ) {
2557 # lets check if it is enough characters for closing brace
2558 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2559 $count = strspn( $text, $text[$i], $i, $maxCount );
2561 # check for maximum matching characters (if there are 5 closing
2562 # characters, we will probably need only 3 - depending on the rules)
2564 $matchingCallback = null;
2565 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2566 if ( $count > $cbType['max'] ) {
2567 # The specified maximum exists in the callback array, unless the caller
2569 $matchingCount = $cbType['max'];
2571 # Count is less than the maximum
2572 # Skip any gaps in the callback array to find the true largest match
2573 # Need to use array_key_exists not isset because the callback can be null
2574 $matchingCount = $count;
2575 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2580 if ($matchingCount <= 0) {
2584 $matchingCallback = $cbType['cb'][$matchingCount];
2586 # let's set a title or last part (if '|' was found)
2587 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2588 $openingBraceStack[$lastOpeningBrace]['title'] =
2589 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2590 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2592 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2593 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2594 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2597 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2598 $pieceEnd = $i +
$matchingCount;
2600 if( is_callable( $matchingCallback ) ) {
2602 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2603 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2604 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2605 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2607 # finally we can call a user callback and replace piece of text
2608 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2609 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2610 $i = $pieceStart +
strlen($replaceWith);
2612 # null value for callback means that parentheses should be parsed, but not replaced
2613 $i +
= $matchingCount;
2616 # reset last opening parentheses, but keep it in case there are unused characters
2617 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2618 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2619 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2622 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2623 $openingBraceStack[$lastOpeningBrace--] = null;
2625 if ($matchingCount < $piece['count']) {
2626 $piece['count'] -= $matchingCount;
2627 $piece['startAt'] -= $matchingCount;
2628 $piece['partStart'] = $piece['startAt'];
2629 # do we still qualify for any callback with remaining count?
2630 $currentCbList = $callbacks[$piece['brace']]['cb'];
2631 while ( $piece['count'] ) {
2632 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2633 $lastOpeningBrace++
;
2634 $openingBraceStack[$lastOpeningBrace] = $piece;
2640 } elseif ( $found == 'pipe' ) {
2641 # lets set a title if it is a first separator, or next part otherwise
2642 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2643 $openingBraceStack[$lastOpeningBrace]['title'] =
2644 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2645 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2646 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2648 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2649 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2650 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2652 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2656 wfProfileOut( __METHOD__
);
2661 * Replace magic variables, templates, and template arguments
2662 * with the appropriate text. Templates are substituted recursively,
2663 * taking care to avoid infinite loops.
2665 * Note that the substitution depends on value of $mOutputType:
2666 * OT_WIKI: only {{subst:}} templates
2667 * OT_MSG: only magic variables
2668 * OT_HTML: all templates and magic variables
2670 * @param string $tex The text to transform
2671 * @param array $args Key-value pairs representing template parameters to substitute
2672 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2675 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2676 # Prevent too big inclusions
2677 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2681 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2682 wfProfileIn( $fname );
2684 # This function is called recursively. To keep track of arguments we need a stack:
2685 array_push( $this->mArgStack
, $args );
2687 $braceCallbacks = array();
2689 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2691 if ( $this->mOutputType
!= OT_MSG
) {
2692 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2694 if ( $braceCallbacks ) {
2698 'cb' => $braceCallbacks,
2699 'min' => $argsOnly ?
3 : 2,
2700 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2704 'cb' => array(2=>null),
2709 $text = $this->replace_callback ($text, $callbacks);
2711 array_pop( $this->mArgStack
);
2713 wfProfileOut( $fname );
2718 * Replace magic variables
2721 function variableSubstitution( $matches ) {
2723 $fname = 'Parser::variableSubstitution';
2724 $varname = $wgContLang->lc($matches[1]);
2725 wfProfileIn( $fname );
2727 if ( $this->mOutputType
== OT_WIKI
) {
2728 # Do only magic variables prefixed by SUBST
2729 $mwSubst =& MagicWord
::get( 'subst' );
2730 if (!$mwSubst->matchStartAndRemove( $varname ))
2732 # Note that if we don't substitute the variable below,
2733 # we don't remove the {{subst:}} magic word, in case
2734 # it is a template rather than a magic variable.
2736 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2737 $id = $this->mVariables
[$varname];
2738 # Now check if we did really match, case sensitive or not
2739 $mw =& MagicWord
::get( $id );
2740 if ($mw->match($matches[1])) {
2741 $text = $this->getVariableValue( $id );
2742 $this->mOutput
->mContainsOldMagic
= true;
2744 $text = $matches[0];
2747 $text = $matches[0];
2749 wfProfileOut( $fname );
2754 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2755 static function createAssocArgs( $args ) {
2756 $assocArgs = array();
2758 foreach( $args as $arg ) {
2759 $eqpos = strpos( $arg, '=' );
2760 if ( $eqpos === false ) {
2761 $assocArgs[$index++
] = $arg;
2763 $name = trim( substr( $arg, 0, $eqpos ) );
2764 $value = trim( substr( $arg, $eqpos+
1 ) );
2765 if ( $value === false ) {
2768 if ( $name !== false ) {
2769 $assocArgs[$name] = $value;
2778 * Return the text of a template, after recursively
2779 * replacing any variables or templates within the template.
2781 * @param array $piece The parts of the template
2782 * $piece['text']: matched text
2783 * $piece['title']: the title, i.e. the part before the |
2784 * $piece['parts']: the parameter array
2785 * @return string the text of the template
2788 function braceSubstitution( $piece ) {
2789 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2790 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2791 wfProfileIn( $fname );
2792 wfProfileIn( __METHOD__
.'-setup' );
2795 $found = false; # $text has been filled
2796 $nowiki = false; # wiki markup in $text should be escaped
2797 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2798 $noargs = false; # Don't replace triple-brace arguments in $text
2799 $replaceHeadings = false; # Make the edit section links go to the template not the article
2800 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2801 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2802 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2804 # Title object, where $text came from
2810 # $part1 is the bit before the first |, and must contain only title characters
2811 # $args is a list of arguments, starting from index 0, not including $part1
2813 $titleText = $part1 = $piece['title'];
2814 # If the third subpattern matched anything, it will start with |
2816 if (null == $piece['parts']) {
2817 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2818 if ($replaceWith != $piece['text']) {
2819 $text = $replaceWith;
2826 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2827 wfProfileOut( __METHOD__
.'-setup' );
2830 wfProfileIn( __METHOD__
.'-modifiers' );
2832 $mwSubst =& MagicWord
::get( 'subst' );
2833 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2834 # One of two possibilities is true:
2835 # 1) Found SUBST but not in the PST phase
2836 # 2) Didn't find SUBST and in the PST phase
2837 # In either case, return without further processing
2838 $text = $piece['text'];
2845 # MSG, MSGNW and RAW
2848 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2849 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2852 # Remove obsolete MSG:
2853 $mwMsg =& MagicWord
::get( 'msg' );
2854 $mwMsg->matchStartAndRemove( $part1 );
2858 $mwRaw =& MagicWord
::get( 'raw' );
2859 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2860 $forceRawInterwiki = true;
2863 wfProfileOut( __METHOD__
.'-modifiers' );
2865 //save path level before recursing into functions & templates.
2866 $lastPathLevel = $this->mTemplatePath
;
2870 wfProfileIn( __METHOD__
. '-pfunc' );
2872 $colonPos = strpos( $part1, ':' );
2873 if ( $colonPos !== false ) {
2874 # Case sensitive functions
2875 $function = substr( $part1, 0, $colonPos );
2876 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2877 $function = $this->mFunctionSynonyms
[1][$function];
2879 # Case insensitive functions
2880 $function = strtolower( $function );
2881 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2882 $function = $this->mFunctionSynonyms
[0][$function];
2888 $funcArgs = array_map( 'trim', $args );
2889 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2890 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2893 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2897 if ( is_array( $result ) ) {
2898 if ( isset( $result[0] ) ) {
2899 $text = $linestart . $result[0];
2900 unset( $result[0] );
2903 // Extract flags into the local scope
2904 // This allows callers to set flags such as nowiki, noparse, found, etc.
2907 $text = $linestart . $result;
2911 wfProfileOut( __METHOD__
. '-pfunc' );
2914 # Template table test
2916 # Did we encounter this template already? If yes, it is in the cache
2917 # and we need to check for loops.
2918 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2921 # Infinite loop test
2922 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2926 $text = $linestart .
2927 "[[$part1]]<!-- WARNING: template loop detected -->";
2928 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2930 # set $text to cached message.
2931 $text = $linestart . $this->mTemplates
[$piece['title']];
2932 #treat title for cached page the same as others
2935 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2936 if ($subpage !== '') {
2937 $ns = $this->mTitle
->getNamespace();
2939 $title = Title
::newFromText( $part1, $ns );
2940 //used by include size checking
2941 $titleText = $title->getPrefixedText();
2942 //used by edit section links
2943 $replaceHeadings = true;
2948 # Load from database
2950 wfProfileIn( __METHOD__
. '-loadtpl' );
2952 # declaring $subpage directly in the function call
2953 # does not work correctly with references and breaks
2954 # {{/subpage}}-style inclusions
2956 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2957 if ($subpage !== '') {
2958 $ns = $this->mTitle
->getNamespace();
2960 $title = Title
::newFromText( $part1, $ns );
2963 if ( !is_null( $title ) ) {
2964 $titleText = $title->getPrefixedText();
2965 # Check for language variants if the template is not found
2966 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2967 $wgContLang->findVariantLink($part1, $title);
2970 if ( !$title->isExternal() ) {
2971 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2972 $text = SpecialPage
::capturePath( $title );
2973 if ( is_string( $text ) ) {
2978 $this->disableCache();
2980 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2981 $found = false; //access denied
2982 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2984 $articleContent = $this->fetchTemplate( $title );
2985 if ( $articleContent !== false ) {
2987 $text = $articleContent;
2988 $replaceHeadings = true;
2992 # If the title is valid but undisplayable, make a link to it
2993 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2994 $text = "[[:$titleText]]";
2997 } elseif ( $title->isTrans() ) {
2998 // Interwiki transclusion
2999 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3000 $text = $this->interwikiTransclude( $title, 'render' );
3004 $text = $this->interwikiTransclude( $title, 'raw' );
3005 $replaceHeadings = true;
3010 # Template cache array insertion
3011 # Use the original $piece['title'] not the mangled $part1, so that
3012 # modifiers such as RAW: produce separate cache entries
3015 // A special page; don't store it in the template cache.
3017 $this->mTemplates
[$piece['title']] = $text;
3019 $text = $linestart . $text;
3022 wfProfileOut( __METHOD__
. '-loadtpl' );
3025 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3026 # Error, oversize inclusion
3027 $text = $linestart .
3028 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3033 # Recursive parsing, escaping and link table handling
3034 # Only for HTML output
3035 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3036 $text = wfEscapeWikiText( $text );
3037 } elseif ( !$this->ot
['msg'] && $found ) {
3039 $assocArgs = array();
3041 # Clean up argument array
3042 $assocArgs = self
::createAssocArgs($args);
3043 # Add a new element to the templace recursion path
3044 $this->mTemplatePath
[$part1] = 1;
3048 # If there are any <onlyinclude> tags, only include them
3049 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3050 $replacer = new OnlyIncludeReplacer
;
3051 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3052 array( &$replacer, 'replace' ), $text );
3053 $text = $replacer->output
;
3055 # Remove <noinclude> sections and <includeonly> tags
3056 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3057 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3059 if( $this->ot
['html'] ||
$this->ot
['pre'] ) {
3060 # Strip <nowiki>, <pre>, etc.
3061 $text = $this->strip( $text, $this->mStripState
);
3062 if ( $this->ot
['html'] ) {
3063 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3064 } elseif ( $this->ot
['pre'] && $this->mOptions
->getRemoveComments() ) {
3065 $text = Sanitizer
::removeHTMLcomments( $text );
3068 $text = $this->replaceVariables( $text, $assocArgs );
3070 # If the template begins with a table or block-level
3071 # element, it should be treated as beginning a new line.
3072 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3073 $text = "\n" . $text;
3075 } elseif ( !$noargs ) {
3076 # $noparse and !$noargs
3077 # Just replace the arguments, not any double-brace items
3078 # This is used for rendered interwiki transclusion
3079 $text = $this->replaceVariables( $text, $assocArgs, true );
3082 # Prune lower levels off the recursion check path
3083 $this->mTemplatePath
= $lastPathLevel;
3085 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3086 # Error, oversize inclusion
3087 $text = $linestart .
3088 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3094 wfProfileOut( $fname );
3095 return $piece['text'];
3097 wfProfileIn( __METHOD__
. '-placeholders' );
3099 # Replace raw HTML by a placeholder
3100 # Add a blank line preceding, to prevent it from mucking up
3101 # immediately preceding headings
3102 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3104 # replace ==section headers==
3105 # XXX this needs to go away once we have a better parser.
3106 if ( !$this->ot
['wiki'] && !$this->ot
['pre'] && $replaceHeadings ) {
3107 if( !is_null( $title ) )
3108 $encodedname = base64_encode($title->getPrefixedDBkey());
3110 $encodedname = base64_encode("");
3111 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3112 PREG_SPLIT_DELIM_CAPTURE
);
3114 $nsec = $headingOffset;
3115 for( $i = 0; $i < count($m); $i +
= 2 ) {
3117 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3119 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3124 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3125 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3126 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3132 wfProfileOut( __METHOD__
. '-placeholders' );
3135 # Prune lower levels off the recursion check path
3136 $this->mTemplatePath
= $lastPathLevel;
3139 wfProfileOut( $fname );
3140 return $piece['text'];
3142 wfProfileOut( $fname );
3148 * Fetch the unparsed text of a template and register a reference to it.
3150 function fetchTemplate( $title ) {
3152 // Loop to fetch the article, with up to 1 redirect
3153 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3154 $rev = Revision
::newFromTitle( $title );
3155 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3157 $text = $rev->getText();
3158 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3160 $message = $wgLang->lcfirst( $title->getText() );
3161 $text = wfMsgForContentNoTrans( $message );
3162 if( wfEmptyMsg( $message, $text ) ) {
3169 if ( $text === false ) {
3173 $title = Title
::newFromRedirect( $text );
3179 * Transclude an interwiki link.
3181 function interwikiTransclude( $title, $action ) {
3182 global $wgEnableScaryTranscluding;
3184 if (!$wgEnableScaryTranscluding)
3185 return wfMsg('scarytranscludedisabled');
3187 $url = $title->getFullUrl( "action=$action" );
3189 if (strlen($url) > 255)
3190 return wfMsg('scarytranscludetoolong');
3191 return $this->fetchScaryTemplateMaybeFromCache($url);
3194 function fetchScaryTemplateMaybeFromCache($url) {
3195 global $wgTranscludeCacheExpiry;
3196 $dbr = wfGetDB(DB_SLAVE
);
3197 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3198 array('tc_url' => $url));
3200 $time = $obj->tc_time
;
3201 $text = $obj->tc_contents
;
3202 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3207 $text = Http
::get($url);
3209 return wfMsg('scarytranscludefailed', $url);
3211 $dbw = wfGetDB(DB_MASTER
);
3212 $dbw->replace('transcache', array('tc_url'), array(
3214 'tc_time' => time(),
3215 'tc_contents' => $text));
3221 * Triple brace replacement -- used for template arguments
3224 function argSubstitution( $matches ) {
3225 $arg = trim( $matches['title'] );
3226 $text = $matches['text'];
3227 $inputArgs = end( $this->mArgStack
);
3229 if ( array_key_exists( $arg, $inputArgs ) ) {
3230 $text = $inputArgs[$arg];
3231 } else if (($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_PREPROCESS
) &&
3232 null != $matches['parts'] && count($matches['parts']) > 0) {
3233 $text = $matches['parts'][0];
3235 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3236 $text = $matches['text'] .
3237 '<!-- WARNING: argument omitted, expansion size too large -->';
3244 * Increment an include size counter
3246 * @param string $type The type of expansion
3247 * @param integer $size The size of the text
3248 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3250 function incrementIncludeSize( $type, $size ) {
3251 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3254 $this->mIncludeSizes
[$type] +
= $size;
3260 * Detect __NOGALLERY__ magic word and set a placeholder
3262 function stripNoGallery( &$text ) {
3263 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3265 $mw = MagicWord
::get( 'nogallery' );
3266 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3270 * Detect __TOC__ magic word and set a placeholder
3272 function stripToc( $text ) {
3273 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3275 $mw = MagicWord
::get( 'notoc' );
3276 if( $mw->matchAndRemove( $text ) ) {
3277 $this->mShowToc
= false;
3280 $mw = MagicWord
::get( 'toc' );
3281 if( $mw->match( $text ) ) {
3282 $this->mShowToc
= true;
3283 $this->mForceTocPosition
= true;
3285 // Set a placeholder. At the end we'll fill it in with the TOC.
3286 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3288 // Only keep the first one.
3289 $text = $mw->replace( '', $text );
3295 * This function accomplishes several tasks:
3296 * 1) Auto-number headings if that option is enabled
3297 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3298 * 3) Add a Table of contents on the top for users who have enabled the option
3299 * 4) Auto-anchor headings
3301 * It loops through all headlines, collects the necessary data, then splits up the
3302 * string and re-inserts the newly formatted headlines.
3304 * @param string $text
3305 * @param boolean $isMain
3308 function formatHeadings( $text, $isMain=true ) {
3309 global $wgMaxTocLevel, $wgContLang;
3311 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3312 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3315 $showEditLink = $this->mOptions
->getEditSection();
3318 # Inhibit editsection links if requested in the page
3319 $esw =& MagicWord
::get( 'noeditsection' );
3320 if( $esw->matchAndRemove( $text ) ) {
3324 # Get all headlines for numbering them and adding funky stuff like [edit]
3325 # links - this is for later, but we need the number of headlines right now
3327 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3329 # if there are fewer than 4 headlines in the article, do not show TOC
3330 # unless it's been explicitly enabled.
3331 $enoughToc = $this->mShowToc
&&
3332 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3334 # Allow user to stipulate that a page should have a "new section"
3335 # link added via __NEWSECTIONLINK__
3336 $mw =& MagicWord
::get( 'newsectionlink' );
3337 if( $mw->matchAndRemove( $text ) )
3338 $this->mOutput
->setNewSection( true );
3340 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3341 # override above conditions and always show TOC above first header
3342 $mw =& MagicWord
::get( 'forcetoc' );
3343 if ($mw->matchAndRemove( $text ) ) {
3344 $this->mShowToc
= true;
3348 # Never ever show TOC if no headers
3349 if( $numMatches < 1 ) {
3353 # We need this to perform operations on the HTML
3354 $sk = $this->mOptions
->getSkin();
3358 $sectionCount = 0; # headlineCount excluding template sections
3360 # Ugh .. the TOC should have neat indentation levels which can be
3361 # passed to the skin functions. These are determined here
3365 $sublevelCount = array();
3366 $levelCount = array();
3373 foreach( $matches[3] as $headline ) {
3375 $templatetitle = '';
3376 $templatesection = 0;
3379 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3381 $templatetitle = base64_decode($mat[1]);
3382 $templatesection = 1 +
(int)base64_decode($mat[2]);
3383 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3387 $prevlevel = $level;
3388 $prevtoclevel = $toclevel;
3390 $level = $matches[1][$headlineCount];
3392 if( $doNumberHeadings ||
$enoughToc ) {
3394 if ( $level > $prevlevel ) {
3395 # Increase TOC level
3397 $sublevelCount[$toclevel] = 0;
3398 if( $toclevel<$wgMaxTocLevel ) {
3399 $toc .= $sk->tocIndent();
3402 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3403 # Decrease TOC level, find level to jump to
3405 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3406 # Can only go down to level 1
3409 for ($i = $toclevel; $i > 0; $i--) {
3410 if ( $levelCount[$i] == $level ) {
3411 # Found last matching level
3415 elseif ( $levelCount[$i] < $level ) {
3416 # Found first matching level below current level
3422 if( $toclevel<$wgMaxTocLevel ) {
3423 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3427 # No change in level, end TOC line
3428 if( $toclevel<$wgMaxTocLevel ) {
3429 $toc .= $sk->tocLineEnd();
3433 $levelCount[$toclevel] = $level;
3435 # count number of headlines for each level
3436 @$sublevelCount[$toclevel]++
;
3438 for( $i = 1; $i <= $toclevel; $i++
) {
3439 if( !empty( $sublevelCount[$i] ) ) {
3443 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3449 # The canonized header is a version of the header text safe to use for links
3450 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3451 $canonized_headline = $this->mStripState
->unstripBoth( $headline );
3453 # Remove link placeholders by the link text.
3454 # <!--LINK number-->
3456 # link text with suffix
3457 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3458 "\$this->mLinkHolders['texts'][\$1]",
3459 $canonized_headline );
3460 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3461 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3462 $canonized_headline );
3465 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3466 $tocline = trim( $canonized_headline );
3467 # Save headline for section edit hint before it's escaped
3468 $headline_hint = trim( $canonized_headline );
3469 $canonized_headline = Sanitizer
::escapeId( $tocline );
3470 $refers[$headlineCount] = $canonized_headline;
3472 # count how many in assoc. array so we can track dupes in anchors
3473 isset( $refers[$canonized_headline] ) ?
$refers[$canonized_headline]++
: $refers[$canonized_headline] = 1;
3474 $refcount[$headlineCount]=$refers[$canonized_headline];
3476 # Don't number the heading if it is the only one (looks silly)
3477 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3478 # the two are different if the line contains a link
3479 $headline=$numbering . ' ' . $headline;
3482 # Create the anchor for linking from the TOC to the section
3483 $anchor = $canonized_headline;
3484 if($refcount[$headlineCount] > 1 ) {
3485 $anchor .= '_' . $refcount[$headlineCount];
3487 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3488 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3490 # give headline the correct <h#> tag
3491 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3493 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3495 $editlink = $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3499 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3507 if( $toclevel<$wgMaxTocLevel ) {
3508 $toc .= $sk->tocUnindent( $toclevel - 1 );
3510 $toc = $sk->tocList( $toc );
3513 # split up and insert constructed headlines
3515 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3518 foreach( $blocks as $block ) {
3519 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3520 # This is the [edit] link that appears for the top block of text when
3521 # section editing is enabled
3523 # Disabled because it broke block formatting
3524 # For example, a bullet point in the top line
3525 # $full .= $sk->editSectionLink(0);
3528 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3529 # Top anchor now in skin
3533 if( !empty( $head[$i] ) ) {
3538 if( $this->mForceTocPosition
) {
3539 return str_replace( '<!--MWTOC-->', $toc, $full );
3546 * Transform wiki markup when saving a page by doing \r\n -> \n
3547 * conversion, substitting signatures, {{subst:}} templates, etc.
3549 * @param string $text the text to transform
3550 * @param Title &$title the Title object for the current article
3551 * @param User &$user the User object describing the current user
3552 * @param ParserOptions $options parsing options
3553 * @param bool $clearState whether to clear the parser state first
3554 * @return string the altered wiki markup
3557 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3558 $this->mOptions
= $options;
3559 $this->mTitle
=& $title;
3560 $this->setOutputType( OT_WIKI
);
3562 if ( $clearState ) {
3563 $this->clearState();
3566 $stripState = new StripState
;
3570 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3571 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3572 $text = $this->pstPass2( $text, $stripState, $user );
3573 $text = $stripState->unstripBoth( $text );
3578 * Pre-save transform helper function
3581 function pstPass2( $text, &$stripState, $user ) {
3582 global $wgContLang, $wgLocaltimezone;
3584 /* Note: This is the timestamp saved as hardcoded wikitext to
3585 * the database, we use $wgContLang here in order to give
3586 * everyone the same signature and use the default one rather
3587 * than the one selected in each user's preferences.
3589 if ( isset( $wgLocaltimezone ) ) {
3590 $oldtz = getenv( 'TZ' );
3591 putenv( 'TZ='.$wgLocaltimezone );
3593 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3594 ' (' . date( 'T' ) . ')';
3595 if ( isset( $wgLocaltimezone ) ) {
3596 putenv( 'TZ='.$oldtz );
3599 # Variable replacement
3600 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3601 $text = $this->replaceVariables( $text );
3603 # Strip out <nowiki> etc. added via replaceVariables
3604 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3607 $sigText = $this->getUserSig( $user );
3608 $text = strtr( $text, array(
3610 '~~~~' => "$sigText $d",
3614 # Context links: [[|name]] and [[name (context)|]]
3616 global $wgLegalTitleChars;
3617 $tc = "[$wgLegalTitleChars]";
3618 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3620 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3621 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3622 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3624 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3625 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3626 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3628 $t = $this->mTitle
->getText();
3630 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3631 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3632 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3633 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3635 # if there's no context, don't bother duplicating the title
3636 $text = preg_replace( $p2, '[[\\1]]', $text );
3639 # Trim trailing whitespace
3640 $text = rtrim( $text );
3646 * Fetch the user's signature text, if any, and normalize to
3647 * validated, ready-to-insert wikitext.
3653 function getUserSig( &$user ) {
3654 $username = $user->getName();
3655 $nickname = $user->getOption( 'nickname' );
3656 $nickname = $nickname === '' ?
$username : $nickname;
3658 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3659 # Sig. might contain markup; validate this
3660 if( $this->validateSig( $nickname ) !== false ) {
3661 # Validated; clean up (if needed) and return it
3662 return $this->cleanSig( $nickname, true );
3664 # Failed to validate; fall back to the default
3665 $nickname = $username;
3666 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3670 // Make sure nickname doesnt get a sig in a sig
3671 $nickname = $this->cleanSigInSig( $nickname );
3673 # If we're still here, make it a link to the user page
3674 $userpage = $user->getUserPage();
3675 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3679 * Check that the user's signature contains no bad XML
3681 * @param string $text
3682 * @return mixed An expanded string, or false if invalid.
3684 function validateSig( $text ) {
3685 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3689 * Clean up signature text
3691 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3692 * 2) Substitute all transclusions
3694 * @param string $text
3695 * @param $parsing Whether we're cleaning (preferences save) or parsing
3696 * @return string Signature text
3698 function cleanSig( $text, $parsing = false ) {
3700 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3702 $substWord = MagicWord
::get( 'subst' );
3703 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3704 $substText = '{{' . $substWord->getSynonym( 0 );
3706 $text = preg_replace( $substRegex, $substText, $text );
3707 $text = $this->cleanSigInSig( $text );
3708 $text = $this->replaceVariables( $text );
3710 $this->clearState();
3715 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3716 * @param string $text
3717 * @return string Signature text with /~{3,5}/ removed
3719 function cleanSigInSig( $text ) {
3720 $text = preg_replace( '/~{3,5}/', '', $text );
3725 * Set up some variables which are usually set up in parse()
3726 * so that an external function can call some class members with confidence
3729 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3730 $this->mTitle
=& $title;
3731 $this->mOptions
= $options;
3732 $this->setOutputType( $outputType );
3733 if ( $clearState ) {
3734 $this->clearState();
3739 * Transform a MediaWiki message by replacing magic variables.
3741 * @param string $text the text to transform
3742 * @param ParserOptions $options options
3743 * @return string the text with variables substituted
3746 function transformMsg( $text, $options ) {
3748 static $executing = false;
3750 $fname = "Parser::transformMsg";
3752 # Guard against infinite recursion
3758 wfProfileIn($fname);
3760 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
3761 $this->mTitle
= $wgTitle;
3763 $this->mTitle
= Title
::newFromText('msg');
3765 $this->mOptions
= $options;
3766 $this->setOutputType( OT_MSG
);
3767 $this->clearState();
3768 $text = $this->replaceVariables( $text );
3771 wfProfileOut($fname);
3776 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3777 * The callback should have the following form:
3778 * function myParserHook( $text, $params, &$parser ) { ... }
3780 * Transform and return $text. Use $parser for any required context, e.g. use
3781 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3785 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3786 * @param mixed $callback The callback function (and object) to use for the tag
3788 * @return The old value of the mTagHooks array associated with the hook
3790 function setHook( $tag, $callback ) {
3791 $tag = strtolower( $tag );
3792 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3793 $this->mTagHooks
[$tag] = $callback;
3799 * Create a function, e.g. {{sum:1|2|3}}
3800 * The callback function should have the form:
3801 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3803 * The callback may either return the text result of the function, or an array with the text
3804 * in element 0, and a number of flags in the other elements. The names of the flags are
3805 * specified in the keys. Valid flags are:
3806 * found The text returned is valid, stop processing the template. This
3808 * nowiki Wiki markup in the return value should be escaped
3809 * noparse Unsafe HTML tags should not be stripped, etc.
3810 * noargs Don't replace triple-brace arguments in the return value
3811 * isHTML The returned text is HTML, armour it against wikitext transformation
3815 * @param string $id The magic word ID
3816 * @param mixed $callback The callback function (and object) to use
3817 * @param integer $flags a combination of the following flags:
3818 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3820 * @return The old callback function for this name, if any
3822 function setFunctionHook( $id, $callback, $flags = 0 ) {
3823 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id] : null;
3824 $this->mFunctionHooks
[$id] = $callback;
3826 # Add to function cache
3827 $mw = MagicWord
::get( $id );
3829 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3831 $synonyms = $mw->getSynonyms();
3832 $sensitive = intval( $mw->isCaseSensitive() );
3834 foreach ( $synonyms as $syn ) {
3836 if ( !$sensitive ) {
3837 $syn = strtolower( $syn );
3840 if ( !( $flags & SFH_NO_HASH
) ) {
3843 # Remove trailing colon
3844 if ( substr( $syn, -1, 1 ) == ':' ) {
3845 $syn = substr( $syn, 0, -1 );
3847 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3853 * Get all registered function hook identifiers
3857 function getFunctionHooks() {
3858 return array_keys( $this->mFunctionHooks
);
3862 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3863 * Placeholders created in Skin::makeLinkObj()
3864 * Returns an array of links found, indexed by PDBK:
3868 * $options is a bit field, RLH_FOR_UPDATE to select for update
3870 function replaceLinkHolders( &$text, $options = 0 ) {
3874 $fname = 'Parser::replaceLinkHolders';
3875 wfProfileIn( $fname );
3879 $sk = $this->mOptions
->getSkin();
3880 $linkCache =& LinkCache
::singleton();
3882 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3883 wfProfileIn( $fname.'-check' );
3884 $dbr = wfGetDB( DB_SLAVE
);
3885 $page = $dbr->tableName( 'page' );
3886 $threshold = $wgUser->getOption('stubthreshold');
3889 asort( $this->mLinkHolders
['namespaces'] );
3894 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3896 $title = $this->mLinkHolders
['titles'][$key];
3898 # Skip invalid entries.
3899 # Result will be ugly, but prevents crash.
3900 if ( is_null( $title ) ) {
3903 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3905 # Check if it's a static known link, e.g. interwiki
3906 if ( $title->isAlwaysKnown() ) {
3907 $colours[$pdbk] = 1;
3908 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3909 $colours[$pdbk] = 1;
3910 $this->mOutput
->addLink( $title, $id );
3911 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3912 $colours[$pdbk] = 0;
3914 # Not in the link cache, add it to the query
3915 if ( !isset( $current ) ) {
3917 $query = "SELECT page_id, page_namespace, page_title";
3918 if ( $threshold > 0 ) {
3919 $query .= ', page_len, page_is_redirect';
3921 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3922 } elseif ( $current != $ns ) {
3924 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3929 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3934 if ( $options & RLH_FOR_UPDATE
) {
3935 $query .= ' FOR UPDATE';
3938 $res = $dbr->query( $query, $fname );
3940 # Fetch data and form into an associative array
3941 # non-existent = broken
3944 while ( $s = $dbr->fetchObject($res) ) {
3945 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3946 $pdbk = $title->getPrefixedDBkey();
3947 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3948 $this->mOutput
->addLink( $title, $s->page_id
);
3950 if ( $threshold > 0 ) {
3951 $size = $s->page_len
;
3952 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3953 $colours[$pdbk] = 1;
3955 $colours[$pdbk] = 2;
3958 $colours[$pdbk] = 1;
3962 wfProfileOut( $fname.'-check' );
3964 # Do a second query for different language variants of links and categories
3965 if($wgContLang->hasVariants()){
3966 $linkBatch = new LinkBatch();
3967 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
3968 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
3969 $varCategories = array(); // category replacements oldDBkey => newDBkey
3971 $categories = $this->mOutput
->getCategoryLinks();
3973 // Add variants of links to link batch
3974 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3975 $title = $this->mLinkHolders
['titles'][$key];
3976 if ( is_null( $title ) )
3979 $pdbk = $title->getPrefixedDBkey();
3980 $titleText = $title->getText();
3982 // generate all variants of the link title text
3983 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
3985 // if link was not found (in first query), add all variants to query
3986 if ( !isset($colours[$pdbk]) ){
3987 foreach($allTextVariants as $textVariant){
3988 if($textVariant != $titleText){
3989 $variantTitle = Title
::makeTitle( $ns, $textVariant );
3990 if(is_null($variantTitle)) continue;
3991 $linkBatch->addObj( $variantTitle );
3992 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
3998 // process categories, check if a category exists in some variant
3999 foreach( $categories as $category){
4000 $variants = $wgContLang->convertLinkToAllVariants($category);
4001 foreach($variants as $variant){
4002 if($variant != $category){
4003 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4004 if(is_null($variantTitle)) continue;
4005 $linkBatch->addObj( $variantTitle );
4006 $categoryMap[$variant] = $category;
4012 if(!$linkBatch->isEmpty()){
4014 $titleClause = $linkBatch->constructSet('page', $dbr);
4016 $variantQuery = "SELECT page_id, page_namespace, page_title";
4017 if ( $threshold > 0 ) {
4018 $variantQuery .= ', page_len, page_is_redirect';
4021 $variantQuery .= " FROM $page WHERE $titleClause";
4022 if ( $options & RLH_FOR_UPDATE
) {
4023 $variantQuery .= ' FOR UPDATE';
4026 $varRes = $dbr->query( $variantQuery, $fname );
4028 // for each found variants, figure out link holders and replace
4029 while ( $s = $dbr->fetchObject($varRes) ) {
4031 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4032 $varPdbk = $variantTitle->getPrefixedDBkey();
4033 $vardbk = $variantTitle->getDBkey();
4035 $holderKeys = array();
4036 if(isset($variantMap[$varPdbk])){
4037 $holderKeys = $variantMap[$varPdbk];
4038 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4039 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4042 // loop over link holders
4043 foreach($holderKeys as $key){
4044 $title = $this->mLinkHolders
['titles'][$key];
4045 if ( is_null( $title ) ) continue;
4047 $pdbk = $title->getPrefixedDBkey();
4049 if(!isset($colours[$pdbk])){
4050 // found link in some of the variants, replace the link holder data
4051 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4052 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4054 // set pdbk and colour
4055 $pdbks[$key] = $varPdbk;
4056 if ( $threshold > 0 ) {
4057 $size = $s->page_len
;
4058 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4059 $colours[$varPdbk] = 1;
4061 $colours[$varPdbk] = 2;
4065 $colours[$varPdbk] = 1;
4070 // check if the object is a variant of a category
4071 if(isset($categoryMap[$vardbk])){
4072 $oldkey = $categoryMap[$vardbk];
4073 if($oldkey != $vardbk)
4074 $varCategories[$oldkey]=$vardbk;
4078 // rebuild the categories in original order (if there are replacements)
4079 if(count($varCategories)>0){
4081 $originalCats = $this->mOutput
->getCategories();
4082 foreach($originalCats as $cat => $sortkey){
4083 // make the replacement
4084 if( array_key_exists($cat,$varCategories) )
4085 $newCats[$varCategories[$cat]] = $sortkey;
4086 else $newCats[$cat] = $sortkey;
4088 $this->mOutput
->setCategoryLinks($newCats);
4093 # Construct search and replace arrays
4094 wfProfileIn( $fname.'-construct' );
4095 $replacePairs = array();
4096 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4097 $pdbk = $pdbks[$key];
4098 $searchkey = "<!--LINK $key-->";
4099 $title = $this->mLinkHolders
['titles'][$key];
4100 if ( empty( $colours[$pdbk] ) ) {
4101 $linkCache->addBadLinkObj( $title );
4102 $colours[$pdbk] = 0;
4103 $this->mOutput
->addLink( $title, 0 );
4104 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4105 $this->mLinkHolders
['texts'][$key],
4106 $this->mLinkHolders
['queries'][$key] );
4107 } elseif ( $colours[$pdbk] == 1 ) {
4108 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4109 $this->mLinkHolders
['texts'][$key],
4110 $this->mLinkHolders
['queries'][$key] );
4111 } elseif ( $colours[$pdbk] == 2 ) {
4112 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4113 $this->mLinkHolders
['texts'][$key],
4114 $this->mLinkHolders
['queries'][$key] );
4117 $replacer = new HashtableReplacer( $replacePairs, 1 );
4118 wfProfileOut( $fname.'-construct' );
4121 wfProfileIn( $fname.'-replace' );
4122 $text = preg_replace_callback(
4123 '/(<!--LINK .*?-->)/',
4127 wfProfileOut( $fname.'-replace' );
4130 # Now process interwiki link holders
4131 # This is quite a bit simpler than internal links
4132 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4133 wfProfileIn( $fname.'-interwiki' );
4134 # Make interwiki link HTML
4135 $replacePairs = array();
4136 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4137 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4138 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4140 $replacer = new HashtableReplacer( $replacePairs, 1 );
4142 $text = preg_replace_callback(
4143 '/<!--IWLINK (.*?)-->/',
4146 wfProfileOut( $fname.'-interwiki' );
4149 wfProfileOut( $fname );
4154 * Replace <!--LINK--> link placeholders with plain text of links
4155 * (not HTML-formatted).
4156 * @param string $text
4159 function replaceLinkHoldersText( $text ) {
4160 $fname = 'Parser::replaceLinkHoldersText';
4161 wfProfileIn( $fname );
4163 $text = preg_replace_callback(
4164 '/<!--(LINK|IWLINK) (.*?)-->/',
4165 array( &$this, 'replaceLinkHoldersTextCallback' ),
4168 wfProfileOut( $fname );
4173 * @param array $matches
4177 function replaceLinkHoldersTextCallback( $matches ) {
4178 $type = $matches[1];
4180 if( $type == 'LINK' ) {
4181 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4182 return $this->mLinkHolders
['texts'][$key];
4184 } elseif( $type == 'IWLINK' ) {
4185 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4186 return $this->mInterwikiLinkHolders
['texts'][$key];
4193 * Tag hook handler for 'pre'.
4195 function renderPreTag( $text, $attribs ) {
4196 // Backwards-compatibility hack
4197 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4199 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4200 return wfOpenElement( 'pre', $attribs ) .
4201 Xml
::escapeTagsOnly( $content ) .
4206 * Renders an image gallery from a text with one line per image.
4207 * text labels may be given by using |-style alternative text. E.g.
4208 * Image:one.jpg|The number "1"
4209 * Image:tree.jpg|A tree
4210 * given as text will return the HTML of a gallery with two images,
4211 * labeled 'The number "1"' and
4214 function renderImageGallery( $text, $params ) {
4215 $ig = new ImageGallery();
4216 $ig->setContextTitle( $this->mTitle
);
4217 $ig->setShowBytes( false );
4218 $ig->setShowFilename( false );
4220 $ig->useSkin( $this->mOptions
->getSkin() );
4222 if( isset( $params['caption'] ) ) {
4223 $caption = $params['caption'];
4224 $caption = htmlspecialchars( $caption );
4225 $caption = $this->replaceInternalLinks( $caption );
4226 $ig->setCaptionHtml( $caption );
4228 if( isset( $params['perrow'] ) ) {
4229 $ig->setPerRow( $params['perrow'] );
4231 if( isset( $params['widths'] ) ) {
4232 $ig->setWidths( $params['widths'] );
4234 if( isset( $params['heights'] ) ) {
4235 $ig->setHeights( $params['heights'] );
4238 $lines = explode( "\n", $text );
4239 foreach ( $lines as $line ) {
4240 # match lines like these:
4241 # Image:someimage.jpg|This is some image
4243 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4245 if ( count( $matches ) == 0 ) {
4248 $tp = Title
::newFromText( $matches[1] );
4250 if( is_null( $nt ) ) {
4251 # Bogus title. Ignore these so we don't bomb out later.
4254 if ( isset( $matches[3] ) ) {
4255 $label = $matches[3];
4260 $pout = $this->parse( $label,
4263 false, // Strip whitespace...?
4264 false // Don't clear state!
4266 $html = $pout->getText();
4268 $ig->add( new Image( $nt ), $html );
4270 # Only add real images (bug #5586)
4271 if ( $nt->getNamespace() == NS_IMAGE
) {
4272 $this->mOutput
->addImage( $nt->getDBkey() );
4275 return $ig->toHTML();
4279 * Parse image options text and use it to make an image
4281 function makeImage( $nt, $options ) {
4282 # @TODO: let the MediaHandler specify its transform parameters
4284 # Check if the options text is of the form "options|alt text"
4286 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4287 # * left no resizing, just left align. label is used for alt= only
4288 # * right same, but right aligned
4289 # * none same, but not aligned
4290 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4291 # * center center the image
4292 # * framed Keep original image size, no magnify-button.
4293 # vertical-align values (no % or length right now):
4304 $part = array_map( 'trim', explode( '|', $options) );
4307 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4308 foreach ( $alignments as $alignment ) {
4309 $mwAlign[$alignment] =& MagicWord
::get( 'img_'.$alignment );
4311 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4312 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4313 $mwWidth =& MagicWord
::get( 'img_width' );
4314 $mwFramed =& MagicWord
::get( 'img_framed' );
4315 $mwPage =& MagicWord
::get( 'img_page' );
4319 $framed = $thumb = false;
4320 $manual_thumb = '' ;
4321 $align = $valign = '';
4322 $sk = $this->mOptions
->getSkin();
4324 foreach( $part as $val ) {
4325 if ( !is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4327 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4328 # use manually specified thumbnail
4330 $manual_thumb = $match;
4332 foreach( $alignments as $alignment ) {
4333 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4334 switch ( $alignment ) {
4335 case 'left': case 'right': case 'center': case 'none':
4336 $align = $alignment; break;
4338 $valign = $alignment;
4343 if ( ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4344 # Select a page in a multipage document
4345 $params['page'] = $match;
4346 } elseif ( !isset( $params['width'] ) && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4347 wfDebug( "img_width match: $match\n" );
4348 # $match is the image width in pixels
4350 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4351 $params['width'] = intval( $m[1] );
4352 $params['height'] = intval( $m[2] );
4354 $params['width'] = intval($match);
4356 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4363 # Strip bad stuff out of the alt text
4364 $alt = $this->replaceLinkHoldersText( $caption );
4366 # make sure there are no placeholders in thumbnail attributes
4367 # that are later expanded to html- so expand them now and
4369 $alt = $this->mStripState
->unstripBoth( $alt );
4370 $alt = Sanitizer
::stripAllTags( $alt );
4372 # Linker does the rest
4373 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $params, $framed, $thumb, $manual_thumb, $valign );
4377 * Set a flag in the output object indicating that the content is dynamic and
4378 * shouldn't be cached.
4380 function disableCache() {
4381 wfDebug( "Parser output marked as uncacheable.\n" );
4382 $this->mOutput
->mCacheTime
= -1;
4386 * Callback from the Sanitizer for expanding items found in HTML attribute
4387 * values, so they can be safely tested and escaped.
4388 * @param string $text
4389 * @param array $args
4393 function attributeStripCallback( &$text, $args ) {
4394 $text = $this->replaceVariables( $text, $args );
4395 $text = $this->mStripState
->unstripBoth( $text );
4404 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4405 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4406 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4412 function getTags() { return array_keys( $this->mTagHooks
); }
4417 * Break wikitext input into sections, and either pull or replace
4418 * some particular section's text.
4420 * External callers should use the getSection and replaceSection methods.
4422 * @param $text Page wikitext
4423 * @param $section Numbered section. 0 pulls the text before the first
4424 * heading; other numbers will pull the given section
4425 * along with its lower-level subsections.
4426 * @param $mode One of "get" or "replace"
4427 * @param $newtext Replacement text for section data.
4428 * @return string for "get", the extracted section text.
4429 * for "replace", the whole page with the section replaced.
4431 private function extractSections( $text, $section, $mode, $newtext='' ) {
4432 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4433 # comments to be stripped as well)
4434 $stripState = new StripState
;
4436 $oldOutputType = $this->mOutputType
;
4437 $oldOptions = $this->mOptions
;
4438 $this->mOptions
= new ParserOptions();
4439 $this->setOutputType( OT_WIKI
);
4441 $striptext = $this->strip( $text, $stripState, true );
4443 $this->setOutputType( $oldOutputType );
4444 $this->mOptions
= $oldOptions;
4446 # now that we can be sure that no pseudo-sections are in the source,
4447 # split it up by section
4448 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4449 $comment = "(?:$uniq-!--.*?QINU)";
4454 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4455 (=+) # Should this be limited to 6?
4456 .+? # Section title...
4457 \\2 # Ending = count must match start
4458 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4467 PREG_SPLIT_DELIM_CAPTURE
);
4469 if( $mode == "get" ) {
4470 if( $section == 0 ) {
4471 // "Section 0" returns the content before any other section.
4474 //track missing section, will replace if found.
4477 } elseif( $mode == "replace" ) {
4478 if( $section == 0 ) {
4479 $rv = $newtext . "\n\n";
4488 for( $index = 1; $index < count( $secs ); ) {
4489 $headerLine = $secs[$index++
];
4490 if( $secs[$index] ) {
4492 $headerLevel = strlen( $secs[$index++
] );
4496 $headerLevel = intval( $secs[$index++
] );
4498 $content = $secs[$index++
];
4501 if( $mode == "get" ) {
4502 if( $count == $section ) {
4503 $rv = $headerLine . $content;
4504 $sectionLevel = $headerLevel;
4505 } elseif( $count > $section ) {
4506 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4507 $rv .= $headerLine . $content;
4509 // Broke out to a higher-level section
4513 } elseif( $mode == "replace" ) {
4514 if( $count < $section ) {
4515 $rv .= $headerLine . $content;
4516 } elseif( $count == $section ) {
4517 $rv .= $newtext . "\n\n";
4518 $sectionLevel = $headerLevel;
4519 } elseif( $count > $section ) {
4520 if( $headerLevel <= $sectionLevel ) {
4521 // Passed the section's sub-parts.
4525 $rv .= $headerLine . $content;
4531 # reinsert stripped tags
4532 $rv = trim( $stripState->unstripBoth( $rv ) );
4538 * This function returns the text of a section, specified by a number ($section).
4539 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4540 * the first section before any such heading (section 0).
4542 * If a section contains subsections, these are also returned.
4544 * @param $text String: text to look in
4545 * @param $section Integer: section number
4546 * @param $deftext: default to return if section is not found
4547 * @return string text of the requested section
4549 public function getSection( $text, $section, $deftext='' ) {
4550 return $this->extractSections( $text, $section, "get", $deftext );
4553 public function replaceSection( $oldtext, $section, $text ) {
4554 return $this->extractSections( $oldtext, $section, "replace", $text );
4558 * Get the timestamp associated with the current revision, adjusted for
4559 * the default server-local timestamp
4561 function getRevisionTimestamp() {
4562 if ( is_null( $this->mRevisionTimestamp
) ) {
4563 wfProfileIn( __METHOD__
);
4565 $dbr = wfGetDB( DB_SLAVE
);
4566 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4567 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4569 // Normalize timestamp to internal MW format for timezone processing.
4570 // This has the added side-effect of replacing a null value with
4571 // the current time, which gives us more sensible behavior for
4573 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4575 // The cryptic '' timezone parameter tells to use the site-default
4576 // timezone offset instead of the user settings.
4578 // Since this value will be saved into the parser cache, served
4579 // to other users, and potentially even used inside links and such,
4580 // it needs to be consistent for all visitors.
4581 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4583 wfProfileOut( __METHOD__
);
4585 return $this->mRevisionTimestamp
;
4589 * Mutator for $mDefaultSort
4591 * @param $sort New value
4593 public function setDefaultSort( $sort ) {
4594 $this->mDefaultSort
= $sort;
4598 * Accessor for $mDefaultSort
4599 * Will use the title/prefixed title if none is set
4603 public function getDefaultSort() {
4604 if( $this->mDefaultSort
!== false ) {
4605 return $this->mDefaultSort
;
4607 return $this->mTitle
->getNamespace() == NS_CATEGORY
4608 ?
$this->mTitle
->getText()
4609 : $this->mTitle
->getPrefixedText();
4616 * @todo document, briefly.
4617 * @addtogroup Parser
4619 class OnlyIncludeReplacer
{
4622 function replace( $matches ) {
4623 if ( substr( $matches[1], -1 ) == "\n" ) {
4624 $this->output
.= substr( $matches[1], 0, -1 );
4626 $this->output
.= $matches[1];
4632 * @todo document, briefly.
4633 * @addtogroup Parser
4636 var $general, $nowiki;
4638 function __construct() {
4639 $this->general
= new ReplacementArray
;
4640 $this->nowiki
= new ReplacementArray
;
4643 function unstripGeneral( $text ) {
4644 wfProfileIn( __METHOD__
);
4645 $text = $this->general
->replace( $text );
4646 wfProfileOut( __METHOD__
);
4650 function unstripNoWiki( $text ) {
4651 wfProfileIn( __METHOD__
);
4652 $text = $this->nowiki
->replace( $text );
4653 wfProfileOut( __METHOD__
);
4657 function unstripBoth( $text ) {
4658 wfProfileIn( __METHOD__
);
4659 $text = $this->general
->replace( $text );
4660 $text = $this->nowiki
->replace( $text );
4661 wfProfileOut( __METHOD__
);