5 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are four main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * performs brace substitution on MediaWiki messages
26 * removes HTML comments and expands templates
29 * objects: $wgLang, $wgContLang
31 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
35 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
36 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * * only within ParserOptions
47 * Update this version number when the ParserOutput format
48 * changes in an incompatible way, so the parser cache
49 * can automatically discard old data.
51 const VERSION
= '1.6.2';
53 # Flags for Parser::setFunctionHook
54 # Also available as global constants from Defines.php
55 const SFH_NO_HASH
= 1;
56 const SFH_OBJECT_ARGS
= 2;
58 # Constants needed for external link processing
59 # Everything except bracket, space, or control characters
60 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
61 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
62 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
64 // State constants for the definition list colon extraction
65 const COLON_STATE_TEXT
= 0;
66 const COLON_STATE_TAG
= 1;
67 const COLON_STATE_TAGSTART
= 2;
68 const COLON_STATE_CLOSETAG
= 3;
69 const COLON_STATE_TAGSLASH
= 4;
70 const COLON_STATE_COMMENT
= 5;
71 const COLON_STATE_COMMENTDASH
= 6;
72 const COLON_STATE_COMMENTDASHDASH
= 7;
78 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
79 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
80 $mExtLinkBracketedRegex;
82 # Cleared with clearState():
83 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
84 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
85 var $mInterwikiLinkHolders, $mLinkHolders;
86 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
87 var $mTplExpandCache,// empty-frame expansion cache
88 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
89 // in this path. Used for loop detection.
90 var $mTplRedirCache, $mTplDomCache, $mHeadings;
93 # These are variables reset at least once per parse regardless of $clearState
94 var $mOptions, // ParserOptions object
95 $mTitle, // Title context, used for self-link rendering and similar things
96 $mOutputType, // Output type, one of the OT_xxx constants
97 $ot, // Shortcut alias, see setOutputType()
98 $mRevisionId, // ID to display in {{REVISIONID}} tags
99 $mRevisionTimestamp, // The timestamp of the specified revision ID
100 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
109 function __construct( $conf = array() ) {
110 $this->mTagHooks
= array();
111 $this->mTransparentTagHooks
= array();
112 $this->mFunctionHooks
= array();
113 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
114 $this->mStripList
= array( 'nowiki', 'gallery' );
115 $this->mMarkerSuffix
= "-QINU\x7f";
116 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
117 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
118 $this->mFirstCall
= true;
122 * Do various kinds of initialisation on the first call of the parser
124 function firstCallInit() {
125 if ( !$this->mFirstCall
) {
129 wfProfileIn( __METHOD__
);
130 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
132 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
134 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH
);
135 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
136 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
137 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
138 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
139 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
140 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
141 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
142 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
143 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
144 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
145 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
146 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
147 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
148 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
149 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
150 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
151 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
159 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH
);
162 if ( $wgAllowDisplayTitle ) {
163 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
165 if ( $wgAllowSlowParserFunctions ) {
166 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
169 $this->initialiseVariables();
170 $this->mFirstCall
= false;
171 wfProfileOut( __METHOD__
);
179 function clearState() {
180 wfProfileIn( __METHOD__
);
181 if ( $this->mFirstCall
) {
182 $this->firstCallInit();
184 $this->mOutput
= new ParserOutput
;
185 $this->mAutonumber
= 0;
186 $this->mLastSection
= '';
187 $this->mDTopen
= false;
188 $this->mIncludeCount
= array();
189 $this->mStripState
= new StripState
;
190 $this->mArgStack
= false;
191 $this->mInPre
= false;
192 $this->mInterwikiLinkHolders
= array(
196 $this->mLinkHolders
= array(
197 'namespaces' => array(),
199 'queries' => array(),
203 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
206 * Prefix for temporary replacement strings for the multipass parser.
207 * \x07 should never appear in input as it's disallowed in XML.
208 * Using it at the front also gives us a little extra robustness
209 * since it shouldn't match when butted up against identifier-like
212 * Must not consist of all title characters, or else it will change
213 * the behaviour of <nowiki> in a link.
215 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
216 $this->mUniqPrefix
= "\x7fUNIQ" . Parser
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTemplatePath
= array();
220 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
222 $this->mShowToc
= true;
223 $this->mForceTocPosition
= false;
224 $this->mIncludeSizes
= array(
228 $this->mPPNodeCount
= 0;
229 $this->mDefaultSort
= false;
230 $this->mHeadings
= array();
232 wfRunHooks( 'ParserClearState', array( &$this ) );
233 wfProfileOut( __METHOD__
);
236 function setOutputType( $ot ) {
237 $this->mOutputType
= $ot;
240 'html' => $ot == OT_HTML
,
241 'wiki' => $ot == OT_WIKI
,
242 'msg' => $ot == OT_MSG
,
243 'pre' => $ot == OT_PREPROCESS
,
248 * Accessor for mUniqPrefix.
252 function uniqPrefix() {
253 return $this->mUniqPrefix
;
257 * Convert wikitext to HTML
258 * Do not call this function recursively.
260 * @param string $text Text we want to parse
261 * @param Title &$title A title object
262 * @param array $options
263 * @param boolean $linestart
264 * @param boolean $clearState
265 * @param int $revid number to pass in {{REVISIONID}}
266 * @return ParserOutput a ParserOutput
268 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
270 * First pass--just handle <nowiki> sections, pass the rest off
271 * to internalParse() which does all the real work.
274 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
275 $fname = 'Parser::parse-' . wfGetCaller();
276 wfProfileIn( __METHOD__
);
277 wfProfileIn( $fname );
283 $this->mOptions
= $options;
284 $this->mTitle
=& $title;
285 $oldRevisionId = $this->mRevisionId
;
286 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
287 if( $revid !== null ) {
288 $this->mRevisionId
= $revid;
289 $this->mRevisionTimestamp
= null;
291 $this->setOutputType( OT_HTML
);
292 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
294 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
295 $text = $this->internalParse( $text );
296 $text = $this->mStripState
->unstripGeneral( $text );
298 # Clean up special characters, only run once, next-to-last before doBlockLevels
300 # french spaces, last one Guillemet-left
301 # only if there is something before the space
302 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
303 # french spaces, Guillemet-right
304 '/(\\302\\253) /' => '\\1 ',
306 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
309 $text = $this->doBlockLevels( $text, $linestart );
311 $this->replaceLinkHolders( $text );
313 # the position of the parserConvert() call should not be changed. it
314 # assumes that the links are all replaced and the only thing left
315 # is the <nowiki> mark.
316 # Side-effects: this calls $this->mOutput->setTitleText()
317 $text = $wgContLang->parserConvert( $text, $this );
319 $text = $this->mStripState
->unstripNoWiki( $text );
321 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
323 //!JF Move to its own function
325 $uniq_prefix = $this->mUniqPrefix
;
327 $elements = array_keys( $this->mTransparentTagHooks
);
328 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
330 foreach( $matches as $marker => $data ) {
331 list( $element, $content, $params, $tag ) = $data;
332 $tagName = strtolower( $element );
333 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
334 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
335 array( $content, $params, $this ) );
339 $this->mStripState
->general
->setPair( $marker, $output );
341 $text = $this->mStripState
->unstripGeneral( $text );
343 $text = Sanitizer
::normalizeCharReferences( $text );
345 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
346 $text = Parser
::tidy($text);
348 # attempt to sanitize at least some nesting problems
349 # (bug #2702 and quite a few others)
351 # ''Something [http://www.cool.com cool''] -->
352 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
353 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
354 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
355 # fix up an anchor inside another anchor, only
356 # at least for a single single nested link (bug 3695)
357 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
358 '\\1\\2</a>\\3</a>\\1\\4</a>',
359 # fix div inside inline elements- doBlockLevels won't wrap a line which
360 # contains a div, so fix it up here; replace
361 # div with escaped text
362 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
363 '\\1\\3<div\\5>\\6</div>\\8\\9',
364 # remove empty italic or bold tag pairs, some
365 # introduced by rules above
366 '/<([bi])><\/\\1>/' => '',
369 $text = preg_replace(
370 array_keys( $tidyregs ),
371 array_values( $tidyregs ),
375 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
377 # Information on include size limits, for the benefit of users who try to skirt them
378 if ( max( $this->mIncludeSizes
) > 1000 ) {
379 $max = $this->mOptions
->getMaxIncludeSize();
381 "Preprocessor node count: {$this->mPPNodeCount}\n" .
382 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
383 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
384 "Maximum: $max bytes\n" .
387 $this->mOutput
->setText( $text );
388 $this->mRevisionId
= $oldRevisionId;
389 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
390 wfProfileOut( $fname );
391 wfProfileOut( __METHOD__
);
393 return $this->mOutput
;
397 * Recursive parser entry point that can be called from an extension tag
400 function recursiveTagParse( $text ) {
401 wfProfileIn( __METHOD__
);
402 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
403 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
404 $text = $this->internalParse( $text );
405 wfProfileOut( __METHOD__
);
410 * Expand templates and variables in the text, producing valid, static wikitext.
411 * Also removes comments.
413 function preprocess( $text, $title, $options, $revid = null ) {
414 wfProfileIn( __METHOD__
);
416 $this->setOutputType( OT_PREPROCESS
);
417 $this->mOptions
= $options;
418 $this->mTitle
= $title;
419 if( $revid !== null ) {
420 $this->mRevisionId
= $revid;
422 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
423 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
424 $text = $this->replaceVariables( $text );
425 if ( $this->mOptions
->getRemoveComments() ) {
426 $text = Sanitizer
::removeHTMLcomments( $text );
428 $text = $this->mStripState
->unstripBoth( $text );
429 wfProfileOut( __METHOD__
);
434 * Get a random string
439 function getRandomString() {
440 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
443 function &getTitle() { return $this->mTitle
; }
444 function getOptions() { return $this->mOptions
; }
446 function getFunctionLang() {
447 global $wgLang, $wgContLang;
448 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
452 * Replaces all occurrences of HTML-style comments and the given tags
453 * in the text with a random marker and returns teh next text. The output
454 * parameter $matches will be an associative array filled with data in
456 * 'UNIQ-xxxxx' => array(
459 * array( 'param' => 'x' ),
460 * '<element param="x">tag content</element>' ) )
462 * @param $elements list of element names. Comments are always extracted.
463 * @param $text Source text string.
464 * @param $uniq_prefix
469 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
474 $taglist = implode( '|', $elements );
475 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
477 while ( '' != $text ) {
478 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
480 if( count( $p ) < 5 ) {
483 if( count( $p ) > 5 ) {
497 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
498 $stripped .= $marker;
500 if ( $close === '/>' ) {
501 // Empty element tag, <tag />
506 if( $element == '!--' ) {
509 $end = "/(<\\/$element\\s*>)/i";
511 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
513 if( count( $q ) < 3 ) {
514 # No end tag -- let it run out to the end of the text.
523 $matches[$marker] = array( $element,
525 Sanitizer
::decodeTagAttributes( $attributes ),
526 "<$element$attributes$close$content$tail" );
532 * Get a list of strippable XML-like elements
534 function getStripList() {
536 $elements = $this->mStripList
;
538 $elements[] = 'html';
540 if( $this->mOptions
->getUseTeX() ) {
541 $elements[] = 'math';
547 * @deprecated use replaceVariables
549 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
554 * Restores pre, math, and other extensions removed by strip()
556 * always call unstripNoWiki() after this one
558 * @deprecated use $this->mStripState->unstrip()
560 function unstrip( $text, $state ) {
561 return $state->unstripGeneral( $text );
565 * Always call this after unstrip() to preserve the order
568 * @deprecated use $this->mStripState->unstrip()
570 function unstripNoWiki( $text, $state ) {
571 return $state->unstripNoWiki( $text );
575 * @deprecated use $this->mStripState->unstripBoth()
577 function unstripForHTML( $text ) {
578 return $this->mStripState
->unstripBoth( $text );
582 * Add an item to the strip state
583 * Returns the unique tag which must be inserted into the stripped text
584 * The tag will be replaced with the original text in unstrip()
588 function insertStripItem( $text ) {
590 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
591 $this->mStripState
->general
->setPair( $rnd, $text );
596 * Interface with html tidy, used if $wgUseTidy = true.
597 * If tidy isn't able to correct the markup, the original will be
598 * returned in all its glory with a warning comment appended.
600 * Either the external tidy program or the in-process tidy extension
601 * will be used depending on availability. Override the default
602 * $wgTidyInternal setting to disable the internal if it's not working.
604 * @param string $text Hideous HTML input
605 * @return string Corrected HTML output
609 function tidy( $text ) {
610 global $wgTidyInternal;
611 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
612 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
613 '<head><title>test</title></head><body>'.$text.'</body></html>';
614 if( $wgTidyInternal ) {
615 $correctedtext = Parser
::internalTidy( $wrappedtext );
617 $correctedtext = Parser
::externalTidy( $wrappedtext );
619 if( is_null( $correctedtext ) ) {
620 wfDebug( "Tidy error detected!\n" );
621 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
623 return $correctedtext;
627 * Spawn an external HTML tidy process and get corrected markup back from it.
632 function externalTidy( $text ) {
633 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
634 $fname = 'Parser::externalTidy';
635 wfProfileIn( $fname );
640 $descriptorspec = array(
641 0 => array('pipe', 'r'),
642 1 => array('pipe', 'w'),
643 2 => array('file', wfGetNull(), 'a')
646 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
647 if (is_resource($process)) {
648 // Theoretically, this style of communication could cause a deadlock
649 // here. If the stdout buffer fills up, then writes to stdin could
650 // block. This doesn't appear to happen with tidy, because tidy only
651 // writes to stdout after it's finished reading from stdin. Search
652 // for tidyParseStdin and tidySaveStdout in console/tidy.c
653 fwrite($pipes[0], $text);
655 while (!feof($pipes[1])) {
656 $cleansource .= fgets($pipes[1], 1024);
659 proc_close($process);
662 wfProfileOut( $fname );
664 if( $cleansource == '' && $text != '') {
665 // Some kind of error happened, so we couldn't get the corrected text.
666 // Just give up; we'll use the source text and append a warning.
674 * Use the HTML tidy PECL extension to use the tidy library in-process,
675 * saving the overhead of spawning a new process.
677 * 'pear install tidy' should be able to compile the extension module.
682 function internalTidy( $text ) {
683 global $wgTidyConf, $IP;
684 $fname = 'Parser::internalTidy';
685 wfProfileIn( $fname );
688 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
689 $tidy->cleanRepair();
690 if( $tidy->getStatus() == 2 ) {
691 // 2 is magic number for fatal error
692 // http://www.php.net/manual/en/function.tidy-get-status.php
695 $cleansource = tidy_get_output( $tidy );
697 wfProfileOut( $fname );
702 * parse the wiki syntax used to render tables
706 function doTableStuff ( $text ) {
707 $fname = 'Parser::doTableStuff';
708 wfProfileIn( $fname );
710 $lines = explode ( "\n" , $text );
711 $td_history = array (); // Is currently a td tag open?
712 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
713 $tr_history = array (); // Is currently a tr tag open?
714 $tr_attributes = array (); // history of tr attributes
715 $has_opened_tr = array(); // Did this table open a <tr> element?
716 $indent_level = 0; // indent level of the table
717 foreach ( $lines as $key => $line )
719 $line = trim ( $line );
721 if( $line == '' ) { // empty line, go to next line
724 $first_character = $line{0};
727 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
728 // First check if we are starting a new table
729 $indent_level = strlen( $matches[1] );
731 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
732 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
734 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
735 array_push ( $td_history , false );
736 array_push ( $last_tag_history , '' );
737 array_push ( $tr_history , false );
738 array_push ( $tr_attributes , '' );
739 array_push ( $has_opened_tr , false );
740 } else if ( count ( $td_history ) == 0 ) {
741 // Don't do any of the following
743 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
744 // We are ending a table
745 $line = '</table>' . substr ( $line , 2 );
746 $last_tag = array_pop ( $last_tag_history );
748 if ( !array_pop ( $has_opened_tr ) ) {
749 $line = "<tr><td></td></tr>{$line}";
752 if ( array_pop ( $tr_history ) ) {
753 $line = "</tr>{$line}";
756 if ( array_pop ( $td_history ) ) {
757 $line = "</{$last_tag}>{$line}";
759 array_pop ( $tr_attributes );
760 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
761 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
762 // Now we have a table row
763 $line = preg_replace( '#^\|-+#', '', $line );
765 // Whats after the tag is now only attributes
766 $attributes = $this->mStripState
->unstripBoth( $line );
767 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
768 array_pop ( $tr_attributes );
769 array_push ( $tr_attributes , $attributes );
772 $last_tag = array_pop ( $last_tag_history );
773 array_pop ( $has_opened_tr );
774 array_push ( $has_opened_tr , true );
776 if ( array_pop ( $tr_history ) ) {
780 if ( array_pop ( $td_history ) ) {
781 $line = "</{$last_tag}>{$line}";
784 $lines[$key] = $line;
785 array_push ( $tr_history , false );
786 array_push ( $td_history , false );
787 array_push ( $last_tag_history , '' );
789 else if ( $first_character == '|' ||
$first_character == '!' ||
substr ( $line , 0 , 2 ) == '|+' ) {
790 // This might be cell elements, td, th or captions
791 if ( substr ( $line , 0 , 2 ) == '|+' ) {
792 $first_character = '+';
793 $line = substr ( $line , 1 );
796 $line = substr ( $line , 1 );
798 if ( $first_character == '!' ) {
799 $line = str_replace ( '!!' , '||' , $line );
802 // Split up multiple cells on the same line.
803 // FIXME : This can result in improper nesting of tags processed
804 // by earlier parser steps, but should avoid splitting up eg
805 // attribute values containing literal "||".
806 $cells = StringUtils
::explodeMarkup( '||' , $line );
810 // Loop through each table cell
811 foreach ( $cells as $cell )
814 if ( $first_character != '+' )
816 $tr_after = array_pop ( $tr_attributes );
817 if ( !array_pop ( $tr_history ) ) {
818 $previous = "<tr{$tr_after}>\n";
820 array_push ( $tr_history , true );
821 array_push ( $tr_attributes , '' );
822 array_pop ( $has_opened_tr );
823 array_push ( $has_opened_tr , true );
826 $last_tag = array_pop ( $last_tag_history );
828 if ( array_pop ( $td_history ) ) {
829 $previous = "</{$last_tag}>{$previous}";
832 if ( $first_character == '|' ) {
834 } else if ( $first_character == '!' ) {
836 } else if ( $first_character == '+' ) {
837 $last_tag = 'caption';
842 array_push ( $last_tag_history , $last_tag );
844 // A cell could contain both parameters and data
845 $cell_data = explode ( '|' , $cell , 2 );
847 // Bug 553: Note that a '|' inside an invalid link should not
848 // be mistaken as delimiting cell parameters
849 if ( strpos( $cell_data[0], '[[' ) !== false ) {
850 $cell = "{$previous}<{$last_tag}>{$cell}";
851 } else if ( count ( $cell_data ) == 1 )
852 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
854 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
855 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
856 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
859 $lines[$key] .= $cell;
860 array_push ( $td_history , true );
865 // Closing open td, tr && table
866 while ( count ( $td_history ) > 0 )
868 if ( array_pop ( $td_history ) ) {
871 if ( array_pop ( $tr_history ) ) {
874 if ( !array_pop ( $has_opened_tr ) ) {
875 $lines[] = "<tr><td></td></tr>" ;
878 $lines[] = '</table>' ;
881 $output = implode ( "\n" , $lines ) ;
883 // special case: don't return empty table
884 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
888 wfProfileOut( $fname );
894 * Helper function for parse() that transforms wiki markup into
895 * HTML. Only called for $mOutputType == OT_HTML.
899 function internalParse( $text ) {
901 $fname = 'Parser::internalParse';
902 wfProfileIn( $fname );
904 # Hook to suspend the parser in this state
905 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
906 wfProfileOut( $fname );
910 # Remove <noinclude> tags and <includeonly> sections
911 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
912 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
913 $text = StringUtils
::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
915 $text = $this->replaceVariables( $text );
916 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
917 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
919 // Tables need to come after variable replacement for things to work
920 // properly; putting them before other transformations should keep
921 // exciting things like link expansions from showing up in surprising
923 $text = $this->doTableStuff( $text );
925 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
927 $text = $this->stripToc( $text );
928 $this->stripNoGallery( $text );
929 $text = $this->doHeadings( $text );
930 if($this->mOptions
->getUseDynamicDates()) {
931 $df =& DateFormatter
::getInstance();
932 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
934 $text = $this->doAllQuotes( $text );
935 $text = $this->replaceInternalLinks( $text );
936 $text = $this->replaceExternalLinks( $text );
938 # replaceInternalLinks may sometimes leave behind
939 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
940 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
942 $text = $this->doMagicLinks( $text );
943 $text = $this->formatHeadings( $text, $isMain );
945 wfProfileOut( $fname );
950 * Replace special strings like "ISBN xxx" and "RFC xxx" with
951 * magic external links.
955 function doMagicLinks( $text ) {
956 wfProfileIn( __METHOD__
);
957 $text = preg_replace_callback(
959 <a.*?</a> | # Skip link text
960 <.*?> | # Skip stuff inside HTML elements
961 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
962 ISBN\s+(\b # ISBN, capture number as m[2]
963 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
964 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
965 [0-9Xx] # check digit
967 )!x', array( &$this, 'magicLinkCallback' ), $text );
968 wfProfileOut( __METHOD__
);
972 function magicLinkCallback( $m ) {
973 if ( substr( $m[0], 0, 1 ) == '<' ) {
976 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
978 $num = strtr( $isbn, array(
983 $titleObj = SpecialPage
::getTitleFor( 'Booksources' );
984 $text = '<a href="' .
985 $titleObj->escapeLocalUrl( "isbn=$num" ) .
986 "\" class=\"internal\">ISBN $isbn</a>";
988 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
992 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
994 $urlmsg = 'pubmedurl';
997 throw new MWException( __METHOD__
.': unrecognised match type "' .
998 substr($m[0], 0, 20 ) . '"' );
1001 $url = wfMsg( $urlmsg, $id);
1002 $sk = $this->mOptions
->getSkin();
1003 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1004 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1010 * Parse headers and return html
1014 function doHeadings( $text ) {
1015 $fname = 'Parser::doHeadings';
1016 wfProfileIn( $fname );
1017 for ( $i = 6; $i >= 1; --$i ) {
1018 $h = str_repeat( '=', $i );
1019 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1020 "<h$i>\\1</h$i>", $text );
1022 wfProfileOut( $fname );
1027 * Replace single quotes with HTML markup
1029 * @return string the altered text
1031 function doAllQuotes( $text ) {
1032 $fname = 'Parser::doAllQuotes';
1033 wfProfileIn( $fname );
1035 $lines = explode( "\n", $text );
1036 foreach ( $lines as $line ) {
1037 $outtext .= $this->doQuotes ( $line ) . "\n";
1039 $outtext = substr($outtext, 0,-1);
1040 wfProfileOut( $fname );
1045 * Helper function for doAllQuotes()
1047 public function doQuotes( $text ) {
1048 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1049 if ( count( $arr ) == 1 )
1053 # First, do some preliminary work. This may shift some apostrophes from
1054 # being mark-up to being text. It also counts the number of occurrences
1055 # of bold and italics mark-ups.
1059 foreach ( $arr as $r )
1061 if ( ( $i %
2 ) == 1 )
1063 # If there are ever four apostrophes, assume the first is supposed to
1064 # be text, and the remaining three constitute mark-up for bold text.
1065 if ( strlen( $arr[$i] ) == 4 )
1070 # If there are more than 5 apostrophes in a row, assume they're all
1071 # text except for the last 5.
1072 else if ( strlen( $arr[$i] ) > 5 )
1074 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1077 # Count the number of occurrences of bold and italics mark-ups.
1078 # We are not counting sequences of five apostrophes.
1079 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1080 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1081 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1086 # If there is an odd number of both bold and italics, it is likely
1087 # that one of the bold ones was meant to be an apostrophe followed
1088 # by italics. Which one we cannot know for certain, but it is more
1089 # likely to be one that has a single-letter word before it.
1090 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1093 $firstsingleletterword = -1;
1094 $firstmultiletterword = -1;
1096 foreach ( $arr as $r )
1098 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1100 $x1 = substr ($arr[$i-1], -1);
1101 $x2 = substr ($arr[$i-1], -2, 1);
1103 if ($firstspace == -1) $firstspace = $i;
1104 } else if ($x2 == ' ') {
1105 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1107 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1113 # If there is a single-letter word, use it!
1114 if ($firstsingleletterword > -1)
1116 $arr [ $firstsingleletterword ] = "''";
1117 $arr [ $firstsingleletterword-1 ] .= "'";
1119 # If not, but there's a multi-letter word, use that one.
1120 else if ($firstmultiletterword > -1)
1122 $arr [ $firstmultiletterword ] = "''";
1123 $arr [ $firstmultiletterword-1 ] .= "'";
1125 # ... otherwise use the first one that has neither.
1126 # (notice that it is possible for all three to be -1 if, for example,
1127 # there is only one pentuple-apostrophe in the line)
1128 else if ($firstspace > -1)
1130 $arr [ $firstspace ] = "''";
1131 $arr [ $firstspace-1 ] .= "'";
1135 # Now let's actually convert our apostrophic mush to HTML!
1140 foreach ($arr as $r)
1144 if ($state == 'both')
1151 if (strlen ($r) == 2)
1154 { $output .= '</i>'; $state = ''; }
1155 else if ($state == 'bi')
1156 { $output .= '</i>'; $state = 'b'; }
1157 else if ($state == 'ib')
1158 { $output .= '</b></i><b>'; $state = 'b'; }
1159 else if ($state == 'both')
1160 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1161 else # $state can be 'b' or ''
1162 { $output .= '<i>'; $state .= 'i'; }
1164 else if (strlen ($r) == 3)
1167 { $output .= '</b>'; $state = ''; }
1168 else if ($state == 'bi')
1169 { $output .= '</i></b><i>'; $state = 'i'; }
1170 else if ($state == 'ib')
1171 { $output .= '</b>'; $state = 'i'; }
1172 else if ($state == 'both')
1173 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1174 else # $state can be 'i' or ''
1175 { $output .= '<b>'; $state .= 'b'; }
1177 else if (strlen ($r) == 5)
1180 { $output .= '</b><i>'; $state = 'i'; }
1181 else if ($state == 'i')
1182 { $output .= '</i><b>'; $state = 'b'; }
1183 else if ($state == 'bi')
1184 { $output .= '</i></b>'; $state = ''; }
1185 else if ($state == 'ib')
1186 { $output .= '</b></i>'; $state = ''; }
1187 else if ($state == 'both')
1188 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1189 else # ($state == '')
1190 { $buffer = ''; $state = 'both'; }
1195 # Now close all remaining tags. Notice that the order is important.
1196 if ($state == 'b' ||
$state == 'ib')
1198 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1202 # There might be lonely ''''', so make sure we have a buffer
1203 if ($state == 'both' && $buffer)
1204 $output .= '<b><i>'.$buffer.'</i></b>';
1210 * Replace external links
1212 * Note: this is all very hackish and the order of execution matters a lot.
1213 * Make sure to run maintenance/parserTests.php if you change this code.
1217 function replaceExternalLinks( $text ) {
1219 $fname = 'Parser::replaceExternalLinks';
1220 wfProfileIn( $fname );
1222 $sk = $this->mOptions
->getSkin();
1224 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1226 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1229 while ( $i<count( $bits ) ) {
1231 $protocol = $bits[$i++
];
1232 $text = $bits[$i++
];
1233 $trail = $bits[$i++
];
1235 # The characters '<' and '>' (which were escaped by
1236 # removeHTMLtags()) should not be included in
1237 # URLs, per RFC 2396.
1239 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1240 $text = substr($url, $m2[0][1]) . ' ' . $text;
1241 $url = substr($url, 0, $m2[0][1]);
1244 # If the link text is an image URL, replace it with an <img> tag
1245 # This happened by accident in the original parser, but some people used it extensively
1246 $img = $this->maybeMakeExternalImage( $text );
1247 if ( $img !== false ) {
1253 # Set linktype for CSS - if URL==text, link is essentially free
1254 $linktype = ($text == $url) ?
'free' : 'text';
1256 # No link text, e.g. [http://domain.tld/some.link]
1257 if ( $text == '' ) {
1258 # Autonumber if allowed. See bug #5918
1259 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1260 $text = '[' . ++
$this->mAutonumber
. ']';
1261 $linktype = 'autonumber';
1263 # Otherwise just use the URL
1264 $text = htmlspecialchars( $url );
1268 # Have link text, e.g. [http://domain.tld/some.link text]s
1270 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1273 $text = $wgContLang->markNoConversion($text);
1275 $url = Sanitizer
::cleanUrl( $url );
1277 # Process the trail (i.e. everything after this link up until start of the next link),
1278 # replacing any non-bracketed links
1279 $trail = $this->replaceFreeExternalLinks( $trail );
1281 # Use the encoded URL
1282 # This means that users can paste URLs directly into the text
1283 # Funny characters like ö aren't valid in URLs anyway
1284 # This was changed in August 2004
1285 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1287 # Register link in the output object.
1288 # Replace unnecessary URL escape codes with the referenced character
1289 # This prevents spammers from hiding links from the filters
1290 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1291 $this->mOutput
->addExternalLink( $pasteurized );
1294 wfProfileOut( $fname );
1299 * Replace anything that looks like a URL with a link
1302 function replaceFreeExternalLinks( $text ) {
1304 $fname = 'Parser::replaceFreeExternalLinks';
1305 wfProfileIn( $fname );
1307 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1308 $s = array_shift( $bits );
1311 $sk = $this->mOptions
->getSkin();
1313 while ( $i < count( $bits ) ){
1314 $protocol = $bits[$i++
];
1315 $remainder = $bits[$i++
];
1318 if ( preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1319 # Found some characters after the protocol that look promising
1320 $url = $protocol . $m[1];
1323 # special case: handle urls as url args:
1324 # http://www.example.com/foo?=http://www.example.com/bar
1325 if(strlen($trail) == 0 &&
1327 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1328 preg_match( '/^('.self
::EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1331 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1336 # The characters '<' and '>' (which were escaped by
1337 # removeHTMLtags()) should not be included in
1338 # URLs, per RFC 2396.
1340 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1341 $trail = substr($url, $m2[0][1]) . $trail;
1342 $url = substr($url, 0, $m2[0][1]);
1345 # Move trailing punctuation to $trail
1347 # If there is no left bracket, then consider right brackets fair game too
1348 if ( strpos( $url, '(' ) === false ) {
1352 $numSepChars = strspn( strrev( $url ), $sep );
1353 if ( $numSepChars ) {
1354 $trail = substr( $url, -$numSepChars ) . $trail;
1355 $url = substr( $url, 0, -$numSepChars );
1358 $url = Sanitizer
::cleanUrl( $url );
1360 # Is this an external image?
1361 $text = $this->maybeMakeExternalImage( $url );
1362 if ( $text === false ) {
1363 # Not an image, make a link
1364 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1365 # Register it in the output object...
1366 # Replace unnecessary URL escape codes with their equivalent characters
1367 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1368 $this->mOutput
->addExternalLink( $pasteurized );
1370 $s .= $text . $trail;
1372 $s .= $protocol . $remainder;
1375 wfProfileOut( $fname );
1380 * Replace unusual URL escape codes with their equivalent characters
1384 * @todo This can merge genuinely required bits in the path or query string,
1385 * breaking legit URLs. A proper fix would treat the various parts of
1386 * the URL differently; as a workaround, just use the output for
1387 * statistical records, not for actual linking/output.
1389 static function replaceUnusualEscapes( $url ) {
1390 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1391 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1395 * Callback function used in replaceUnusualEscapes().
1396 * Replaces unusual URL escape codes with their equivalent character
1400 private static function replaceUnusualEscapesCallback( $matches ) {
1401 $char = urldecode( $matches[0] );
1402 $ord = ord( $char );
1403 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1404 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1405 // No, shouldn't be escaped
1408 // Yes, leave it escaped
1414 * make an image if it's allowed, either through the global
1415 * option or through the exception
1418 function maybeMakeExternalImage( $url ) {
1419 $sk = $this->mOptions
->getSkin();
1420 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1421 $imagesexception = !empty($imagesfrom);
1423 if ( $this->mOptions
->getAllowExternalImages()
1424 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1425 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1427 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1434 * Process [[ ]] wikilinks
1438 function replaceInternalLinks( $s ) {
1440 static $fname = 'Parser::replaceInternalLinks' ;
1442 wfProfileIn( $fname );
1444 wfProfileIn( $fname.'-setup' );
1446 # the % is needed to support urlencoded titles as well
1447 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1449 $sk = $this->mOptions
->getSkin();
1451 #split the entire text string on occurences of [[
1452 $a = explode( '[[', ' ' . $s );
1453 #get the first element (all text up to first [[), and remove the space we added
1454 $s = array_shift( $a );
1455 $s = substr( $s, 1 );
1457 # Match a link having the form [[namespace:link|alternate]]trail
1459 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1460 # Match cases where there is no "]]", which might still be images
1461 static $e1_img = FALSE;
1462 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1464 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1466 if ( $useLinkPrefixExtension ) {
1467 # Match the end of a line for a word that's not followed by whitespace,
1468 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1469 $e2 = wfMsgForContent( 'linkprefix' );
1472 if( is_null( $this->mTitle
) ) {
1473 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1475 $nottalk = !$this->mTitle
->isTalkPage();
1477 if ( $useLinkPrefixExtension ) {
1479 if ( preg_match( $e2, $s, $m ) ) {
1480 $first_prefix = $m[2];
1482 $first_prefix = false;
1488 if($wgContLang->hasVariants()) {
1489 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1491 $selflink = array($this->mTitle
->getPrefixedText());
1493 $useSubpages = $this->areSubpagesAllowed();
1494 wfProfileOut( $fname.'-setup' );
1496 # Loop for each link
1497 for ($k = 0; isset( $a[$k] ); $k++
) {
1499 if ( $useLinkPrefixExtension ) {
1500 wfProfileIn( $fname.'-prefixhandling' );
1501 if ( preg_match( $e2, $s, $m ) ) {
1509 $prefix = $first_prefix;
1510 $first_prefix = false;
1512 wfProfileOut( $fname.'-prefixhandling' );
1515 $might_be_img = false;
1517 wfProfileIn( "$fname-e1" );
1518 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1520 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1521 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1522 # the real problem is with the $e1 regex
1525 # Still some problems for cases where the ] is meant to be outside punctuation,
1526 # and no image is in sight. See bug 2095.
1529 substr( $m[3], 0, 1 ) === ']' &&
1530 strpos($text, '[') !== false
1533 $text .= ']'; # so that replaceExternalLinks($text) works later
1534 $m[3] = substr( $m[3], 1 );
1536 # fix up urlencoded title texts
1537 if( strpos( $m[1], '%' ) !== false ) {
1538 # Should anchors '#' also be rejected?
1539 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1542 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1543 $might_be_img = true;
1545 if ( strpos( $m[1], '%' ) !== false ) {
1546 $m[1] = urldecode($m[1]);
1549 } else { # Invalid form; output directly
1550 $s .= $prefix . '[[' . $line ;
1551 wfProfileOut( "$fname-e1" );
1554 wfProfileOut( "$fname-e1" );
1555 wfProfileIn( "$fname-misc" );
1557 # Don't allow internal links to pages containing
1558 # PROTO: where PROTO is a valid URL protocol; these
1559 # should be external links.
1560 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1561 $s .= $prefix . '[[' . $line ;
1565 # Make subpage if necessary
1566 if( $useSubpages ) {
1567 $link = $this->maybeDoSubpageLink( $m[1], $text );
1572 $noforce = (substr($m[1], 0, 1) != ':');
1574 # Strip off leading ':'
1575 $link = substr($link, 1);
1578 wfProfileOut( "$fname-misc" );
1579 wfProfileIn( "$fname-title" );
1580 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1582 $s .= $prefix . '[[' . $line;
1583 wfProfileOut( "$fname-title" );
1587 $ns = $nt->getNamespace();
1588 $iw = $nt->getInterWiki();
1589 wfProfileOut( "$fname-title" );
1591 if ($might_be_img) { # if this is actually an invalid link
1592 wfProfileIn( "$fname-might_be_img" );
1593 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1595 while (isset ($a[$k+
1]) ) {
1596 #look at the next 'line' to see if we can close it there
1597 $spliced = array_splice( $a, $k +
1, 1 );
1598 $next_line = array_shift( $spliced );
1599 $m = explode( ']]', $next_line, 3 );
1600 if ( count( $m ) == 3 ) {
1601 # the first ]] closes the inner link, the second the image
1603 $text .= "[[{$m[0]}]]{$m[1]}";
1606 } elseif ( count( $m ) == 2 ) {
1607 #if there's exactly one ]] that's fine, we'll keep looking
1608 $text .= "[[{$m[0]}]]{$m[1]}";
1610 #if $next_line is invalid too, we need look no further
1611 $text .= '[[' . $next_line;
1616 # we couldn't find the end of this imageLink, so output it raw
1617 #but don't ignore what might be perfectly normal links in the text we've examined
1618 $text = $this->replaceInternalLinks($text);
1619 $s .= "{$prefix}[[$link|$text";
1620 # note: no $trail, because without an end, there *is* no trail
1621 wfProfileOut( "$fname-might_be_img" );
1624 } else { #it's not an image, so output it raw
1625 $s .= "{$prefix}[[$link|$text";
1626 # note: no $trail, because without an end, there *is* no trail
1627 wfProfileOut( "$fname-might_be_img" );
1630 wfProfileOut( "$fname-might_be_img" );
1633 $wasblank = ( '' == $text );
1634 if( $wasblank ) $text = $link;
1636 # Link not escaped by : , create the various objects
1640 wfProfileIn( "$fname-interwiki" );
1641 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1642 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1643 $s = rtrim($s . $prefix);
1644 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1645 wfProfileOut( "$fname-interwiki" );
1648 wfProfileOut( "$fname-interwiki" );
1650 if ( $ns == NS_IMAGE
) {
1651 wfProfileIn( "$fname-image" );
1652 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1653 # recursively parse links inside the image caption
1654 # actually, this will parse them in any other parameters, too,
1655 # but it might be hard to fix that, and it doesn't matter ATM
1656 $text = $this->replaceExternalLinks($text);
1657 $text = $this->replaceInternalLinks($text);
1659 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1660 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1661 $this->mOutput
->addImage( $nt->getDBkey() );
1663 wfProfileOut( "$fname-image" );
1666 # We still need to record the image's presence on the page
1667 $this->mOutput
->addImage( $nt->getDBkey() );
1669 wfProfileOut( "$fname-image" );
1673 if ( $ns == NS_CATEGORY
) {
1674 wfProfileIn( "$fname-category" );
1675 $s = rtrim($s . "\n"); # bug 87
1678 $sortkey = $this->getDefaultSort();
1682 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1683 $sortkey = str_replace( "\n", '', $sortkey );
1684 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1685 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1688 * Strip the whitespace Category links produce, see bug 87
1689 * @todo We might want to use trim($tmp, "\n") here.
1691 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1693 wfProfileOut( "$fname-category" );
1698 # Self-link checking
1699 if( $nt->getFragment() === '' ) {
1700 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1701 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1706 # Special and Media are pseudo-namespaces; no pages actually exist in them
1707 if( $ns == NS_MEDIA
) {
1708 $link = $sk->makeMediaLinkObj( $nt, $text );
1709 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1710 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1711 $this->mOutput
->addImage( $nt->getDBkey() );
1713 } elseif( $ns == NS_SPECIAL
) {
1714 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1715 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1717 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1720 } elseif( $ns == NS_IMAGE
) {
1721 $img = wfFindFile( $nt );
1723 // Force a blue link if the file exists; may be a remote
1724 // upload on the shared repository, and we want to see its
1725 // auto-generated page.
1726 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1727 $this->mOutput
->addLink( $nt );
1731 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1733 wfProfileOut( $fname );
1738 * Make a link placeholder. The text returned can be later resolved to a real link with
1739 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1740 * parsing of interwiki links, and secondly to allow all existence checks and
1741 * article length checks (for stub links) to be bundled into a single query.
1744 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1745 wfProfileIn( __METHOD__
);
1746 if ( ! is_object($nt) ) {
1748 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1750 # Separate the link trail from the rest of the link
1751 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1753 if ( $nt->isExternal() ) {
1754 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1755 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1756 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1758 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1759 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1760 $this->mLinkHolders
['queries'][] = $query;
1761 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1762 $this->mLinkHolders
['titles'][] = $nt;
1764 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1767 wfProfileOut( __METHOD__
);
1772 * Render a forced-blue link inline; protect against double expansion of
1773 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1774 * Since this little disaster has to split off the trail text to avoid
1775 * breaking URLs in the following text without breaking trails on the
1776 * wiki links, it's been made into a horrible function.
1779 * @param string $text
1780 * @param string $query
1781 * @param string $trail
1782 * @param string $prefix
1783 * @return string HTML-wikitext mix oh yuck
1785 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1786 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1787 $sk = $this->mOptions
->getSkin();
1788 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1789 return $this->armorLinks( $link ) . $trail;
1793 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1794 * going to go through further parsing steps before inline URL expansion.
1796 * In particular this is important when using action=render, which causes
1797 * full URLs to be included.
1799 * Oh man I hate our multi-layer parser!
1801 * @param string more-or-less HTML
1802 * @return string less-or-more HTML with NOPARSE bits
1804 function armorLinks( $text ) {
1805 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1806 "{$this->mUniqPrefix}NOPARSE$1", $text );
1810 * Return true if subpage links should be expanded on this page.
1813 function areSubpagesAllowed() {
1814 # Some namespaces don't allow subpages
1815 global $wgNamespacesWithSubpages;
1816 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1820 * Handle link to subpage if necessary
1821 * @param string $target the source of the link
1822 * @param string &$text the link text, modified as necessary
1823 * @return string the full name of the link
1826 function maybeDoSubpageLink($target, &$text) {
1829 # :Foobar -- override special treatment of prefix (images, language links)
1830 # /Foobar -- convert to CurrentPage/Foobar
1831 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1832 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1833 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1835 $fname = 'Parser::maybeDoSubpageLink';
1836 wfProfileIn( $fname );
1837 $ret = $target; # default return value is no change
1839 # Some namespaces don't allow subpages,
1840 # so only perform processing if subpages are allowed
1841 if( $this->areSubpagesAllowed() ) {
1842 $hash = strpos( $target, '#' );
1843 if( $hash !== false ) {
1844 $suffix = substr( $target, $hash );
1845 $target = substr( $target, 0, $hash );
1850 $target = trim( $target );
1851 # Look at the first character
1852 if( $target != '' && $target{0} == '/' ) {
1853 # / at end means we don't want the slash to be shown
1855 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1856 if( $trailingSlashes ) {
1857 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1859 $noslash = substr( $target, 1 );
1862 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1863 if( '' === $text ) {
1864 $text = $target . $suffix;
1865 } # this might be changed for ugliness reasons
1867 # check for .. subpage backlinks
1869 $nodotdot = $target;
1870 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1872 $nodotdot = substr( $nodotdot, 3 );
1874 if($dotdotcount > 0) {
1875 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1876 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1877 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1878 # / at the end means don't show full path
1879 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1880 $nodotdot = substr( $nodotdot, 0, -1 );
1881 if( '' === $text ) {
1882 $text = $nodotdot . $suffix;
1885 $nodotdot = trim( $nodotdot );
1886 if( $nodotdot != '' ) {
1887 $ret .= '/' . $nodotdot;
1895 wfProfileOut( $fname );
1900 * Used by doBlockLevels()
1903 /* private */ function closeParagraph() {
1905 if ( '' != $this->mLastSection
) {
1906 $result = '</' . $this->mLastSection
. ">\n";
1908 $this->mInPre
= false;
1909 $this->mLastSection
= '';
1912 # getCommon() returns the length of the longest common substring
1913 # of both arguments, starting at the beginning of both.
1915 /* private */ function getCommon( $st1, $st2 ) {
1916 $fl = strlen( $st1 );
1917 $shorter = strlen( $st2 );
1918 if ( $fl < $shorter ) { $shorter = $fl; }
1920 for ( $i = 0; $i < $shorter; ++
$i ) {
1921 if ( $st1{$i} != $st2{$i} ) { break; }
1925 # These next three functions open, continue, and close the list
1926 # element appropriate to the prefix character passed into them.
1928 /* private */ function openList( $char ) {
1929 $result = $this->closeParagraph();
1931 if ( '*' == $char ) { $result .= '<ul><li>'; }
1932 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1933 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1934 else if ( ';' == $char ) {
1935 $result .= '<dl><dt>';
1936 $this->mDTopen
= true;
1938 else { $result = '<!-- ERR 1 -->'; }
1943 /* private */ function nextItem( $char ) {
1944 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1945 else if ( ':' == $char ||
';' == $char ) {
1947 if ( $this->mDTopen
) { $close = '</dt>'; }
1948 if ( ';' == $char ) {
1949 $this->mDTopen
= true;
1950 return $close . '<dt>';
1952 $this->mDTopen
= false;
1953 return $close . '<dd>';
1956 return '<!-- ERR 2 -->';
1959 /* private */ function closeList( $char ) {
1960 if ( '*' == $char ) { $text = '</li></ul>'; }
1961 else if ( '#' == $char ) { $text = '</li></ol>'; }
1962 else if ( ':' == $char ) {
1963 if ( $this->mDTopen
) {
1964 $this->mDTopen
= false;
1965 $text = '</dt></dl>';
1967 $text = '</dd></dl>';
1970 else { return '<!-- ERR 3 -->'; }
1976 * Make lists from lines starting with ':', '*', '#', etc.
1979 * @return string the lists rendered as HTML
1981 function doBlockLevels( $text, $linestart ) {
1982 $fname = 'Parser::doBlockLevels';
1983 wfProfileIn( $fname );
1985 # Parsing through the text line by line. The main thing
1986 # happening here is handling of block-level elements p, pre,
1987 # and making lists from lines starting with * # : etc.
1989 $textLines = explode( "\n", $text );
1991 $lastPrefix = $output = '';
1992 $this->mDTopen
= $inBlockElem = false;
1994 $paragraphStack = false;
1996 if ( !$linestart ) {
1997 $output .= array_shift( $textLines );
1999 foreach ( $textLines as $oLine ) {
2000 $lastPrefixLength = strlen( $lastPrefix );
2001 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2002 $preOpenMatch = preg_match('/<pre/i', $oLine );
2003 if ( !$this->mInPre
) {
2004 # Multiple prefixes may abut each other for nested lists.
2005 $prefixLength = strspn( $oLine, '*#:;' );
2006 $pref = substr( $oLine, 0, $prefixLength );
2009 $pref2 = str_replace( ';', ':', $pref );
2010 $t = substr( $oLine, $prefixLength );
2011 $this->mInPre
= !empty($preOpenMatch);
2013 # Don't interpret any other prefixes in preformatted text
2015 $pref = $pref2 = '';
2020 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2021 # Same as the last item, so no need to deal with nesting or opening stuff
2022 $output .= $this->nextItem( substr( $pref, -1 ) );
2023 $paragraphStack = false;
2025 if ( substr( $pref, -1 ) == ';') {
2026 # The one nasty exception: definition lists work like this:
2027 # ; title : definition text
2028 # So we check for : in the remainder text to split up the
2029 # title and definition, without b0rking links.
2031 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2033 $output .= $term . $this->nextItem( ':' );
2036 } elseif( $prefixLength ||
$lastPrefixLength ) {
2037 # Either open or close a level...
2038 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2039 $paragraphStack = false;
2041 while( $commonPrefixLength < $lastPrefixLength ) {
2042 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2043 --$lastPrefixLength;
2045 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2046 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2048 while ( $prefixLength > $commonPrefixLength ) {
2049 $char = substr( $pref, $commonPrefixLength, 1 );
2050 $output .= $this->openList( $char );
2052 if ( ';' == $char ) {
2053 # FIXME: This is dupe of code above
2054 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2056 $output .= $term . $this->nextItem( ':' );
2059 ++
$commonPrefixLength;
2061 $lastPrefix = $pref2;
2063 if( 0 == $prefixLength ) {
2064 wfProfileIn( "$fname-paragraph" );
2065 # No prefix (not in list)--go to paragraph mode
2066 // XXX: use a stack for nestable elements like span, table and div
2067 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2068 $closematch = preg_match(
2069 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2070 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2071 if ( $openmatch or $closematch ) {
2072 $paragraphStack = false;
2073 #Â TODO bug 5718: paragraph closed
2074 $output .= $this->closeParagraph();
2075 if ( $preOpenMatch and !$preCloseMatch ) {
2076 $this->mInPre
= true;
2078 if ( $closematch ) {
2079 $inBlockElem = false;
2081 $inBlockElem = true;
2083 } else if ( !$inBlockElem && !$this->mInPre
) {
2084 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2086 if ($this->mLastSection
!= 'pre') {
2087 $paragraphStack = false;
2088 $output .= $this->closeParagraph().'<pre>';
2089 $this->mLastSection
= 'pre';
2091 $t = substr( $t, 1 );
2094 if ( '' == trim($t) ) {
2095 if ( $paragraphStack ) {
2096 $output .= $paragraphStack.'<br />';
2097 $paragraphStack = false;
2098 $this->mLastSection
= 'p';
2100 if ($this->mLastSection
!= 'p' ) {
2101 $output .= $this->closeParagraph();
2102 $this->mLastSection
= '';
2103 $paragraphStack = '<p>';
2105 $paragraphStack = '</p><p>';
2109 if ( $paragraphStack ) {
2110 $output .= $paragraphStack;
2111 $paragraphStack = false;
2112 $this->mLastSection
= 'p';
2113 } else if ($this->mLastSection
!= 'p') {
2114 $output .= $this->closeParagraph().'<p>';
2115 $this->mLastSection
= 'p';
2120 wfProfileOut( "$fname-paragraph" );
2122 // somewhere above we forget to get out of pre block (bug 785)
2123 if($preCloseMatch && $this->mInPre
) {
2124 $this->mInPre
= false;
2126 if ($paragraphStack === false) {
2130 while ( $prefixLength ) {
2131 $output .= $this->closeList( $pref2{$prefixLength-1} );
2134 if ( '' != $this->mLastSection
) {
2135 $output .= '</' . $this->mLastSection
. '>';
2136 $this->mLastSection
= '';
2139 wfProfileOut( $fname );
2144 * Split up a string on ':', ignoring any occurences inside tags
2145 * to prevent illegal overlapping.
2146 * @param string $str the string to split
2147 * @param string &$before set to everything before the ':'
2148 * @param string &$after set to everything after the ':'
2149 * return string the position of the ':', or false if none found
2151 function findColonNoLinks($str, &$before, &$after) {
2152 $fname = 'Parser::findColonNoLinks';
2153 wfProfileIn( $fname );
2155 $pos = strpos( $str, ':' );
2156 if( $pos === false ) {
2158 wfProfileOut( $fname );
2162 $lt = strpos( $str, '<' );
2163 if( $lt === false ||
$lt > $pos ) {
2164 // Easy; no tag nesting to worry about
2165 $before = substr( $str, 0, $pos );
2166 $after = substr( $str, $pos+
1 );
2167 wfProfileOut( $fname );
2171 // Ugly state machine to walk through avoiding tags.
2172 $state = self
::COLON_STATE_TEXT
;
2174 $len = strlen( $str );
2175 for( $i = 0; $i < $len; $i++
) {
2179 // (Using the number is a performance hack for common cases)
2180 case 0: // self::COLON_STATE_TEXT:
2183 // Could be either a <start> tag or an </end> tag
2184 $state = self
::COLON_STATE_TAGSTART
;
2189 $before = substr( $str, 0, $i );
2190 $after = substr( $str, $i +
1 );
2191 wfProfileOut( $fname );
2194 // Embedded in a tag; don't break it.
2197 // Skip ahead looking for something interesting
2198 $colon = strpos( $str, ':', $i );
2199 if( $colon === false ) {
2200 // Nothing else interesting
2201 wfProfileOut( $fname );
2204 $lt = strpos( $str, '<', $i );
2205 if( $stack === 0 ) {
2206 if( $lt === false ||
$colon < $lt ) {
2208 $before = substr( $str, 0, $colon );
2209 $after = substr( $str, $colon +
1 );
2210 wfProfileOut( $fname );
2214 if( $lt === false ) {
2215 // Nothing else interesting to find; abort!
2216 // We're nested, but there's no close tags left. Abort!
2219 // Skip ahead to next tag start
2221 $state = self
::COLON_STATE_TAGSTART
;
2224 case 1: // self::COLON_STATE_TAG:
2229 $state = self
::COLON_STATE_TEXT
;
2232 // Slash may be followed by >?
2233 $state = self
::COLON_STATE_TAGSLASH
;
2239 case 2: // self::COLON_STATE_TAGSTART:
2242 $state = self
::COLON_STATE_CLOSETAG
;
2245 $state = self
::COLON_STATE_COMMENT
;
2248 // Illegal early close? This shouldn't happen D:
2249 $state = self
::COLON_STATE_TEXT
;
2252 $state = self
::COLON_STATE_TAG
;
2255 case 3: // self::COLON_STATE_CLOSETAG:
2260 wfDebug( "Invalid input in $fname; too many close tags\n" );
2261 wfProfileOut( $fname );
2264 $state = self
::COLON_STATE_TEXT
;
2267 case self
::COLON_STATE_TAGSLASH
:
2269 // Yes, a self-closed tag <blah/>
2270 $state = self
::COLON_STATE_TEXT
;
2272 // Probably we're jumping the gun, and this is an attribute
2273 $state = self
::COLON_STATE_TAG
;
2276 case 5: // self::COLON_STATE_COMMENT:
2278 $state = self
::COLON_STATE_COMMENTDASH
;
2281 case self
::COLON_STATE_COMMENTDASH
:
2283 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2285 $state = self
::COLON_STATE_COMMENT
;
2288 case self
::COLON_STATE_COMMENTDASHDASH
:
2290 $state = self
::COLON_STATE_TEXT
;
2292 $state = self
::COLON_STATE_COMMENT
;
2296 throw new MWException( "State machine error in $fname" );
2300 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2303 wfProfileOut( $fname );
2308 * Return value of a magic variable (like PAGENAME)
2312 function getVariableValue( $index ) {
2313 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2316 * Some of these require message or data lookups and can be
2317 * expensive to check many times.
2319 static $varCache = array();
2320 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2321 if ( isset( $varCache[$index] ) ) {
2322 return $varCache[$index];
2327 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2330 global $wgLocaltimezone;
2331 if ( isset( $wgLocaltimezone ) ) {
2332 $oldtz = getenv( 'TZ' );
2333 putenv( 'TZ='.$wgLocaltimezone );
2336 wfSuppressWarnings(); // E_STRICT system time bitching
2337 $localTimestamp = date( 'YmdHis', $ts );
2338 $localMonth = date( 'm', $ts );
2339 $localMonthName = date( 'n', $ts );
2340 $localDay = date( 'j', $ts );
2341 $localDay2 = date( 'd', $ts );
2342 $localDayOfWeek = date( 'w', $ts );
2343 $localWeek = date( 'W', $ts );
2344 $localYear = date( 'Y', $ts );
2345 $localHour = date( 'H', $ts );
2346 if ( isset( $wgLocaltimezone ) ) {
2347 putenv( 'TZ='.$oldtz );
2349 wfRestoreWarnings();
2352 case 'currentmonth':
2353 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2354 case 'currentmonthname':
2355 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2356 case 'currentmonthnamegen':
2357 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2358 case 'currentmonthabbrev':
2359 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2361 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2363 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2365 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2366 case 'localmonthname':
2367 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2368 case 'localmonthnamegen':
2369 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2370 case 'localmonthabbrev':
2371 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2373 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2375 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2377 return wfEscapeWikiText( $this->mTitle
->getText() );
2379 return $this->mTitle
->getPartialURL();
2380 case 'fullpagename':
2381 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2382 case 'fullpagenamee':
2383 return $this->mTitle
->getPrefixedURL();
2385 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2386 case 'subpagenamee':
2387 return $this->mTitle
->getSubpageUrlForm();
2388 case 'basepagename':
2389 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2390 case 'basepagenamee':
2391 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2392 case 'talkpagename':
2393 if( $this->mTitle
->canTalk() ) {
2394 $talkPage = $this->mTitle
->getTalkPage();
2395 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2399 case 'talkpagenamee':
2400 if( $this->mTitle
->canTalk() ) {
2401 $talkPage = $this->mTitle
->getTalkPage();
2402 return $talkPage->getPrefixedUrl();
2406 case 'subjectpagename':
2407 $subjPage = $this->mTitle
->getSubjectPage();
2408 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2409 case 'subjectpagenamee':
2410 $subjPage = $this->mTitle
->getSubjectPage();
2411 return $subjPage->getPrefixedUrl();
2413 // Let the edit saving system know we should parse the page
2414 // *after* a revision ID has been assigned.
2415 $this->mOutput
->setFlag( 'vary-revision' );
2416 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2417 return $this->mRevisionId
;
2419 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2420 case 'revisionday2':
2421 return substr( $this->getRevisionTimestamp(), 6, 2 );
2422 case 'revisionmonth':
2423 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2424 case 'revisionyear':
2425 return substr( $this->getRevisionTimestamp(), 0, 4 );
2426 case 'revisiontimestamp':
2427 return $this->getRevisionTimestamp();
2429 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2431 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2433 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2435 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2436 case 'subjectspace':
2437 return $this->mTitle
->getSubjectNsText();
2438 case 'subjectspacee':
2439 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2440 case 'currentdayname':
2441 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2443 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2445 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2447 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2449 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2450 // int to remove the padding
2451 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2453 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2454 case 'localdayname':
2455 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2457 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2459 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2461 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2463 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2464 // int to remove the padding
2465 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2467 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2468 case 'numberofarticles':
2469 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2470 case 'numberoffiles':
2471 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::images() );
2472 case 'numberofusers':
2473 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::users() );
2474 case 'numberofpages':
2475 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2476 case 'numberofadmins':
2477 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::admins() );
2478 case 'numberofedits':
2479 return $varCache[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2480 case 'currenttimestamp':
2481 return $varCache[$index] = wfTimestampNow();
2482 case 'localtimestamp':
2483 return $varCache[$index] = $localTimestamp;
2484 case 'currentversion':
2485 return $varCache[$index] = SpecialVersion
::getVersion();
2491 return $wgServerName;
2493 return $wgScriptPath;
2494 case 'directionmark':
2495 return $wgContLang->getDirMark();
2496 case 'contentlanguage':
2497 global $wgContLanguageCode;
2498 return $wgContLanguageCode;
2501 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2509 * initialise the magic variables (like CURRENTMONTHNAME)
2513 function initialiseVariables() {
2514 $fname = 'Parser::initialiseVariables';
2515 wfProfileIn( $fname );
2516 $variableIDs = MagicWord
::getVariableIDs();
2518 $this->mVariables
= new MagicWordArray( $variableIDs );
2519 wfProfileOut( $fname );
2523 * Parse any parentheses in format ((title|part|part)} and return the document tree
2524 * This is the ghost of replace_variables().
2526 * @param string $text The text to parse
2529 function preprocessToDom ( $text ) {
2530 wfProfileIn( __METHOD__
);
2531 wfProfileIn( __METHOD__
.'-makexml' );
2533 static $msgRules, $normalRules;
2546 'names' => array( 2 => null ),
2551 $normalRules = array(
2563 'names' => array( 2 => null ),
2569 if ( $this->ot
['msg'] ) {
2572 $rules = $normalRules;
2575 $extElements = implode( '|', $this->getStripList() );
2576 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
2577 $extElementsRegex = "/($extElements)(?:\s|\/>|>)|(!--)/iA";
2579 $stack = array(); # Stack of unclosed parentheses
2580 $stackIndex = -1; # Stack read pointer
2582 $searchBase = implode( '', array_keys( $rules ) ) . '<';
2584 $i = -1; # Input pointer, starts out pointing to a pseudo-newline before the start
2585 $topAccum = '<root>'; # Top level text accumulator
2586 $accum =& $topAccum; # Current text accumulator
2587 $findEquals = false; # True to find equals signs in arguments
2588 $findHeading = false; # True to look at LF characters for possible headings
2589 $findPipe = false; # True to take notice of pipe characters
2591 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
2593 while ( $i < strlen( $text ) ) {
2595 $found = 'line-start';
2598 # Find next opening brace, closing brace or pipe
2599 $search = $searchBase;
2600 if ( $stackIndex == -1 ) {
2601 $currentClosing = '';
2602 // Look for headings only at the top stack level
2603 // Among other things, this resolves the ambiguity between =
2604 // for headings and = for template arguments
2607 $currentClosing = $stack[$stackIndex]['close'];
2608 $search .= $currentClosing;
2613 if ( $findEquals ) {
2617 # Output literal section, advance input counter
2618 $literalLength = strcspn( $text, $search, $i );
2619 if ( $literalLength > 0 ) {
2620 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
2621 $i +
= $literalLength;
2623 if ( $i >= strlen( $text ) ) {
2624 if ( $currentClosing == "\n" ) {
2625 // Do a past-the-end run to finish off the heading
2627 $found = 'line-end';
2633 $curChar = $text[$i];
2634 if ( $curChar == '|' ) {
2636 } elseif ( $curChar == '=' ) {
2638 } elseif ( $curChar == '<' ) {
2640 } elseif ( $curChar == "\n" ) {
2641 if ( $stackIndex == -1 ) {
2642 $found = 'line-start';
2644 $found = 'line-end';
2646 } elseif ( $curChar == $currentClosing ) {
2648 } elseif ( isset( $rules[$curChar] ) ) {
2650 $rule = $rules[$curChar];
2652 # Some versions of PHP have a strcspn which stops on null characters
2653 # Ignore and continue
2660 if ( $found == 'angle' ) {
2662 // Determine element name
2663 if ( !preg_match( $extElementsRegex, $text, $matches, 0, $i +
1 ) ) {
2664 // Element name missing or not listed
2670 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
2671 // HTML comment, scan to end
2672 $endpos = strpos( $text, '-->', $i +
4 );
2673 if ( $endpos === false ) {
2674 // Unclosed comment in input, runs to end
2675 $accum .= htmlspecialchars( substr( $text, $i ) );
2676 if ( $this->ot
['html'] ) {
2677 // Close it so later stripping can remove it
2678 $accum .= htmlspecialchars( '-->' );
2680 $i = strlen( $text );
2683 $accum .= htmlspecialchars( substr( $text, $i, $endpos - $i +
3 ) );
2684 #$inner = substr( $text, $i + 4, $endpos - $i - 4 );
2685 #$accum .= '<ext><name>!--</name><inner>' . htmlspecialchars( $inner ) . '</inner></ext>';
2689 $name = $matches[1];
2690 $attrStart = $i +
strlen( $name ) +
1;
2693 $tagEndPos = $noMoreGT ?
false : strpos( $text, '>', $attrStart );
2694 if ( $tagEndPos === false ) {
2695 // Infinite backtrack
2696 // Disable tag search to prevent worst-case O(N^2) performance
2702 if ( $text[$tagEndPos-1] == '/' ) {
2703 $attrEnd = $tagEndPos - 1;
2705 $i = $tagEndPos +
1;
2708 $attrEnd = $tagEndPos;
2710 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE
, $tagEndPos +
1 ) ) {
2711 $inner = substr( $text, $tagEndPos +
1, $matches[0][1] - $tagEndPos - 1 );
2712 $i = $matches[0][1] +
strlen( $matches[0][0] );
2713 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
2715 // No end tag -- let it run out to the end of the text.
2716 $inner = substr( $text, $tagEndPos +
1 );
2717 $i = strlen( $text );
2722 if ( $attrEnd <= $attrStart ) {
2725 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
2727 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
2728 // Note that the attr element contains the whitespace between name and attribute,
2729 // this is necessary for precise reconstruction during pre-save transform.
2730 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
2731 if ( $inner !== null ) {
2732 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
2734 $accum .= $close . '</ext>';
2737 elseif ( $found == 'line-start' ) {
2738 // Is this the start of a heading?
2739 // Line break belongs before the heading element in any case
2743 $count = strspn( $text, '=', $i, 6 );
2748 'parts' => array( str_repeat( '=', $count ) ),
2749 'count' => $count );
2750 $stack[++
$stackIndex] = $piece;
2752 $accum =& $stack[$stackIndex]['parts'][0];
2757 elseif ( $found == 'line-end' ) {
2758 $piece = $stack[$stackIndex];
2759 // A heading must be open, otherwise \n wouldn't have been in the search list
2760 assert( $piece['open'] == "\n" );
2761 assert( $stackIndex == 0 );
2762 // Search back through the accumulator to see if it has a proper close
2763 // No efficient way to do this in PHP AFAICT: strrev, PCRE search with $ anchor
2764 // and rtrim are all O(N) in total size. Optimal would be O(N) in trailing
2765 // whitespace size only.
2767 $count = $piece['count'];
2768 if ( preg_match( "/(={{$count}})\s*$/", $accum, $m, 0, $count ) ) {
2769 // Found match, output <h>
2770 $count = min( strlen( $m[1] ), $count );
2771 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
2774 // No match, no <h>, just pass down the inner text
2778 // Headings can only occur on the top level, so this is a bit simpler than the
2779 // generic stack unwind operation in the close case
2780 unset( $stack[$stackIndex--] );
2781 $accum =& $topAccum;
2782 $findEquals = false;
2785 // Append the result to the enclosing accumulator
2787 // Note that we do NOT increment the input pointer.
2788 // This is because the closing linebreak could be the opening linebreak of
2789 // another heading. Infinite loops are avoided because the next iteration MUST
2790 // hit the heading open case above, which unconditionally increments the
2794 elseif ( $found == 'open' ) {
2795 # count opening brace characters
2796 $count = strspn( $text, $curChar, $i );
2798 # we need to add to stack only if opening brace count is enough for one of the rules
2799 if ( $count >= $rule['min'] ) {
2800 # Add it to the stack
2803 'close' => $rule['end'],
2805 'parts' => array( '' ),
2807 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
2811 $stack[$stackIndex] = $piece;
2812 $accum =& $stack[$stackIndex]['parts'][0];
2813 $findEquals = false;
2816 # Add literal brace(s)
2817 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2822 elseif ( $found == 'close' ) {
2823 $piece = $stack[$stackIndex];
2824 # lets check if there are enough characters for closing brace
2825 $maxCount = $piece['count'];
2826 $count = strspn( $text, $curChar, $i, $maxCount );
2828 # check for maximum matching characters (if there are 5 closing
2829 # characters, we will probably need only 3 - depending on the rules)
2831 $rule = $rules[$piece['open']];
2832 if ( $count > $rule['max'] ) {
2833 # The specified maximum exists in the callback array, unless the caller
2835 $matchingCount = $rule['max'];
2837 # Count is less than the maximum
2838 # Skip any gaps in the callback array to find the true largest match
2839 # Need to use array_key_exists not isset because the callback can be null
2840 $matchingCount = $count;
2841 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
2846 if ($matchingCount <= 0) {
2847 # No matching element found in callback array
2848 # Output a literal closing brace and continue
2849 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2853 $name = $rule['names'][$matchingCount];
2854 if ( $name === null ) {
2855 // No element, just literal text
2856 $element = str_repeat( $piece['open'], $matchingCount ) .
2857 implode( '|', $piece['parts'] ) .
2858 str_repeat( $rule['end'], $matchingCount );
2860 # Create XML element
2861 # Note: $parts is already XML, does not need to be encoded further
2862 $parts = $piece['parts'];
2866 # The invocation is at the start of the line if lineStart is set in
2867 # the stack, and all opening brackets are used up.
2868 if ( $maxCount == $matchingCount && !empty( $piece['lineStart'] ) ) {
2869 $attr = ' lineStart="1"';
2874 $element = "<$name$attr>";
2875 $element .= "<title>$title</title>";
2877 foreach ( $parts as $partIndex => $part ) {
2878 if ( isset( $piece['eqpos'][$partIndex] ) ) {
2879 $eqpos = $piece['eqpos'][$partIndex];
2880 list( $ws1, $argName, $ws2 ) = self
::splitWhitespace( substr( $part, 0, $eqpos ) );
2881 list( $ws3, $argValue, $ws4 ) = self
::splitWhitespace( substr( $part, $eqpos +
1 ) );
2882 $element .= "<part>$ws1<name>$argName</name>$ws2=$ws3<value>$argValue</value>$ws4</part>";
2884 list( $ws1, $value, $ws2 ) = self
::splitWhitespace( $part );
2885 $element .= "<part>$ws1<name index=\"$argIndex\" /><value>$value</value>$ws2</part>";
2889 $element .= "</$name>";
2892 # Advance input pointer
2893 $i +
= $matchingCount;
2896 unset( $stack[$stackIndex--] );
2897 if ( $stackIndex == -1 ) {
2898 $accum =& $topAccum;
2899 $findEquals = false;
2902 $partCount = count( $stack[$stackIndex]['parts'] );
2903 $accum =& $stack[$stackIndex]['parts'][$partCount - 1];
2904 $findPipe = $stack[$stackIndex]['open'] != "\n";
2905 $findEquals = $findPipe && $partCount > 1
2906 && !isset( $stack[$stackIndex]['eqpos'][$partCount - 1] );
2909 # Re-add the old stack element if it still has unmatched opening characters remaining
2910 if ($matchingCount < $piece['count']) {
2911 $piece['parts'] = array( '' );
2912 $piece['count'] -= $matchingCount;
2913 $piece['eqpos'] = array();
2914 # do we still qualify for any callback with remaining count?
2915 $names = $rules[$piece['open']]['names'];
2917 $enclosingAccum =& $accum;
2918 while ( $piece['count'] ) {
2919 if ( array_key_exists( $piece['count'], $names ) ) {
2921 $stack[$stackIndex] = $piece;
2922 $accum =& $stack[$stackIndex]['parts'][0];
2930 $enclosingAccum .= str_repeat( $piece['open'], $skippedBraces );
2933 # Add XML element to the enclosing accumulator
2937 elseif ( $found == 'pipe' ) {
2938 $stack[$stackIndex]['parts'][] = '';
2939 $partsCount = count( $stack[$stackIndex]['parts'] );
2940 $accum =& $stack[$stackIndex]['parts'][$partsCount - 1];
2945 elseif ( $found == 'equals' ) {
2946 $findEquals = false;
2947 $partsCount = count( $stack[$stackIndex]['parts'] );
2948 $stack[$stackIndex]['eqpos'][$partsCount - 1] = strlen( $accum );
2954 # Output any remaining unclosed brackets
2955 foreach ( $stack as $piece ) {
2956 if ( $piece['open'] == "\n" ) {
2957 $topAccum .= $piece['parts'][0];
2959 $topAccum .= str_repeat( $piece['open'], $piece['count'] ) . implode( '|', $piece['parts'] );
2962 $topAccum .= '</root>';
2964 wfProfileOut( __METHOD__
.'-makexml' );
2965 wfProfileIn( __METHOD__
.'-loadXML' );
2966 $dom = new DOMDocument
;
2967 if ( !$dom->loadXML( $topAccum ) ) {
2968 throw new MWException( __METHOD__
.' generated invalid XML' );
2970 wfProfileOut( __METHOD__
.'-loadXML' );
2971 wfProfileOut( __METHOD__
);
2976 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2978 public static function splitWhitespace( $s ) {
2979 $ltrimmed = ltrim( $s );
2980 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2981 $trimmed = rtrim( $ltrimmed );
2982 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2984 $w2 = substr( $ltrimmed, -$diff );
2988 return array( $w1, $trimmed, $w2 );
2992 * Replace magic variables, templates, and template arguments
2993 * with the appropriate text. Templates are substituted recursively,
2994 * taking care to avoid infinite loops.
2996 * Note that the substitution depends on value of $mOutputType:
2997 * OT_WIKI: only {{subst:}} templates
2998 * OT_MSG: only magic variables
2999 * OT_HTML: all templates and magic variables
3001 * @param string $tex The text to transform
3002 * @param PPFrame $frame Object describing the arguments passed to the template
3003 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3006 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3007 # Prevent too big inclusions
3008 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3012 $fname = __METHOD__
;
3013 wfProfileIn( $fname );
3015 if ( $frame === false ) {
3016 $frame = new PPFrame( $this );
3017 } elseif ( !( $frame instanceof PPFrame
) ) {
3018 throw new MWException( __METHOD__
. ' called using the old argument format' );
3021 $dom = $this->preprocessToDom( $text );
3022 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3023 $text = $frame->expand( $dom, 0, $flags );
3025 wfProfileOut( $fname );
3029 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3030 static function createAssocArgs( $args ) {
3031 $assocArgs = array();
3033 foreach( $args as $arg ) {
3034 $eqpos = strpos( $arg, '=' );
3035 if ( $eqpos === false ) {
3036 $assocArgs[$index++
] = $arg;
3038 $name = trim( substr( $arg, 0, $eqpos ) );
3039 $value = trim( substr( $arg, $eqpos+
1 ) );
3040 if ( $value === false ) {
3043 if ( $name !== false ) {
3044 $assocArgs[$name] = $value;
3053 * Return the text of a template, after recursively
3054 * replacing any variables or templates within the template.
3056 * @param array $piece The parts of the template
3057 * $piece['text']: matched text
3058 * $piece['title']: the title, i.e. the part before the |
3059 * $piece['parts']: the parameter array
3060 * @param PPFrame The current frame, contains template arguments
3061 * @return string the text of the template
3064 function braceSubstitution( $piece, $frame ) {
3065 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
3066 $fname = __METHOD__
;
3067 wfProfileIn( $fname );
3068 wfProfileIn( __METHOD__
.'-setup' );
3071 $found = false; # $text has been filled
3072 $nowiki = false; # wiki markup in $text should be escaped
3073 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
3074 $noargs = false; # Don't replace triple-brace arguments in $text
3075 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3076 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3077 $isDOM = false; # $text is a DOM node needing expansion
3079 # Title object, where $text came from
3082 # $part1 is the bit before the first |, and must contain only title characters.
3083 # Various prefixes will be stripped from it later.
3084 $titleWithSpaces = $frame->expand( $piece['title'] );
3085 $part1 = trim( $titleWithSpaces );
3088 # Original title text preserved for various purposes
3089 $originalTitle = $part1;
3091 # $args is a list of argument nodes, starting from index 0, not including $part1
3092 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
3093 wfProfileOut( __METHOD__
.'-setup' );
3096 wfProfileIn( __METHOD__
.'-modifiers' );
3098 $mwSubst =& MagicWord
::get( 'subst' );
3099 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
3100 # One of two possibilities is true:
3101 # 1) Found SUBST but not in the PST phase
3102 # 2) Didn't find SUBST and in the PST phase
3103 # In either case, return without further processing
3104 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3112 if ( !$found && $args->length
== 0 ) {
3113 $id = $this->mVariables
->matchStartToEnd( $part1 );
3114 if ( $id !== false ) {
3115 $text = $this->getVariableValue( $id );
3116 $this->mOutput
->mContainsOldMagic
= true;
3123 # MSG, MSGNW and RAW
3126 $mwMsgnw =& MagicWord
::get( 'msgnw' );
3127 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3130 # Remove obsolete MSG:
3131 $mwMsg =& MagicWord
::get( 'msg' );
3132 $mwMsg->matchStartAndRemove( $part1 );
3136 $mwRaw =& MagicWord
::get( 'raw' );
3137 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3138 $forceRawInterwiki = true;
3141 wfProfileOut( __METHOD__
.'-modifiers' );
3143 # Save path level before recursing into functions & templates.
3144 $lastPathLevel = $this->mTemplatePath
;
3148 wfProfileIn( __METHOD__
. '-pfunc' );
3150 $colonPos = strpos( $part1, ':' );
3151 if ( $colonPos !== false ) {
3152 # Case sensitive functions
3153 $function = substr( $part1, 0, $colonPos );
3154 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3155 $function = $this->mFunctionSynonyms
[1][$function];
3157 # Case insensitive functions
3158 $function = strtolower( $function );
3159 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3160 $function = $this->mFunctionSynonyms
[0][$function];
3166 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3167 $initialArgs = array( &$this );
3168 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3169 if ( $flags & SFH_OBJECT_ARGS
) {
3170 # Add a frame parameter, and pass the arguments as an array
3171 $allArgs = $initialArgs;
3172 $allArgs[] = $frame;
3173 foreach ( $args as $arg ) {
3176 $allArgs[] = $funcArgs;
3178 # Convert arguments to plain text
3179 foreach ( $args as $arg ) {
3180 $funcArgs[] = trim( $frame->expand( $arg ) );
3182 $allArgs = array_merge( $initialArgs, $funcArgs );
3185 if (! is_callable($callback)) {
3186 if (is_array($callback))
3187 $callback = $callback[0];
3189 die ("\nInvalid callback for $function: '$callback' ($flags)\n");
3192 $result = call_user_func_array( $callback, $allArgs );
3195 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
3199 if ( is_array( $result ) ) {
3200 if ( isset( $result[0] ) ) {
3202 unset( $result[0] );
3205 // Extract flags into the local scope
3206 // This allows callers to set flags such as nowiki, noparse, found, etc.
3213 wfProfileOut( __METHOD__
. '-pfunc' );
3216 # Finish mangling title and then check for loops.
3217 # Set $title to a Title object and $titleText to the PDBK
3220 # Split the title into page and subpage
3222 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3223 if ($subpage !== '') {
3224 $ns = $this->mTitle
->getNamespace();
3226 $title = Title
::newFromText( $part1, $ns );
3228 $titleText = $title->getPrefixedText();
3229 # Check for language variants if the template is not found
3230 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3231 $wgContLang->findVariantLink($part1, $title);
3233 # Do infinite loop check
3234 if ( isset( $this->mTemplatePath
[$titleText] ) ) {
3238 $text = "[[$part1]]" . $this->insertStripItem( '<!-- WARNING: template loop detected -->' );
3239 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3244 # Load from database
3245 if ( !$found && $title ) {
3246 wfProfileIn( __METHOD__
. '-loadtpl' );
3247 if ( !$title->isExternal() ) {
3248 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3249 $text = SpecialPage
::capturePath( $title );
3250 if ( is_string( $text ) ) {
3255 $this->disableCache();
3257 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3258 $found = false; //access denied
3259 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3261 list( $text, $title ) = $this->getTemplateDom( $title );
3262 if ( $text !== false ) {
3268 # If the title is valid but undisplayable, make a link to it
3269 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3270 $text = "[[:$titleText]]";
3273 } elseif ( $title->isTrans() ) {
3274 // Interwiki transclusion
3275 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3276 $text = $this->interwikiTransclude( $title, 'render' );
3280 $text = $this->interwikiTransclude( $title, 'raw' );
3284 wfProfileOut( __METHOD__
. '-loadtpl' );
3287 # Recursive parsing, escaping and link table handling
3288 # Only for HTML output
3289 if ( $nowiki && $found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3291 $text = $frame->expand( $text );
3293 $text = wfEscapeWikiText( $text );
3294 } elseif ( !$this->ot
['msg'] && $found ) {
3296 $newFrame = $frame->newChild();
3298 # Clean up argument array
3299 $newFrame = $frame->newChild( $args, $title );
3300 # Add a new element to the templace recursion path
3301 $this->mTemplatePath
[$titleText] = 1;
3306 if ( $titleText !== false && count( $newFrame->args
) == 0 ) {
3307 # Expansion is eligible for the empty-frame cache
3308 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3309 $text = $this->mTplExpandCache
[$titleText];
3311 $text = $newFrame->expand( $text );
3312 $this->mTplExpandCache
[$titleText] = $text;
3315 $text = $newFrame->expand( $text );
3318 $text = $this->replaceVariables( $text, $newFrame );
3321 # strip woz 'ere 2004-07
3323 # Bug 529: if the template begins with a table or block-level
3324 # element, it should be treated as beginning a new line.
3325 # This behaviour is somewhat controversial.
3326 if (!$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3327 $text = "\n" . $text;
3329 } elseif ( !$noargs ) {
3330 # $noparse and !$noargs
3331 # Just replace the arguments, not any double-brace items
3332 # This is used for rendered interwiki transclusion
3334 $text = $newFrame->expand( $text, 0, PPFrame
::NO_TEMPLATES
);
3336 $text = $this->replaceVariables( $text, $newFrame, true );
3338 } elseif ( $isDOM ) {
3339 $text = $frame->expand( $text );
3341 } elseif ( $isDOM ) {
3342 $text = $frame->expand( $text, 0, PPFrame
::NO_TEMPLATES | PPFrame
::NO_ARGS
);
3345 # Prune lower levels off the recursion check path
3346 $this->mTemplatePath
= $lastPathLevel;
3348 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3349 # Error, oversize inclusion
3350 $text = "[[$originalTitle]]" .
3351 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3357 wfProfileOut( $fname );
3358 return '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3360 wfProfileIn( __METHOD__
. '-placeholders' );
3362 # Replace raw HTML by a placeholder
3363 # Add a blank line preceding, to prevent it from mucking up
3364 # immediately preceding headings
3365 $text = "\n\n" . $this->insertStripItem( $text );
3367 wfProfileOut( __METHOD__
. '-placeholders' );
3370 # Prune lower levels off the recursion check path
3371 $this->mTemplatePath
= $lastPathLevel;
3374 wfProfileOut( $fname );
3375 return '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3377 wfProfileOut( $fname );
3383 * Get the semi-parsed DOM representation of a template with a given title,
3384 * and its redirect destination title. Cached.
3386 function getTemplateDom( $title ) {
3387 $titleText = $title->getPrefixedDBkey();
3389 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3390 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3391 $title = Title
::makeTitle( $ns, $dbk );
3392 $titleText = $title->getPrefixedDBkey();
3394 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3395 return array( $this->mTplDomCache
[$titleText], $title );
3398 // Cache miss, go to the database
3399 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3401 if ( $text === false ) {
3402 $this->mTplDomCache
[$titleText] = false;
3403 return array( false, $title );
3406 # If there are any <onlyinclude> tags, only include them
3407 if ( !$this->ot
['msg'] ) {
3408 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3409 $replacer = new OnlyIncludeReplacer
;
3410 StringUtils
::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3411 array( &$replacer, 'replace' ), $text );
3412 $text = $replacer->output
;
3414 # Remove <noinclude> sections and <includeonly> tags
3415 $text = StringUtils
::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3416 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3419 $dom = $this->preprocessToDom( $text );
3420 $this->mTplDomCache
[$titleText] = $dom;
3421 return array( $dom, $title );
3425 * Fetch the unparsed text of a template and register a reference to it.
3427 function fetchTemplateAndTitle( $title ) {
3428 $templateCb = $this->mOptions
->getTemplateCallback();
3429 $stuff = call_user_func( $templateCb, $title );
3430 $text = $stuff['text'];
3431 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3432 if ( isset( $stuff['deps'] ) ) {
3433 foreach ( $stuff['deps'] as $dep ) {
3434 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3437 return array($text,$finalTitle);
3440 function fetchTemplate( $title ) {
3441 $rv = $this->fetchTemplateAndTitle($title);
3446 * Static function to get a template
3447 * Can be overridden via ParserOptions::setTemplateCallback().
3449 static function statelessFetchTemplate( $title ) {
3450 $text = $skip = false;
3451 $finalTitle = $title;
3454 // Loop to fetch the article, with up to 1 redirect
3455 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3456 # Give extensions a chance to select the revision instead
3457 $id = false; // Assume current
3458 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3464 'page_id' => $title->getArticleID(),
3468 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3469 $rev_id = $rev ?
$rev->getId() : 0;
3473 'page_id' => $title->getArticleID(),
3474 'rev_id' => $rev_id );
3477 $text = $rev->getText();
3478 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3480 $message = $wgLang->lcfirst( $title->getText() );
3481 $text = wfMsgForContentNoTrans( $message );
3482 if( wfEmptyMsg( $message, $text ) ) {
3489 if ( $text === false ) {
3493 $finalTitle = $title;
3494 $title = Title
::newFromRedirect( $text );
3498 'finalTitle' => $finalTitle,
3503 * Transclude an interwiki link.
3505 function interwikiTransclude( $title, $action ) {
3506 global $wgEnableScaryTranscluding;
3508 if (!$wgEnableScaryTranscluding)
3509 return wfMsg('scarytranscludedisabled');
3511 $url = $title->getFullUrl( "action=$action" );
3513 if (strlen($url) > 255)
3514 return wfMsg('scarytranscludetoolong');
3515 return $this->fetchScaryTemplateMaybeFromCache($url);
3518 function fetchScaryTemplateMaybeFromCache($url) {
3519 global $wgTranscludeCacheExpiry;
3520 $dbr = wfGetDB(DB_SLAVE
);
3521 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3522 array('tc_url' => $url));
3524 $time = $obj->tc_time
;
3525 $text = $obj->tc_contents
;
3526 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3531 $text = Http
::get($url);
3533 return wfMsg('scarytranscludefailed', $url);
3535 $dbw = wfGetDB(DB_MASTER
);
3536 $dbw->replace('transcache', array('tc_url'), array(
3538 'tc_time' => time(),
3539 'tc_contents' => $text));
3545 * Triple brace replacement -- used for template arguments
3548 function argSubstitution( $piece, $frame ) {
3549 wfProfileIn( __METHOD__
);
3553 $parts = $piece['parts'];
3554 $argWithSpaces = $frame->expand( $piece['title'] );
3555 $arg = trim( $argWithSpaces );
3557 if ( isset( $frame->args
[$arg] ) ) {
3558 $text = $frame->parent
->expand( $frame->args
[$arg] );
3559 } else if ( ( $this->ot
['html'] ||
$this->ot
['pre'] ) && $parts->length
> 0 ) {
3560 $text = $frame->expand( $parts->item( 0 ) );
3562 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3563 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3566 if ( $text === false ) {
3567 $text = '{{{' . $frame->implode( '|', $argWithSpaces, $parts ) . '}}}';
3569 if ( $error !== false ) {
3573 wfProfileOut( __METHOD__
);
3578 * Return the text to be used for a given extension tag.
3579 * This is the ghost of strip().
3581 * @param array $params Associative array of parameters:
3582 * name DOMNode for the tag name
3583 * attrText DOMNode for unparsed text where tag attributes are thought to be
3584 * inner Contents of extension element
3585 * noClose Original text did not have a close tag
3586 * @param PPFrame $frame
3588 function extensionSubstitution( $params, $frame ) {
3589 global $wgRawHtml, $wgContLang;
3592 $name = $frame->expand( $params['name'] );
3593 $attrText = is_null( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3594 $content = is_null( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3596 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++
) . $this->mMarkerSuffix
;
3598 if ( $this->ot
['html'] ) {
3599 if ( $name == '!--' ) {
3602 $name = strtolower( $name );
3604 $params = Sanitizer
::decodeTagAttributes( $attrText );
3611 throw new MWException( '<html> extension tag encountered unexpectedly' );
3614 $output = Xml
::escapeTagsOnly( $content );
3617 $output = $wgContLang->armourMath(
3618 MathRenderer
::renderMath( $content, $params ) );
3621 $output = $this->renderImageGallery( $content, $params );
3624 if( isset( $this->mTagHooks
[$name] ) ) {
3625 $output = call_user_func_array( $this->mTagHooks
[$name],
3626 array( $content, $params, $this ) );
3628 throw new MWException( "Invalid call hook $name" );
3632 if ( $name == '!--' ) {
3633 $output = '<!--' . $content . '-->';
3635 if ( $content === null ) {
3636 $output = "<$name$attrText/>";
3638 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3639 $output = "<$name$attrText>$content$close";
3644 if ( $name == 'html' ||
$name == 'nowiki' ) {
3645 $this->mStripState
->nowiki
->setPair( $marker, $output );
3647 $this->mStripState
->general
->setPair( $marker, $output );
3653 * Increment an include size counter
3655 * @param string $type The type of expansion
3656 * @param integer $size The size of the text
3657 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3659 function incrementIncludeSize( $type, $size ) {
3660 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3663 $this->mIncludeSizes
[$type] +
= $size;
3669 * Detect __NOGALLERY__ magic word and set a placeholder
3671 function stripNoGallery( &$text ) {
3672 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3674 $mw = MagicWord
::get( 'nogallery' );
3675 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3679 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3680 * placeholder that will then be replaced by the real TOC in
3681 * ->formatHeadings, this works because at this points real
3682 * comments will have already been discarded by the sanitizer.
3684 * Any additional __TOC__ magic words left over will be discarded
3685 * as there can only be one TOC on the page.
3687 function stripToc( $text ) {
3688 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3690 $mw = MagicWord
::get( 'notoc' );
3691 if( $mw->matchAndRemove( $text ) ) {
3692 $this->mShowToc
= false;
3695 $mw = MagicWord
::get( 'toc' );
3696 if( $mw->match( $text ) ) {
3697 $this->mShowToc
= true;
3698 $this->mForceTocPosition
= true;
3700 // Set a placeholder. At the end we'll fill it in with the TOC.
3701 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3703 // Only keep the first one.
3704 $text = $mw->replace( '', $text );
3710 * This function accomplishes several tasks:
3711 * 1) Auto-number headings if that option is enabled
3712 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3713 * 3) Add a Table of contents on the top for users who have enabled the option
3714 * 4) Auto-anchor headings
3716 * It loops through all headlines, collects the necessary data, then splits up the
3717 * string and re-inserts the newly formatted headlines.
3719 * @param string $text
3720 * @param boolean $isMain
3723 function formatHeadings( $text, $isMain=true ) {
3724 global $wgMaxTocLevel, $wgContLang;
3726 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3727 if( !$this->mTitle
->quickUserCan( 'edit' ) ) {
3730 $showEditLink = $this->mOptions
->getEditSection();
3733 # Inhibit editsection links if requested in the page
3734 $esw =& MagicWord
::get( 'noeditsection' );
3735 if( $esw->matchAndRemove( $text ) ) {
3739 # Get all headlines for numbering them and adding funky stuff like [edit]
3740 # links - this is for later, but we need the number of headlines right now
3742 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3744 # if there are fewer than 4 headlines in the article, do not show TOC
3745 # unless it's been explicitly enabled.
3746 $enoughToc = $this->mShowToc
&&
3747 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3749 # Allow user to stipulate that a page should have a "new section"
3750 # link added via __NEWSECTIONLINK__
3751 $mw =& MagicWord
::get( 'newsectionlink' );
3752 if( $mw->matchAndRemove( $text ) )
3753 $this->mOutput
->setNewSection( true );
3755 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3756 # override above conditions and always show TOC above first header
3757 $mw =& MagicWord
::get( 'forcetoc' );
3758 if ($mw->matchAndRemove( $text ) ) {
3759 $this->mShowToc
= true;
3763 # We need this to perform operations on the HTML
3764 $sk = $this->mOptions
->getSkin();
3770 # Ugh .. the TOC should have neat indentation levels which can be
3771 # passed to the skin functions. These are determined here
3775 $sublevelCount = array();
3776 $levelCount = array();
3782 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3783 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3785 foreach( $matches[3] as $headline ) {
3786 $isTemplate = false;
3788 $sectionIndex = false;
3790 $markerMatches = array();
3791 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3792 $serial = $markerMatches[1];
3793 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3794 $isTemplate = ($titleText != $baseTitleText);
3795 $headline = preg_replace("/^$markerRegex/", "", $headline);
3799 $prevlevel = $level;
3800 $prevtoclevel = $toclevel;
3802 $level = $matches[1][$headlineCount];
3804 if( $doNumberHeadings ||
$enoughToc ) {
3806 if ( $level > $prevlevel ) {
3807 # Increase TOC level
3809 $sublevelCount[$toclevel] = 0;
3810 if( $toclevel<$wgMaxTocLevel ) {
3811 $prevtoclevel = $toclevel;
3812 $toc .= $sk->tocIndent();
3816 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3817 # Decrease TOC level, find level to jump to
3819 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3820 # Can only go down to level 1
3823 for ($i = $toclevel; $i > 0; $i--) {
3824 if ( $levelCount[$i] == $level ) {
3825 # Found last matching level
3829 elseif ( $levelCount[$i] < $level ) {
3830 # Found first matching level below current level
3836 if( $toclevel<$wgMaxTocLevel ) {
3837 if($prevtoclevel < $wgMaxTocLevel) {
3838 # Unindent only if the previous toc level was shown :p
3839 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3841 $toc .= $sk->tocLineEnd();
3846 # No change in level, end TOC line
3847 if( $toclevel<$wgMaxTocLevel ) {
3848 $toc .= $sk->tocLineEnd();
3852 $levelCount[$toclevel] = $level;
3854 # count number of headlines for each level
3855 @$sublevelCount[$toclevel]++
;
3857 for( $i = 1; $i <= $toclevel; $i++
) {
3858 if( !empty( $sublevelCount[$i] ) ) {
3862 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3868 # The safe header is a version of the header text safe to use for links
3869 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3870 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3872 # Remove link placeholders by the link text.
3873 # <!--LINK number-->
3875 # link text with suffix
3876 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3877 "\$this->mLinkHolders['texts'][\$1]",
3879 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3880 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3883 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3884 $tocline = preg_replace(
3885 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3889 $tocline = trim( $tocline );
3891 # For the anchor, strip out HTML-y stuff period
3892 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3893 $safeHeadline = trim( $safeHeadline );
3895 # Save headline for section edit hint before it's escaped
3896 $headlineHint = $safeHeadline;
3897 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3898 $refers[$headlineCount] = $safeHeadline;
3900 # count how many in assoc. array so we can track dupes in anchors
3901 isset( $refers[$safeHeadline] ) ?
$refers[$safeHeadline]++
: $refers[$safeHeadline] = 1;
3902 $refcount[$headlineCount] = $refers[$safeHeadline];
3904 # Don't number the heading if it is the only one (looks silly)
3905 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3906 # the two are different if the line contains a link
3907 $headline=$numbering . ' ' . $headline;
3910 # Create the anchor for linking from the TOC to the section
3911 $anchor = $safeHeadline;
3912 if($refcount[$headlineCount] > 1 ) {
3913 $anchor .= '_' . $refcount[$headlineCount];
3915 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3916 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3918 # give headline the correct <h#> tag
3919 if( $showEditLink && $sectionIndex !== false ) {
3921 $editlink = $sk->editSectionLinkForOther($titleText, $sectionIndex);
3923 $editlink = $sk->editSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3927 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3932 # Never ever show TOC if no headers
3933 if( $numVisible < 1 ) {
3938 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3939 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3941 $toc = $sk->tocList( $toc );
3944 # split up and insert constructed headlines
3946 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3949 foreach( $blocks as $block ) {
3950 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3951 # This is the [edit] link that appears for the top block of text when
3952 # section editing is enabled
3954 # Disabled because it broke block formatting
3955 # For example, a bullet point in the top line
3956 # $full .= $sk->editSectionLink(0);
3959 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3960 # Top anchor now in skin
3964 if( !empty( $head[$i] ) ) {
3969 if( $this->mForceTocPosition
) {
3970 return str_replace( '<!--MWTOC-->', $toc, $full );
3977 * Transform wiki markup when saving a page by doing \r\n -> \n
3978 * conversion, substitting signatures, {{subst:}} templates, etc.
3980 * @param string $text the text to transform
3981 * @param Title &$title the Title object for the current article
3982 * @param User &$user the User object describing the current user
3983 * @param ParserOptions $options parsing options
3984 * @param bool $clearState whether to clear the parser state first
3985 * @return string the altered wiki markup
3988 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3989 $this->mOptions
= $options;
3990 $this->mTitle
=& $title;
3991 $this->setOutputType( OT_WIKI
);
3993 if ( $clearState ) {
3994 $this->clearState();
4000 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4001 $text = $this->pstPass2( $text, $user );
4002 $text = $this->mStripState
->unstripBoth( $text );
4007 * Pre-save transform helper function
4010 function pstPass2( $text, $user ) {
4011 global $wgContLang, $wgLocaltimezone;
4013 /* Note: This is the timestamp saved as hardcoded wikitext to
4014 * the database, we use $wgContLang here in order to give
4015 * everyone the same signature and use the default one rather
4016 * than the one selected in each user's preferences.
4018 if ( isset( $wgLocaltimezone ) ) {
4019 $oldtz = getenv( 'TZ' );
4020 putenv( 'TZ='.$wgLocaltimezone );
4022 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
4023 ' (' . date( 'T' ) . ')';
4024 if ( isset( $wgLocaltimezone ) ) {
4025 putenv( 'TZ='.$oldtz );
4028 # Variable replacement
4029 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4030 $text = $this->replaceVariables( $text );
4032 # Strip out <nowiki> etc. added via replaceVariables
4033 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
4036 $sigText = $this->getUserSig( $user );
4037 $text = strtr( $text, array(
4039 '~~~~' => "$sigText $d",
4043 # Context links: [[|name]] and [[name (context)|]]
4045 global $wgLegalTitleChars;
4046 $tc = "[$wgLegalTitleChars]";
4047 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
4049 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4050 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4051 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4053 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4054 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4055 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4057 $t = $this->mTitle
->getText();
4059 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4060 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4061 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
4062 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4064 # if there's no context, don't bother duplicating the title
4065 $text = preg_replace( $p2, '[[\\1]]', $text );
4068 # Trim trailing whitespace
4069 $text = rtrim( $text );
4075 * Fetch the user's signature text, if any, and normalize to
4076 * validated, ready-to-insert wikitext.
4082 function getUserSig( &$user ) {
4083 global $wgMaxSigChars;
4085 $username = $user->getName();
4086 $nickname = $user->getOption( 'nickname' );
4087 $nickname = $nickname === '' ?
$username : $nickname;
4089 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4090 $nickname = $username;
4091 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4092 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
4093 # Sig. might contain markup; validate this
4094 if( $this->validateSig( $nickname ) !== false ) {
4095 # Validated; clean up (if needed) and return it
4096 return $this->cleanSig( $nickname, true );
4098 # Failed to validate; fall back to the default
4099 $nickname = $username;
4100 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
4104 // Make sure nickname doesnt get a sig in a sig
4105 $nickname = $this->cleanSigInSig( $nickname );
4107 # If we're still here, make it a link to the user page
4108 $userText = wfEscapeWikiText( $username );
4109 $nickText = wfEscapeWikiText( $nickname );
4110 if ( $user->isAnon() ) {
4111 return wfMsgForContent( 'signature-anon', $userText, $nickText );
4113 return wfMsgForContent( 'signature', $userText, $nickText );
4118 * Check that the user's signature contains no bad XML
4120 * @param string $text
4121 * @return mixed An expanded string, or false if invalid.
4123 function validateSig( $text ) {
4124 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
4128 * Clean up signature text
4130 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4131 * 2) Substitute all transclusions
4133 * @param string $text
4134 * @param $parsing Whether we're cleaning (preferences save) or parsing
4135 * @return string Signature text
4137 function cleanSig( $text, $parsing = false ) {
4139 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
4141 $substWord = MagicWord
::get( 'subst' );
4142 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4143 $substText = '{{' . $substWord->getSynonym( 0 );
4145 $text = preg_replace( $substRegex, $substText, $text );
4146 $text = $this->cleanSigInSig( $text );
4147 $text = $this->replaceVariables( $text );
4149 $this->clearState();
4154 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4155 * @param string $text
4156 * @return string Signature text with /~{3,5}/ removed
4158 function cleanSigInSig( $text ) {
4159 $text = preg_replace( '/~{3,5}/', '', $text );
4164 * Set up some variables which are usually set up in parse()
4165 * so that an external function can call some class members with confidence
4168 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4169 $this->mTitle
=& $title;
4170 $this->mOptions
= $options;
4171 $this->setOutputType( $outputType );
4172 if ( $clearState ) {
4173 $this->clearState();
4178 * Transform a MediaWiki message by replacing magic variables.
4180 * For some unknown reason, it also expands templates, but only to the
4181 * first recursion level. This is wrong and broken, probably introduced
4182 * accidentally during refactoring, but probably relied upon by thousands
4185 * @param string $text the text to transform
4186 * @param ParserOptions $options options
4187 * @return string the text with variables substituted
4190 function transformMsg( $text, $options ) {
4192 static $executing = false;
4194 $fname = "Parser::transformMsg";
4196 # Guard against infinite recursion
4202 wfProfileIn($fname);
4204 if ( $wgTitle && !( $wgTitle instanceof FakeTitle
) ) {
4205 $this->mTitle
= $wgTitle;
4207 $this->mTitle
= Title
::newFromText('msg');
4209 $this->mOptions
= $options;
4210 $this->setOutputType( OT_MSG
);
4211 $this->clearState();
4212 $text = $this->replaceVariables( $text );
4215 wfProfileOut($fname);
4220 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4221 * The callback should have the following form:
4222 * function myParserHook( $text, $params, &$parser ) { ... }
4224 * Transform and return $text. Use $parser for any required context, e.g. use
4225 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4229 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4230 * @param mixed $callback The callback function (and object) to use for the tag
4232 * @return The old value of the mTagHooks array associated with the hook
4234 function setHook( $tag, $callback ) {
4235 $tag = strtolower( $tag );
4236 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4237 $this->mTagHooks
[$tag] = $callback;
4238 $this->mStripList
[] = $tag;
4243 function setTransparentTagHook( $tag, $callback ) {
4244 $tag = strtolower( $tag );
4245 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4246 $this->mTransparentTagHooks
[$tag] = $callback;
4252 * Create a function, e.g. {{sum:1|2|3}}
4253 * The callback function should have the form:
4254 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4256 * The callback may either return the text result of the function, or an array with the text
4257 * in element 0, and a number of flags in the other elements. The names of the flags are
4258 * specified in the keys. Valid flags are:
4259 * found The text returned is valid, stop processing the template. This
4261 * nowiki Wiki markup in the return value should be escaped
4262 * noparse Unsafe HTML tags should not be stripped, etc.
4263 * noargs Don't replace triple-brace arguments in the return value
4264 * isHTML The returned text is HTML, armour it against wikitext transformation
4268 * @param string $id The magic word ID
4269 * @param mixed $callback The callback function (and object) to use
4270 * @param integer $flags a combination of the following flags:
4271 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4273 * @return The old callback function for this name, if any
4275 function setFunctionHook( $id, $callback, $flags = 0 ) {
4276 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4277 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4279 # Add to function cache
4280 $mw = MagicWord
::get( $id );
4282 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4284 $synonyms = $mw->getSynonyms();
4285 $sensitive = intval( $mw->isCaseSensitive() );
4287 foreach ( $synonyms as $syn ) {
4289 if ( !$sensitive ) {
4290 $syn = strtolower( $syn );
4293 if ( !( $flags & SFH_NO_HASH
) ) {
4296 # Remove trailing colon
4297 if ( substr( $syn, -1, 1 ) == ':' ) {
4298 $syn = substr( $syn, 0, -1 );
4300 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4306 * Get all registered function hook identifiers
4310 function getFunctionHooks() {
4311 return array_keys( $this->mFunctionHooks
);
4315 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4316 * Placeholders created in Skin::makeLinkObj()
4317 * Returns an array of links found, indexed by PDBK:
4321 * $options is a bit field, RLH_FOR_UPDATE to select for update
4323 function replaceLinkHolders( &$text, $options = 0 ) {
4327 $fname = 'Parser::replaceLinkHolders';
4328 wfProfileIn( $fname );
4332 $sk = $this->mOptions
->getSkin();
4333 $linkCache =& LinkCache
::singleton();
4335 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
4336 wfProfileIn( $fname.'-check' );
4337 $dbr = wfGetDB( DB_SLAVE
);
4338 $page = $dbr->tableName( 'page' );
4339 $threshold = $wgUser->getOption('stubthreshold');
4342 asort( $this->mLinkHolders
['namespaces'] );
4347 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4349 $title = $this->mLinkHolders
['titles'][$key];
4351 # Skip invalid entries.
4352 # Result will be ugly, but prevents crash.
4353 if ( is_null( $title ) ) {
4356 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4358 # Check if it's a static known link, e.g. interwiki
4359 if ( $title->isAlwaysKnown() ) {
4360 $colours[$pdbk] = 1;
4361 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4362 $colours[$pdbk] = 1;
4363 $this->mOutput
->addLink( $title, $id );
4364 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4365 $colours[$pdbk] = 0;
4366 } elseif ( $title->getNamespace() == NS_SPECIAL
&& !SpecialPage
::exists( $pdbk ) ) {
4367 $colours[$pdbk] = 0;
4369 # Not in the link cache, add it to the query
4370 if ( !isset( $current ) ) {
4372 $query = "SELECT page_id, page_namespace, page_title";
4373 if ( $threshold > 0 ) {
4374 $query .= ', page_len, page_is_redirect';
4376 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4377 } elseif ( $current != $ns ) {
4379 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4384 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4389 if ( $options & RLH_FOR_UPDATE
) {
4390 $query .= ' FOR UPDATE';
4393 $res = $dbr->query( $query, $fname );
4395 # Fetch data and form into an associative array
4396 # non-existent = broken
4399 while ( $s = $dbr->fetchObject($res) ) {
4400 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4401 $pdbk = $title->getPrefixedDBkey();
4402 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4403 $this->mOutput
->addLink( $title, $s->page_id
);
4405 $colours[$pdbk] = ( $threshold == 0 ||
(
4406 $s->page_len
>= $threshold ||
# always true if $threshold <= 0
4407 $s->page_is_redirect ||
4408 !Namespace::isContent( $s->page_namespace
) )
4412 wfProfileOut( $fname.'-check' );
4414 # Do a second query for different language variants of links and categories
4415 if($wgContLang->hasVariants()){
4416 $linkBatch = new LinkBatch();
4417 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4418 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4419 $varCategories = array(); // category replacements oldDBkey => newDBkey
4421 $categories = $this->mOutput
->getCategoryLinks();
4423 // Add variants of links to link batch
4424 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4425 $title = $this->mLinkHolders
['titles'][$key];
4426 if ( is_null( $title ) )
4429 $pdbk = $title->getPrefixedDBkey();
4430 $titleText = $title->getText();
4432 // generate all variants of the link title text
4433 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4435 // if link was not found (in first query), add all variants to query
4436 if ( !isset($colours[$pdbk]) ){
4437 foreach($allTextVariants as $textVariant){
4438 if($textVariant != $titleText){
4439 $variantTitle = Title
::makeTitle( $ns, $textVariant );
4440 if(is_null($variantTitle)) continue;
4441 $linkBatch->addObj( $variantTitle );
4442 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4448 // process categories, check if a category exists in some variant
4449 foreach( $categories as $category ){
4450 $variants = $wgContLang->convertLinkToAllVariants($category);
4451 foreach($variants as $variant){
4452 if($variant != $category){
4453 $variantTitle = Title
::newFromDBkey( Title
::makeName(NS_CATEGORY
,$variant) );
4454 if(is_null($variantTitle)) continue;
4455 $linkBatch->addObj( $variantTitle );
4456 $categoryMap[$variant] = $category;
4462 if(!$linkBatch->isEmpty()){
4464 $titleClause = $linkBatch->constructSet('page', $dbr);
4466 $variantQuery = "SELECT page_id, page_namespace, page_title";
4467 if ( $threshold > 0 ) {
4468 $variantQuery .= ', page_len, page_is_redirect';
4471 $variantQuery .= " FROM $page WHERE $titleClause";
4472 if ( $options & RLH_FOR_UPDATE
) {
4473 $variantQuery .= ' FOR UPDATE';
4476 $varRes = $dbr->query( $variantQuery, $fname );
4478 // for each found variants, figure out link holders and replace
4479 while ( $s = $dbr->fetchObject($varRes) ) {
4481 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4482 $varPdbk = $variantTitle->getPrefixedDBkey();
4483 $vardbk = $variantTitle->getDBkey();
4485 $holderKeys = array();
4486 if(isset($variantMap[$varPdbk])){
4487 $holderKeys = $variantMap[$varPdbk];
4488 $linkCache->addGoodLinkObj( $s->page_id
, $variantTitle );
4489 $this->mOutput
->addLink( $variantTitle, $s->page_id
);
4492 // loop over link holders
4493 foreach($holderKeys as $key){
4494 $title = $this->mLinkHolders
['titles'][$key];
4495 if ( is_null( $title ) ) continue;
4497 $pdbk = $title->getPrefixedDBkey();
4499 if(!isset($colours[$pdbk])){
4500 // found link in some of the variants, replace the link holder data
4501 $this->mLinkHolders
['titles'][$key] = $variantTitle;
4502 $this->mLinkHolders
['dbkeys'][$key] = $variantTitle->getDBkey();
4504 // set pdbk and colour
4505 $pdbks[$key] = $varPdbk;
4506 if ( $threshold > 0 ) {
4507 $size = $s->page_len
;
4508 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4509 $colours[$varPdbk] = 1;
4511 $colours[$varPdbk] = 2;
4515 $colours[$varPdbk] = 1;
4520 // check if the object is a variant of a category
4521 if(isset($categoryMap[$vardbk])){
4522 $oldkey = $categoryMap[$vardbk];
4523 if($oldkey != $vardbk)
4524 $varCategories[$oldkey]=$vardbk;
4528 // rebuild the categories in original order (if there are replacements)
4529 if(count($varCategories)>0){
4531 $originalCats = $this->mOutput
->getCategories();
4532 foreach($originalCats as $cat => $sortkey){
4533 // make the replacement
4534 if( array_key_exists($cat,$varCategories) )
4535 $newCats[$varCategories[$cat]] = $sortkey;
4536 else $newCats[$cat] = $sortkey;
4538 $this->mOutput
->setCategoryLinks($newCats);
4543 # Construct search and replace arrays
4544 wfProfileIn( $fname.'-construct' );
4545 $replacePairs = array();
4546 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4547 $pdbk = $pdbks[$key];
4548 $searchkey = "<!--LINK $key-->";
4549 $title = $this->mLinkHolders
['titles'][$key];
4550 if ( empty( $colours[$pdbk] ) ) {
4551 $linkCache->addBadLinkObj( $title );
4552 $colours[$pdbk] = 0;
4553 $this->mOutput
->addLink( $title, 0 );
4554 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4555 $this->mLinkHolders
['texts'][$key],
4556 $this->mLinkHolders
['queries'][$key] );
4557 } elseif ( $colours[$pdbk] == 1 ) {
4558 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4559 $this->mLinkHolders
['texts'][$key],
4560 $this->mLinkHolders
['queries'][$key] );
4561 } elseif ( $colours[$pdbk] == 2 ) {
4562 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4563 $this->mLinkHolders
['texts'][$key],
4564 $this->mLinkHolders
['queries'][$key] );
4567 $replacer = new HashtableReplacer( $replacePairs, 1 );
4568 wfProfileOut( $fname.'-construct' );
4571 wfProfileIn( $fname.'-replace' );
4572 $text = preg_replace_callback(
4573 '/(<!--LINK .*?-->)/',
4577 wfProfileOut( $fname.'-replace' );
4580 # Now process interwiki link holders
4581 # This is quite a bit simpler than internal links
4582 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4583 wfProfileIn( $fname.'-interwiki' );
4584 # Make interwiki link HTML
4585 $replacePairs = array();
4586 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4587 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4588 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4590 $replacer = new HashtableReplacer( $replacePairs, 1 );
4592 $text = preg_replace_callback(
4593 '/<!--IWLINK (.*?)-->/',
4596 wfProfileOut( $fname.'-interwiki' );
4599 wfProfileOut( $fname );
4604 * Replace <!--LINK--> link placeholders with plain text of links
4605 * (not HTML-formatted).
4606 * @param string $text
4609 function replaceLinkHoldersText( $text ) {
4610 $fname = 'Parser::replaceLinkHoldersText';
4611 wfProfileIn( $fname );
4613 $text = preg_replace_callback(
4614 '/<!--(LINK|IWLINK) (.*?)-->/',
4615 array( &$this, 'replaceLinkHoldersTextCallback' ),
4618 wfProfileOut( $fname );
4623 * @param array $matches
4627 function replaceLinkHoldersTextCallback( $matches ) {
4628 $type = $matches[1];
4630 if( $type == 'LINK' ) {
4631 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4632 return $this->mLinkHolders
['texts'][$key];
4634 } elseif( $type == 'IWLINK' ) {
4635 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4636 return $this->mInterwikiLinkHolders
['texts'][$key];
4643 * Tag hook handler for 'pre'.
4645 function renderPreTag( $text, $attribs ) {
4646 // Backwards-compatibility hack
4647 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4649 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4650 return wfOpenElement( 'pre', $attribs ) .
4651 Xml
::escapeTagsOnly( $content ) .
4656 * Renders an image gallery from a text with one line per image.
4657 * text labels may be given by using |-style alternative text. E.g.
4658 * Image:one.jpg|The number "1"
4659 * Image:tree.jpg|A tree
4660 * given as text will return the HTML of a gallery with two images,
4661 * labeled 'The number "1"' and
4664 function renderImageGallery( $text, $params ) {
4665 $ig = new ImageGallery();
4666 $ig->setContextTitle( $this->mTitle
);
4667 $ig->setShowBytes( false );
4668 $ig->setShowFilename( false );
4669 $ig->setParser( $this );
4670 $ig->setHideBadImages();
4671 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4672 $ig->useSkin( $this->mOptions
->getSkin() );
4673 $ig->mRevisionId
= $this->mRevisionId
;
4675 if( isset( $params['caption'] ) ) {
4676 $caption = $params['caption'];
4677 $caption = htmlspecialchars( $caption );
4678 $caption = $this->replaceInternalLinks( $caption );
4679 $ig->setCaptionHtml( $caption );
4681 if( isset( $params['perrow'] ) ) {
4682 $ig->setPerRow( $params['perrow'] );
4684 if( isset( $params['widths'] ) ) {
4685 $ig->setWidths( $params['widths'] );
4687 if( isset( $params['heights'] ) ) {
4688 $ig->setHeights( $params['heights'] );
4691 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4693 $lines = explode( "\n", $text );
4694 foreach ( $lines as $line ) {
4695 # match lines like these:
4696 # Image:someimage.jpg|This is some image
4698 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4700 if ( count( $matches ) == 0 ) {
4703 $tp = Title
::newFromText( $matches[1] );
4705 if( is_null( $nt ) ) {
4706 # Bogus title. Ignore these so we don't bomb out later.
4709 if ( isset( $matches[3] ) ) {
4710 $label = $matches[3];
4715 $pout = $this->parse( $label,
4718 false, // Strip whitespace...?
4719 false // Don't clear state!
4721 $html = $pout->getText();
4723 $ig->add( $nt, $html );
4725 # Only add real images (bug #5586)
4726 if ( $nt->getNamespace() == NS_IMAGE
) {
4727 $this->mOutput
->addImage( $nt->getDBkey() );
4730 return $ig->toHTML();
4733 function getImageParams( $handler ) {
4735 $handlerClass = get_class( $handler );
4739 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4740 // Initialise static lists
4741 static $internalParamNames = array(
4742 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4743 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4744 'bottom', 'text-bottom' ),
4745 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4746 'upright', 'border' ),
4748 static $internalParamMap;
4749 if ( !$internalParamMap ) {
4750 $internalParamMap = array();
4751 foreach ( $internalParamNames as $type => $names ) {
4752 foreach ( $names as $name ) {
4753 $magicName = str_replace( '-', '_', "img_$name" );
4754 $internalParamMap[$magicName] = array( $type, $name );
4759 // Add handler params
4760 $paramMap = $internalParamMap;
4762 $handlerParamMap = $handler->getParamMap();
4763 foreach ( $handlerParamMap as $magic => $paramName ) {
4764 $paramMap[$magic] = array( 'handler', $paramName );
4767 $this->mImageParams
[$handlerClass] = $paramMap;
4768 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4770 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4774 * Parse image options text and use it to make an image
4776 function makeImage( $title, $options ) {
4777 # @TODO: let the MediaHandler specify its transform parameters
4779 # Check if the options text is of the form "options|alt text"
4781 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4782 # * left no resizing, just left align. label is used for alt= only
4783 # * right same, but right aligned
4784 # * none same, but not aligned
4785 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4786 # * center center the image
4787 # * framed Keep original image size, no magnify-button.
4788 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4789 # * upright reduce width for upright images, rounded to full __0 px
4790 # * border draw a 1px border around the image
4791 # vertical-align values (no % or length right now):
4801 $parts = array_map( 'trim', explode( '|', $options) );
4802 $sk = $this->mOptions
->getSkin();
4804 # Give extensions a chance to select the file revision for us
4805 $skip = $time = false;
4806 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4809 return $sk->makeLinkObj( $title );
4813 $file = wfFindFile( $title, $time );
4814 $handler = $file ?
$file->getHandler() : false;
4816 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4818 # Process the input parameters
4820 $params = array( 'frame' => array(), 'handler' => array(),
4821 'horizAlign' => array(), 'vertAlign' => array() );
4822 foreach( $parts as $part ) {
4823 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4824 if ( isset( $paramMap[$magicName] ) ) {
4825 list( $type, $paramName ) = $paramMap[$magicName];
4826 $params[$type][$paramName] = $value;
4828 // Special case; width and height come in one variable together
4829 if( $type == 'handler' && $paramName == 'width' ) {
4831 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4832 $params[$type]['width'] = intval( $m[1] );
4833 $params[$type]['height'] = intval( $m[2] );
4835 $params[$type]['width'] = intval( $value );
4843 # Process alignment parameters
4844 if ( $params['horizAlign'] ) {
4845 $params['frame']['align'] = key( $params['horizAlign'] );
4847 if ( $params['vertAlign'] ) {
4848 $params['frame']['valign'] = key( $params['vertAlign'] );
4851 # Validate the handler parameters
4853 foreach ( $params['handler'] as $name => $value ) {
4854 if ( !$handler->validateParam( $name, $value ) ) {
4855 unset( $params['handler'][$name] );
4860 # Strip bad stuff out of the alt text
4861 $alt = $this->replaceLinkHoldersText( $caption );
4863 # make sure there are no placeholders in thumbnail attributes
4864 # that are later expanded to html- so expand them now and
4866 $alt = $this->mStripState
->unstripBoth( $alt );
4867 $alt = Sanitizer
::stripAllTags( $alt );
4869 $params['frame']['alt'] = $alt;
4870 $params['frame']['caption'] = $caption;
4872 # Linker does the rest
4873 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4875 # Give the handler a chance to modify the parser object
4877 $handler->parserTransformHook( $this, $file );
4884 * Set a flag in the output object indicating that the content is dynamic and
4885 * shouldn't be cached.
4887 function disableCache() {
4888 wfDebug( "Parser output marked as uncacheable.\n" );
4889 $this->mOutput
->mCacheTime
= -1;
4893 * Callback from the Sanitizer for expanding items found in HTML attribute
4894 * values, so they can be safely tested and escaped.
4895 * @param string $text
4896 * @param PPFrame $frame
4900 function attributeStripCallback( &$text, $frame = false ) {
4901 $text = $this->replaceVariables( $text, $frame );
4902 $text = $this->mStripState
->unstripBoth( $text );
4911 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4912 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4913 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4919 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4924 * Break wikitext input into sections, and either pull or replace
4925 * some particular section's text.
4927 * External callers should use the getSection and replaceSection methods.
4929 * @param $text Page wikitext
4930 * @param $section Numbered section. 0 pulls the text before the first
4931 * heading; other numbers will pull the given section
4932 * along with its lower-level subsections. If the section is
4933 * not found, $mode=get will return $newtext, and
4934 * $mode=replace will return $text.
4935 * @param $mode One of "get" or "replace"
4936 * @param $newText Replacement text for section data.
4937 * @return string for "get", the extracted section text.
4938 * for "replace", the whole page with the section replaced.
4940 private function extractSections( $text, $section, $mode, $newText='' ) {
4941 $this->clearState();
4942 $this->mOptions
= new ParserOptions
;
4943 $this->setOutputType( OT_WIKI
);
4946 $frame = new PPFrame( $this );
4948 // Preprocess the text
4949 $dom = $this->preprocessToDom( $text );
4950 $root = $dom->documentElement
;
4952 // <h> nodes indicate section breaks
4953 // They can only occur at the top level, so we can find them by iterating the root's children
4954 $node = $root->firstChild
;
4956 // Find the target section
4957 if ( $section == 0 ) {
4958 // Section zero doesn't nest, level=big
4959 $targetLevel = 1000;
4962 if ( $node->nodeName
== 'h' ) {
4963 if ( $curIndex +
1 == $section ) {
4968 if ( $mode == 'replace' ) {
4969 $outText .= $frame->expand( $node );
4971 $node = $node->nextSibling
;
4974 $targetLevel = $node->getAttribute( 'level' );
4980 if ( $mode == 'get' ) {
4987 // Find the end of the section, including nested sections
4989 if ( $node->nodeName
== 'h' ) {
4991 $curLevel = $node->getAttribute( 'level' );
4992 if ( $curIndex != $section && $curLevel <= $targetLevel ) {
4996 if ( $mode == 'get' ) {
4997 $outText .= $frame->expand( $node );
4999 $node = $node->nextSibling
;
5002 // Write out the remainder (in replace mode only)
5003 if ( $mode == 'replace' ) {
5004 // Output the replacement text
5005 // Add two newlines on -- trailing whitespace in $newText is conventionally
5006 // stripped by the editor, so we need both newlines to restore the paragraph gap
5007 $outText .= $newText . "\n\n";
5009 $outText .= $frame->expand( $node );
5010 $node = $node->nextSibling
;
5014 if ( is_string( $outText ) ) {
5015 // Re-insert stripped tags
5016 $outText = trim( $this->mStripState
->unstripBoth( $outText ) );
5023 * This function returns the text of a section, specified by a number ($section).
5024 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5025 * the first section before any such heading (section 0).
5027 * If a section contains subsections, these are also returned.
5029 * @param $text String: text to look in
5030 * @param $section Integer: section number
5031 * @param $deftext: default to return if section is not found
5032 * @return string text of the requested section
5034 public function getSection( $text, $section, $deftext='' ) {
5035 return $this->extractSections( $text, $section, "get", $deftext );
5038 public function replaceSection( $oldtext, $section, $text ) {
5039 return $this->extractSections( $oldtext, $section, "replace", $text );
5043 * Get the timestamp associated with the current revision, adjusted for
5044 * the default server-local timestamp
5046 function getRevisionTimestamp() {
5047 if ( is_null( $this->mRevisionTimestamp
) ) {
5048 wfProfileIn( __METHOD__
);
5050 $dbr = wfGetDB( DB_SLAVE
);
5051 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5052 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
5054 // Normalize timestamp to internal MW format for timezone processing.
5055 // This has the added side-effect of replacing a null value with
5056 // the current time, which gives us more sensible behavior for
5058 $timestamp = wfTimestamp( TS_MW
, $timestamp );
5060 // The cryptic '' timezone parameter tells to use the site-default
5061 // timezone offset instead of the user settings.
5063 // Since this value will be saved into the parser cache, served
5064 // to other users, and potentially even used inside links and such,
5065 // it needs to be consistent for all visitors.
5066 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5068 wfProfileOut( __METHOD__
);
5070 return $this->mRevisionTimestamp
;
5074 * Mutator for $mDefaultSort
5076 * @param $sort New value
5078 public function setDefaultSort( $sort ) {
5079 $this->mDefaultSort
= $sort;
5083 * Accessor for $mDefaultSort
5084 * Will use the title/prefixed title if none is set
5088 public function getDefaultSort() {
5089 if( $this->mDefaultSort
!== false ) {
5090 return $this->mDefaultSort
;
5092 return $this->mTitle
->getNamespace() == NS_CATEGORY
5093 ?
$this->mTitle
->getText()
5094 : $this->mTitle
->getPrefixedText();
5099 * Try to guess the section anchor name based on a wikitext fragment
5100 * presumably extracted from a heading, for example "Header" from
5103 public function guessSectionNameFromWikiText( $text ) {
5104 # Strip out wikitext links(they break the anchor)
5105 $text = $this->stripSectionName( $text );
5106 $headline = Sanitizer
::decodeCharReferences( $text );
5108 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5109 $headline = trim( $headline );
5110 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5111 $replacearray = array(
5116 array_keys( $replacearray ),
5117 array_values( $replacearray ),
5122 * Strips a text string of wikitext for use in a section anchor
5124 * Accepts a text string and then removes all wikitext from the
5125 * string and leaves only the resultant text (i.e. the result of
5126 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5127 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5128 * to create valid section anchors by mimicing the output of the
5129 * parser when headings are parsed.
5131 * @param $text string Text string to be stripped of wikitext
5132 * for use in a Section anchor
5133 * @return Filtered text string
5135 public function stripSectionName( $text ) {
5136 # Strip internal link markup
5137 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5138 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5140 # Strip external link markup (FIXME: Not Tolerant to blank link text
5141 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5142 # on how many empty links there are on the page - need to figure that out.
5143 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5145 # Parse wikitext quotes (italics & bold)
5146 $text = $this->doQuotes($text);
5149 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5154 * strip/replaceVariables/unstrip for preprocessor regression testing
5156 function srvus( $text ) {
5157 $text = $this->replaceVariables( $text );
5158 $text = $this->mStripState
->unstripBoth( $text );
5164 * @todo document, briefly.
5165 * @addtogroup Parser
5167 class OnlyIncludeReplacer
{
5170 function replace( $matches ) {
5171 if ( substr( $matches[1], -1 ) == "\n" ) {
5172 $this->output
.= substr( $matches[1], 0, -1 );
5174 $this->output
.= $matches[1];
5180 * @todo document, briefly.
5181 * @addtogroup Parser
5184 var $general, $nowiki;
5186 function __construct() {
5187 $this->general
= new ReplacementArray
;
5188 $this->nowiki
= new ReplacementArray
;
5191 function unstripGeneral( $text ) {
5192 wfProfileIn( __METHOD__
);
5195 $text = $this->general
->replace( $text );
5196 } while ( $text != $oldText );
5197 wfProfileOut( __METHOD__
);
5201 function unstripNoWiki( $text ) {
5202 wfProfileIn( __METHOD__
);
5205 $text = $this->nowiki
->replace( $text );
5206 } while ( $text != $oldText );
5207 wfProfileOut( __METHOD__
);
5211 function unstripBoth( $text ) {
5212 wfProfileIn( __METHOD__
);
5215 $text = $this->general
->replace( $text );
5216 $text = $this->nowiki
->replace( $text );
5217 } while ( $text != $oldText );
5218 wfProfileOut( __METHOD__
);
5224 * An expansion frame, used as a context to expand the result of preprocessToDom()
5227 var $parser, $title;
5230 const NO_TEMPLATES
= 2;
5233 * Construct a new preprocessor frame.
5234 * @param Parser $parser The parent parser
5235 * @param Title $title The context title, or false if there isn't one
5237 function __construct( $parser ) {
5238 $this->parser
= $parser;
5239 $this->title
= $parser->mTitle
;
5243 * Create a new child frame
5244 * $args is optionally a DOMNodeList containing the template arguments
5246 function newChild( $args = false, $title = false ) {
5247 $assocArgs = array();
5248 if ( $title === false ) {
5249 $title = $this->title
;
5251 if ( $args !== false ) {
5253 foreach ( $args as $arg ) {
5255 $xpath = new DOMXPath( $arg->ownerDocument
);
5258 $nameNodes = $xpath->query( 'name', $arg );
5259 if ( $nameNodes->item( 0 )->hasAttributes() ) {
5260 // Numbered parameter
5261 $name = $nameNodes->item( 0 )->attributes
->getNamedItem( 'index' )->textContent
;
5264 $name = $this->expand( $nameNodes->item( 0 ) );
5267 $value = $xpath->query( 'value', $arg );
5268 $assocArgs[$name] = $value->item( 0 );
5271 return new PPTemplateFrame( $this->parser
, $this, $assocArgs, $title );
5275 * Expand a DOMNode describing a preprocessed document into plain wikitext,
5276 * using the current context
5277 * @param $root the node
5279 function expand( $root, $shallowFlags = 0, $deepFlags = 0 ) {
5280 if ( is_string( $root ) ) {
5284 if ( $this->parser
->ot
['html']
5285 && ++
$this->parser
->mPPNodeCount
> $this->parser
->mOptions
->mMaxPPNodeCount
)
5287 return $this->parser
->insertStripItem( '<!-- node-count limit exceeded -->' );
5289 $flags = $shallowFlags |
$deepFlags;
5291 if ( is_array( $root ) ) {
5293 foreach ( $root as $node ) {
5294 $s .= $this->expand( $node, 0, $deepFlags );
5296 } elseif ( $root instanceof DOMNodeList
) {
5298 foreach ( $root as $node ) {
5299 $s .= $this->expand( $node, 0, $deepFlags );
5301 } elseif ( $root instanceof DOMNode
) {
5302 if ( $root->nodeType
== XML_TEXT_NODE
) {
5303 $s = $root->nodeValue
;
5304 } elseif ( $root->nodeName
== 'template' ) {
5305 # Double-brace expansion
5306 $xpath = new DOMXPath( $root->ownerDocument
);
5307 $titles = $xpath->query( 'title', $root );
5308 $title = $titles->item( 0 );
5309 $parts = $xpath->query( 'part', $root );
5310 if ( $flags & self
::NO_TEMPLATES
) {
5311 $s = '{{' . $this->implodeWithFlags( '|', 0, $deepFlags, $title, $parts ) . '}}';
5313 $lineStart = $root->getAttribute( 'lineStart' );
5317 'lineStart' => $lineStart,
5318 'text' => 'FIXME' );
5319 $s = $this->parser
->braceSubstitution( $params, $this );
5321 } elseif ( $root->nodeName
== 'tplarg' ) {
5322 # Triple-brace expansion
5323 $xpath = new DOMXPath( $root->ownerDocument
);
5324 $titles = $xpath->query( 'title', $root );
5325 $title = $titles->item( 0 );
5326 $parts = $xpath->query( 'part', $root );
5327 if ( $flags & self
::NO_ARGS ||
$this->parser
->ot
['msg'] ) {
5328 $s = '{{{' . $this->implode( '|', 0, $deepFlags, $title, $parts ) . '}}}';
5330 $params = array( 'title' => $title, 'parts' => $parts, 'text' => 'FIXME' );
5331 $s = $this->parser
->argSubstitution( $params, $this );
5333 } elseif ( $root->nodeName
== 'ext' ) {
5335 $xpath = new DOMXPath( $root->ownerDocument
);
5336 $names = $xpath->query( 'name', $root );
5337 $attrs = $xpath->query( 'attr', $root );
5338 $inners = $xpath->query( 'inner', $root );
5339 $closes = $xpath->query( 'close', $root );
5341 'name' => $names->item( 0 ),
5342 'attr' => $attrs->length
> 0 ?
$attrs->item( 0 ) : null,
5343 'inner' => $inners->length
> 0 ?
$inners->item( 0 ) : null,
5344 'close' => $closes->length
> 0 ?
$closes->item( 0 ) : null,
5346 $s = $this->parser
->extensionSubstitution( $params, $this );
5347 } elseif ( $root->nodeName
== 'h' ) {
5349 $s = $this->expand( $root->childNodes
, 0, $deepFlags );
5351 if ( $this->parser
->ot
['html'] ) {
5352 # Insert heading index marker
5353 $headingIndex = $root->getAttribute( 'i' );
5354 $titleText = $this->title
->getPrefixedDBkey();
5355 $this->parser
->mHeadings
[] = array( $titleText, $headingIndex );
5356 $serial = count( $this->parser
->mHeadings
) - 1;
5357 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
5358 $count = $root->getAttribute( 'level' );
5360 // FIXME: bug-for-bug with old parser
5361 // Lose whitespace for no apparent reason
5362 // Remove this after differential testing is done
5365 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
5368 if ( preg_match( '/^(={1,6})(.*?)(={1,6})\s*?$/', $s, $m ) ) {
5369 if ( $m[2] != '' ) {
5370 $s = $m[1] . $marker . $m[2] . $m[3];
5374 $this->parser
->mStripState
->general
->setPair( $marker, '' );
5377 # Generic recursive expansion
5379 for ( $node = $root->firstChild
; $node; $node = $node->nextSibling
) {
5380 if ( $node->nodeType
== XML_TEXT_NODE
) {
5381 $s .= $node->nodeValue
;
5382 } elseif ( $node->nodeType
== XML_ELEMENT_NODE
) {
5383 $s .= $this->expand( $node, 0, $deepFlags );
5388 throw new MWException( __METHOD__
.': Invalid parameter type' );
5393 function implodeWithFlags( $sep, $shallowFlags, $deepFlags /*, ... */ ) {
5394 $args = array_slice( func_get_args(), 3 );
5398 foreach ( $args as $root ) {
5399 if ( !is_array( $root ) && !( $root instanceof DOMNodeList
) ) {
5400 $root = array( $root );
5402 foreach ( $root as $node ) {
5408 $s .= $this->expand( $node, $shallowFlags, $deepFlags );
5414 function implode( $sep /*, ... */ ) {
5415 $args = func_get_args();
5416 $args = array_merge( array_slice( $args, 0, 1 ), array( 0, 0 ), array_slice( $args, 1 ) );
5417 return call_user_func_array( array( $this, 'implodeWithFlags' ), $args );
5420 function __toString() {
5426 * Expansion frame with template arguments
5428 class PPTemplateFrame
extends PPFrame
{
5429 public $parser, $args, $parent, $serial;
5431 function __construct( $parser, $parent = false, $args = array(), $title = false ) {
5432 $this->parser
= $parser;
5433 $this->parent
= $parent;
5434 $this->args
= $args;
5435 $this->title
= $title;
5438 function __toString() {
5441 foreach ( $this->args
as $name => $value ) {
5447 $s .= "\"$name\":\"" .
5448 str_replace( '"', '\\"', $value->ownerDocument
->saveXML( $value ) ) . '"';